@turbobase/cli 1.1.17 → 1.1.18

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.
@@ -1,47 +1,47 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __tbCreateRequire } from 'node:module';
3
3
  const require = __tbCreateRequire(import.meta.url);
4
- var m$=Object.create;var Cc=Object.defineProperty;var g$=Object.getOwnPropertyDescriptor;var y$=Object.getOwnPropertyNames;var b$=Object.getPrototypeOf,w$=Object.prototype.hasOwnProperty;var Lo=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var O=(t,e)=>()=>(t&&(e=t(t=0)),e);var Z=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Mo=(t,e)=>{for(var r in e)Cc(t,r,{get:e[r],enumerable:!0})},_$=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of y$(e))!w$.call(t,o)&&o!==r&&Cc(t,o,{get:()=>e[o],enumerable:!(n=g$(e,o))||n.enumerable});return t};var zc=(t,e,r)=>(r=t!=null?m$(b$(t)):{},_$(e||!t||!t.__esModule?Cc(r,"default",{value:t,enumerable:!0}):r,t));var Do=Z(jc=>{var li=class extends Error{constructor(e,r,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=e,this.nestedError=void 0}},Nc=class extends li{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};jc.CommanderError=li;jc.InvalidArgumentError=Nc});var ui=Z(Mc=>{var{InvalidArgumentError:v$}=Do(),Lc=class{constructor(e,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new v$(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,n):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function x$(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}Mc.Argument=Lc;Mc.humanReadableArgName=x$});var Uc=Z(hm=>{var{humanReadableArgName:k$}=ui(),Dc=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let r=e.commands.filter(n=>!n._hidden);if(e._hasImplicitHelpCommand()){let[,n,o]=e._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/),s=e.createCommand(n).helpOption(!1);s.description(e._helpCommandDescription),o&&s.arguments(o),r.push(s)}return this.sortSubcommands&&r.sort((n,o)=>n.name().localeCompare(o.name())),r}compareOptions(e,r){let n=o=>o.short?o.short.replace(/^-/,""):o.long.replace(/^--/,"");return n(e).localeCompare(n(r))}visibleOptions(e){let r=e.options.filter(s=>!s.hidden),n=e._hasHelpOption&&e._helpShortFlag&&!e._findOption(e._helpShortFlag),o=e._hasHelpOption&&!e._findOption(e._helpLongFlag);if(n||o){let s;n?o?s=e.createOption(e._helpFlags,e._helpDescription):s=e.createOption(e._helpShortFlag,e._helpDescription):s=e.createOption(e._helpLongFlag,e._helpDescription),r.push(s)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let r=[];for(let n=e.parent;n;n=n.parent){let o=n.options.filter(s=>!s.hidden);r.push(...o)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(r=>{r.description=r.description||e._argsDescription[r.name()]||""}),e.registeredArguments.find(r=>r.description)?e.registeredArguments:[]}subcommandTerm(e){let r=e.registeredArguments.map(n=>k$(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,r){return r.visibleCommands(e).reduce((n,o)=>Math.max(n,r.subcommandTerm(o).length),0)}longestOptionTermLength(e,r){return r.visibleOptions(e).reduce((n,o)=>Math.max(n,r.optionTerm(o).length),0)}longestGlobalOptionTermLength(e,r){return r.visibleGlobalOptions(e).reduce((n,o)=>Math.max(n,r.optionTerm(o).length),0)}longestArgumentTermLength(e,r){return r.visibleArguments(e).reduce((n,o)=>Math.max(n,r.argumentTerm(o).length),0)}commandUsage(e){let r=e._name;e._aliases[0]&&(r=r+"|"+e._aliases[0]);let n="";for(let o=e.parent;o;o=o.parent)n=o.name()+" "+n;return n+r+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let r=[];return e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&r.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&r.push(`env: ${e.envVar}`),r.length>0?`${e.description} (${r.join(", ")})`:e.description}argumentDescription(e){let r=[];if(e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),r.length>0){let n=`(${r.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,r){let n=r.padWidth(e,r),o=r.helpWidth||80,s=2,i=2;function a(f,y){if(y){let v=`${f.padEnd(n+i)}${y}`;return r.wrap(v,o-s,n+i)}return f}function c(f){return f.join(`
4
+ var N$=Object.create;var Uc=Object.defineProperty;var j$=Object.getOwnPropertyDescriptor;var L$=Object.getOwnPropertyNames;var D$=Object.getPrototypeOf,M$=Object.prototype.hasOwnProperty;var Zo=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var O=(t,e)=>()=>(t&&(e=t(t=0)),e);var Z=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),qo=(t,e)=>{for(var r in e)Uc(t,r,{get:e[r],enumerable:!0})},U$=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of L$(e))!M$.call(t,o)&&o!==r&&Uc(t,o,{get:()=>e[o],enumerable:!(n=j$(e,o))||n.enumerable});return t};var Zc=(t,e,r)=>(r=t!=null?N$(D$(t)):{},U$(e||!t||!t.__esModule?Uc(r,"default",{value:t,enumerable:!0}):r,t));var Fo=Z(Fc=>{var mi=class extends Error{constructor(e,r,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=e,this.nestedError=void 0}},qc=class extends mi{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Fc.CommanderError=mi;Fc.InvalidArgumentError=qc});var gi=Z(Vc=>{var{InvalidArgumentError:Z$}=Fo(),Bc=class{constructor(e,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new Z$(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,n):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function q$(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}Vc.Argument=Bc;Vc.humanReadableArgName=q$});var Kc=Z(km=>{var{humanReadableArgName:F$}=gi(),Hc=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let r=e.commands.filter(n=>!n._hidden);if(e._hasImplicitHelpCommand()){let[,n,o]=e._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/),s=e.createCommand(n).helpOption(!1);s.description(e._helpCommandDescription),o&&s.arguments(o),r.push(s)}return this.sortSubcommands&&r.sort((n,o)=>n.name().localeCompare(o.name())),r}compareOptions(e,r){let n=o=>o.short?o.short.replace(/^-/,""):o.long.replace(/^--/,"");return n(e).localeCompare(n(r))}visibleOptions(e){let r=e.options.filter(s=>!s.hidden),n=e._hasHelpOption&&e._helpShortFlag&&!e._findOption(e._helpShortFlag),o=e._hasHelpOption&&!e._findOption(e._helpLongFlag);if(n||o){let s;n?o?s=e.createOption(e._helpFlags,e._helpDescription):s=e.createOption(e._helpShortFlag,e._helpDescription):s=e.createOption(e._helpLongFlag,e._helpDescription),r.push(s)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let r=[];for(let n=e.parent;n;n=n.parent){let o=n.options.filter(s=>!s.hidden);r.push(...o)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(r=>{r.description=r.description||e._argsDescription[r.name()]||""}),e.registeredArguments.find(r=>r.description)?e.registeredArguments:[]}subcommandTerm(e){let r=e.registeredArguments.map(n=>F$(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,r){return r.visibleCommands(e).reduce((n,o)=>Math.max(n,r.subcommandTerm(o).length),0)}longestOptionTermLength(e,r){return r.visibleOptions(e).reduce((n,o)=>Math.max(n,r.optionTerm(o).length),0)}longestGlobalOptionTermLength(e,r){return r.visibleGlobalOptions(e).reduce((n,o)=>Math.max(n,r.optionTerm(o).length),0)}longestArgumentTermLength(e,r){return r.visibleArguments(e).reduce((n,o)=>Math.max(n,r.argumentTerm(o).length),0)}commandUsage(e){let r=e._name;e._aliases[0]&&(r=r+"|"+e._aliases[0]);let n="";for(let o=e.parent;o;o=o.parent)n=o.name()+" "+n;return n+r+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let r=[];return e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&r.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&r.push(`env: ${e.envVar}`),r.length>0?`${e.description} (${r.join(", ")})`:e.description}argumentDescription(e){let r=[];if(e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),r.length>0){let n=`(${r.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,r){let n=r.padWidth(e,r),o=r.helpWidth||80,s=2,i=2;function a(f,y){if(y){let v=`${f.padEnd(n+i)}${y}`;return r.wrap(v,o-s,n+i)}return f}function c(f){return f.join(`
5
5
  `).replace(/^/gm," ".repeat(s))}let l=[`Usage: ${r.commandUsage(e)}`,""],u=r.commandDescription(e);u.length>0&&(l=l.concat([r.wrap(u,o,0),""]));let d=r.visibleArguments(e).map(f=>a(r.argumentTerm(f),r.argumentDescription(f)));d.length>0&&(l=l.concat(["Arguments:",c(d),""]));let b=r.visibleOptions(e).map(f=>a(r.optionTerm(f),r.optionDescription(f)));if(b.length>0&&(l=l.concat(["Options:",c(b),""])),this.showGlobalOptions){let f=r.visibleGlobalOptions(e).map(y=>a(r.optionTerm(y),r.optionDescription(y)));f.length>0&&(l=l.concat(["Global Options:",c(f),""]))}let m=r.visibleCommands(e).map(f=>a(r.subcommandTerm(f),r.subcommandDescription(f)));return m.length>0&&(l=l.concat(["Commands:",c(m),""])),l.join(`
6
6
  `)}padWidth(e,r){return Math.max(r.longestOptionTermLength(e,r),r.longestGlobalOptionTermLength(e,r),r.longestSubcommandTermLength(e,r),r.longestArgumentTermLength(e,r))}wrap(e,r,n,o=40){let s=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",i=new RegExp(`[\\n][${s}]+`);if(e.match(i))return e;let a=r-n;if(a<o)return e;let c=e.slice(0,n),l=e.slice(n).replace(`\r
7
7
  `,`
8
8
  `),u=" ".repeat(n),b="\\s\u200B",m=new RegExp(`
9
9
  |.{1,${a-1}}([${b}]|$)|[^${b}]+?([${b}]|$)`,"g"),f=l.match(m)||[];return c+f.map((y,v)=>y===`
10
10
  `?"":(v>0?u:"")+y.trimEnd()).join(`
11
- `)}};hm.Help=Dc});var Fc=Z(di=>{var{InvalidArgumentError:$$}=Do(),Zc=class{constructor(e,r){this.flags=e,this.description=r||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=mm(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let r=e;return typeof e=="string"&&(r={[e]:!0}),this.implied=Object.assign(this.implied||{},r),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new $$(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,n):r},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return S$(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},qc=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(r=>{r.negate?this.negativeOptions.set(r.attributeName(),r):this.positiveOptions.set(r.attributeName(),r)}),this.negativeOptions.forEach((r,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,r){let n=r.attributeName();if(!this.dualOptions.has(n))return!0;let o=this.negativeOptions.get(n).presetArg,s=o!==void 0?o:!1;return r.negate===(s===e)}};function S$(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function mm(t){let e,r,n=t.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(e=n.shift()),r=n.shift(),!e&&/^-[^-]$/.test(r)&&(e=r,r=void 0),{shortFlag:e,longFlag:r}}di.Option=Zc;di.splitOptionFlags=mm;di.DualOptions=qc});var ym=Z(gm=>{function T$(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let r=[];for(let n=0;n<=t.length;n++)r[n]=[n];for(let n=0;n<=e.length;n++)r[0][n]=n;for(let n=1;n<=e.length;n++)for(let o=1;o<=t.length;o++){let s=1;t[o-1]===e[n-1]?s=0:s=1,r[o][n]=Math.min(r[o-1][n]+1,r[o][n-1]+1,r[o-1][n-1]+s),o>1&&n>1&&t[o-1]===e[n-2]&&t[o-2]===e[n-1]&&(r[o][n]=Math.min(r[o][n],r[o-2][n-2]+1))}return r[t.length][e.length]}function E$(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let r=t.startsWith("--");r&&(t=t.slice(2),e=e.map(i=>i.slice(2)));let n=[],o=3,s=.4;return e.forEach(i=>{if(i.length<=1)return;let a=T$(t,i),c=Math.max(t.length,i.length);(c-a)/c>s&&(a<o?(o=a,n=[i]):a===o&&n.push(i))}),n.sort((i,a)=>i.localeCompare(a)),r&&(n=n.map(i=>`--${i}`)),n.length>1?`
11
+ `)}};km.Help=Hc});var Jc=Z(yi=>{var{InvalidArgumentError:B$}=Fo(),Gc=class{constructor(e,r){this.flags=e,this.description=r||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=$m(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let r=e;return typeof e=="string"&&(r={[e]:!0}),this.implied=Object.assign(this.implied||{},r),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new B$(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,n):r},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return V$(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Wc=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(r=>{r.negate?this.negativeOptions.set(r.attributeName(),r):this.positiveOptions.set(r.attributeName(),r)}),this.negativeOptions.forEach((r,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,r){let n=r.attributeName();if(!this.dualOptions.has(n))return!0;let o=this.negativeOptions.get(n).presetArg,s=o!==void 0?o:!1;return r.negate===(s===e)}};function V$(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function $m(t){let e,r,n=t.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(e=n.shift()),r=n.shift(),!e&&/^-[^-]$/.test(r)&&(e=r,r=void 0),{shortFlag:e,longFlag:r}}yi.Option=Gc;yi.splitOptionFlags=$m;yi.DualOptions=Wc});var Tm=Z(Sm=>{function H$(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let r=[];for(let n=0;n<=t.length;n++)r[n]=[n];for(let n=0;n<=e.length;n++)r[0][n]=n;for(let n=1;n<=e.length;n++)for(let o=1;o<=t.length;o++){let s=1;t[o-1]===e[n-1]?s=0:s=1,r[o][n]=Math.min(r[o-1][n]+1,r[o][n-1]+1,r[o-1][n-1]+s),o>1&&n>1&&t[o-1]===e[n-2]&&t[o-2]===e[n-1]&&(r[o][n]=Math.min(r[o][n],r[o-2][n-2]+1))}return r[t.length][e.length]}function K$(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let r=t.startsWith("--");r&&(t=t.slice(2),e=e.map(i=>i.slice(2)));let n=[],o=3,s=.4;return e.forEach(i=>{if(i.length<=1)return;let a=H$(t,i),c=Math.max(t.length,i.length);(c-a)/c>s&&(a<o?(o=a,n=[i]):a===o&&n.push(i))}),n.sort((i,a)=>i.localeCompare(a)),r&&(n=n.map(i=>`--${i}`)),n.length>1?`
12
12
  (Did you mean one of ${n.join(", ")}?)`:n.length===1?`
13
- (Did you mean ${n[0]}?)`:""}gm.suggestSimilar=E$});var km=Z(xm=>{var R$=Lo("events").EventEmitter,Bc=Lo("child_process"),gr=Lo("path"),Vc=Lo("fs"),Me=Lo("process"),{Argument:P$,humanReadableArgName:A$}=ui(),{CommanderError:Hc}=Do(),{Help:I$}=Uc(),{Option:bm,splitOptionFlags:O$,DualOptions:C$}=Fc(),{suggestSimilar:wm}=ym(),Kc=class t extends R${constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:r=>Me.stdout.write(r),writeErr:r=>Me.stderr.write(r),getOutHelpWidth:()=>Me.stdout.isTTY?Me.stdout.columns:void 0,getErrHelpWidth:()=>Me.stderr.isTTY?Me.stderr.columns:void 0,outputError:(r,n)=>n(r)},this._hidden=!1,this._hasHelpOption=!0,this._helpFlags="-h, --help",this._helpDescription="display help for command",this._helpShortFlag="-h",this._helpLongFlag="--help",this._addImplicitHelpCommand=void 0,this._helpCommandName="help",this._helpCommandnameAndArgs="help [command]",this._helpCommandDescription="display help for command",this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._hasHelpOption=e._hasHelpOption,this._helpFlags=e._helpFlags,this._helpDescription=e._helpDescription,this._helpShortFlag=e._helpShortFlag,this._helpLongFlag=e._helpLongFlag,this._helpCommandName=e._helpCommandName,this._helpCommandnameAndArgs=e._helpCommandnameAndArgs,this._helpCommandDescription=e._helpCommandDescription,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let r=this;r;r=r.parent)e.push(r);return e}command(e,r,n){let o=r,s=n;typeof o=="object"&&o!==null&&(s=o,o=null),s=s||{};let[,i,a]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(i);return o&&(c.description(o),c._executableHandler=!0),s.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(s.noHelp||s.hidden),c._executableFile=s.executableFile||null,a&&c.arguments(a),this.commands.push(c),c.parent=this,c.copyInheritedSettings(this),o?this:c}createCommand(e){return new t(e)}createHelp(){return Object.assign(new I$,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,r){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
14
- - specify the name in Command constructor or using .name()`);return r=r||{},r.isDefault&&(this._defaultCommandName=e._name),(r.noHelp||r.hidden)&&(e._hidden=!0),this.commands.push(e),e.parent=this,this}createArgument(e,r){return new P$(e,r)}argument(e,r,n,o){let s=this.createArgument(e,r);return typeof n=="function"?s.default(o).argParser(n):s.default(n),this.addArgument(s),this}arguments(e){return e.trim().split(/ +/).forEach(r=>{this.argument(r)}),this}addArgument(e){let r=this.registeredArguments.slice(-1)[0];if(r&&r.variadic)throw new Error(`only the last argument can be variadic '${r.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}addHelpCommand(e,r){return e===!1?this._addImplicitHelpCommand=!1:(this._addImplicitHelpCommand=!0,typeof e=="string"&&(this._helpCommandName=e.split(" ")[0],this._helpCommandnameAndArgs=e),this._helpCommandDescription=r||this._helpCommandDescription),this}_hasImplicitHelpCommand(){return this._addImplicitHelpCommand===void 0?this.commands.length&&!this._actionHandler&&!this._findCommand("help"):this._addImplicitHelpCommand}hook(e,r){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
15
- Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(r):this._lifeCycleHooks[e]=[r],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=r=>{if(r.code!=="commander.executeSubCommandAsync")throw r},this}_exit(e,r,n){this._exitCallback&&this._exitCallback(new Hc(e,r,n)),Me.exit(e)}action(e){let r=n=>{let o=this.registeredArguments.length,s=n.slice(0,o);return this._storeOptionsAsProperties?s[o]=this:s[o]=this.opts(),s.push(this),e.apply(this,s)};return this._actionHandler=r,this}createOption(e,r){return new bm(e,r)}_callParseArg(e,r,n,o){try{return e.parseArg(r,n)}catch(s){if(s.code==="commander.invalidArgument"){let i=`${o} ${s.message}`;this.error(i,{exitCode:s.exitCode,code:s.code})}throw s}}addOption(e){let r=e.name(),n=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");this.options.push(e);let o=(s,i,a)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);let c=this.getOptionValue(n);s!==null&&e.parseArg?s=this._callParseArg(e,s,c,i):s!==null&&e.variadic&&(s=e._concatValue(s,c)),s==null&&(e.negate?s=!1:e.isBoolean()||e.optional?s=!0:s=""),this.setOptionValueWithSource(n,s,a)};return this.on("option:"+r,s=>{let i=`error: option '${e.flags}' argument '${s}' is invalid.`;o(s,i,"cli")}),e.envVar&&this.on("optionEnv:"+r,s=>{let i=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;o(s,i,"env")}),this}_optionEx(e,r,n,o,s){if(typeof r=="object"&&r instanceof bm)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let i=this.createOption(r,n);if(i.makeOptionMandatory(!!e.mandatory),typeof o=="function")i.default(s).argParser(o);else if(o instanceof RegExp){let a=o;o=(c,l)=>{let u=a.exec(c);return u?u[0]:l},i.default(s).argParser(o)}else i.default(o);return this.addOption(i)}option(e,r,n,o){return this._optionEx({},e,r,n,o)}requiredOption(e,r,n,o){return this._optionEx({mandatory:!0},e,r,n,o)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){if(this._passThroughOptions=!!e,this.parent&&e&&!this.parent._enablePositionalOptions)throw new Error("passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)");return this}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,r){return this.setOptionValueWithSource(e,r,void 0)}setOptionValueWithSource(e,r,n){return this._storeOptionsAsProperties?this[e]=r:this._optionValues[e]=r,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let r;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(r=n.getOptionValueSource(e))}),r}_prepareUserArgs(e,r){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");r=r||{},e===void 0&&(e=Me.argv,Me.versions&&Me.versions.electron&&(r.from="electron")),this.rawArgs=e.slice();let n;switch(r.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":Me.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;default:throw new Error(`unexpected parse option { from: '${r.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,r){let n=this._prepareUserArgs(e,r);return this._parseCommand([],n),this}async parseAsync(e,r){let n=this._prepareUserArgs(e,r);return await this._parseCommand([],n),this}_executeSubCommand(e,r){r=r.slice();let n=!1,o=[".js",".ts",".tsx",".mjs",".cjs"];function s(u,d){let b=gr.resolve(u,d);if(Vc.existsSync(b))return b;if(o.includes(gr.extname(d)))return;let m=o.find(f=>Vc.existsSync(`${b}${f}`));if(m)return`${b}${m}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=Vc.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=gr.resolve(gr.dirname(u),a)}if(a){let u=s(a,i);if(!u&&!e._executableFile&&this._scriptPath){let d=gr.basename(this._scriptPath,gr.extname(this._scriptPath));d!==this._name&&(u=s(a,`${d}-${e._name}`))}i=u||i}n=o.includes(gr.extname(i));let c;Me.platform!=="win32"?n?(r.unshift(i),r=vm(Me.execArgv).concat(r),c=Bc.spawn(Me.argv[0],r,{stdio:"inherit"})):c=Bc.spawn(i,r,{stdio:"inherit"}):(r.unshift(i),r=vm(Me.execArgv).concat(r),c=Bc.spawn(Me.execPath,r,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{Me.on(d,()=>{c.killed===!1&&c.exitCode===null&&c.kill(d)})});let l=this._exitCallback;l?c.on("close",()=>{l(new Hc(Me.exitCode||0,"commander.executeSubCommandAsync","(close)"))}):c.on("close",Me.exit.bind(Me)),c.on("error",u=>{if(u.code==="ENOENT"){let d=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",b=`'${i}' does not exist
13
+ (Did you mean ${n[0]}?)`:""}Sm.suggestSimilar=K$});var Om=Z(Im=>{var G$=Zo("events").EventEmitter,Yc=Zo("child_process"),mr=Zo("path"),Xc=Zo("fs"),De=Zo("process"),{Argument:W$,humanReadableArgName:J$}=gi(),{CommanderError:Qc}=Fo(),{Help:Y$}=Kc(),{Option:Em,splitOptionFlags:X$,DualOptions:Q$}=Jc(),{suggestSimilar:Rm}=Tm(),el=class t extends G${constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:r=>De.stdout.write(r),writeErr:r=>De.stderr.write(r),getOutHelpWidth:()=>De.stdout.isTTY?De.stdout.columns:void 0,getErrHelpWidth:()=>De.stderr.isTTY?De.stderr.columns:void 0,outputError:(r,n)=>n(r)},this._hidden=!1,this._hasHelpOption=!0,this._helpFlags="-h, --help",this._helpDescription="display help for command",this._helpShortFlag="-h",this._helpLongFlag="--help",this._addImplicitHelpCommand=void 0,this._helpCommandName="help",this._helpCommandnameAndArgs="help [command]",this._helpCommandDescription="display help for command",this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._hasHelpOption=e._hasHelpOption,this._helpFlags=e._helpFlags,this._helpDescription=e._helpDescription,this._helpShortFlag=e._helpShortFlag,this._helpLongFlag=e._helpLongFlag,this._helpCommandName=e._helpCommandName,this._helpCommandnameAndArgs=e._helpCommandnameAndArgs,this._helpCommandDescription=e._helpCommandDescription,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let r=this;r;r=r.parent)e.push(r);return e}command(e,r,n){let o=r,s=n;typeof o=="object"&&o!==null&&(s=o,o=null),s=s||{};let[,i,a]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(i);return o&&(c.description(o),c._executableHandler=!0),s.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(s.noHelp||s.hidden),c._executableFile=s.executableFile||null,a&&c.arguments(a),this.commands.push(c),c.parent=this,c.copyInheritedSettings(this),o?this:c}createCommand(e){return new t(e)}createHelp(){return Object.assign(new Y$,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,r){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
14
+ - specify the name in Command constructor or using .name()`);return r=r||{},r.isDefault&&(this._defaultCommandName=e._name),(r.noHelp||r.hidden)&&(e._hidden=!0),this.commands.push(e),e.parent=this,this}createArgument(e,r){return new W$(e,r)}argument(e,r,n,o){let s=this.createArgument(e,r);return typeof n=="function"?s.default(o).argParser(n):s.default(n),this.addArgument(s),this}arguments(e){return e.trim().split(/ +/).forEach(r=>{this.argument(r)}),this}addArgument(e){let r=this.registeredArguments.slice(-1)[0];if(r&&r.variadic)throw new Error(`only the last argument can be variadic '${r.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}addHelpCommand(e,r){return e===!1?this._addImplicitHelpCommand=!1:(this._addImplicitHelpCommand=!0,typeof e=="string"&&(this._helpCommandName=e.split(" ")[0],this._helpCommandnameAndArgs=e),this._helpCommandDescription=r||this._helpCommandDescription),this}_hasImplicitHelpCommand(){return this._addImplicitHelpCommand===void 0?this.commands.length&&!this._actionHandler&&!this._findCommand("help"):this._addImplicitHelpCommand}hook(e,r){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
15
+ Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(r):this._lifeCycleHooks[e]=[r],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=r=>{if(r.code!=="commander.executeSubCommandAsync")throw r},this}_exit(e,r,n){this._exitCallback&&this._exitCallback(new Qc(e,r,n)),De.exit(e)}action(e){let r=n=>{let o=this.registeredArguments.length,s=n.slice(0,o);return this._storeOptionsAsProperties?s[o]=this:s[o]=this.opts(),s.push(this),e.apply(this,s)};return this._actionHandler=r,this}createOption(e,r){return new Em(e,r)}_callParseArg(e,r,n,o){try{return e.parseArg(r,n)}catch(s){if(s.code==="commander.invalidArgument"){let i=`${o} ${s.message}`;this.error(i,{exitCode:s.exitCode,code:s.code})}throw s}}addOption(e){let r=e.name(),n=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");this.options.push(e);let o=(s,i,a)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);let c=this.getOptionValue(n);s!==null&&e.parseArg?s=this._callParseArg(e,s,c,i):s!==null&&e.variadic&&(s=e._concatValue(s,c)),s==null&&(e.negate?s=!1:e.isBoolean()||e.optional?s=!0:s=""),this.setOptionValueWithSource(n,s,a)};return this.on("option:"+r,s=>{let i=`error: option '${e.flags}' argument '${s}' is invalid.`;o(s,i,"cli")}),e.envVar&&this.on("optionEnv:"+r,s=>{let i=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;o(s,i,"env")}),this}_optionEx(e,r,n,o,s){if(typeof r=="object"&&r instanceof Em)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let i=this.createOption(r,n);if(i.makeOptionMandatory(!!e.mandatory),typeof o=="function")i.default(s).argParser(o);else if(o instanceof RegExp){let a=o;o=(c,l)=>{let u=a.exec(c);return u?u[0]:l},i.default(s).argParser(o)}else i.default(o);return this.addOption(i)}option(e,r,n,o){return this._optionEx({},e,r,n,o)}requiredOption(e,r,n,o){return this._optionEx({mandatory:!0},e,r,n,o)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){if(this._passThroughOptions=!!e,this.parent&&e&&!this.parent._enablePositionalOptions)throw new Error("passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)");return this}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,r){return this.setOptionValueWithSource(e,r,void 0)}setOptionValueWithSource(e,r,n){return this._storeOptionsAsProperties?this[e]=r:this._optionValues[e]=r,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let r;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(r=n.getOptionValueSource(e))}),r}_prepareUserArgs(e,r){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");r=r||{},e===void 0&&(e=De.argv,De.versions&&De.versions.electron&&(r.from="electron")),this.rawArgs=e.slice();let n;switch(r.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":De.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;default:throw new Error(`unexpected parse option { from: '${r.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,r){let n=this._prepareUserArgs(e,r);return this._parseCommand([],n),this}async parseAsync(e,r){let n=this._prepareUserArgs(e,r);return await this._parseCommand([],n),this}_executeSubCommand(e,r){r=r.slice();let n=!1,o=[".js",".ts",".tsx",".mjs",".cjs"];function s(u,d){let b=mr.resolve(u,d);if(Xc.existsSync(b))return b;if(o.includes(mr.extname(d)))return;let m=o.find(f=>Xc.existsSync(`${b}${f}`));if(m)return`${b}${m}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=Xc.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=mr.resolve(mr.dirname(u),a)}if(a){let u=s(a,i);if(!u&&!e._executableFile&&this._scriptPath){let d=mr.basename(this._scriptPath,mr.extname(this._scriptPath));d!==this._name&&(u=s(a,`${d}-${e._name}`))}i=u||i}n=o.includes(mr.extname(i));let c;De.platform!=="win32"?n?(r.unshift(i),r=Am(De.execArgv).concat(r),c=Yc.spawn(De.argv[0],r,{stdio:"inherit"})):c=Yc.spawn(i,r,{stdio:"inherit"}):(r.unshift(i),r=Am(De.execArgv).concat(r),c=Yc.spawn(De.execPath,r,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{De.on(d,()=>{c.killed===!1&&c.exitCode===null&&c.kill(d)})});let l=this._exitCallback;l?c.on("close",()=>{l(new Qc(De.exitCode||0,"commander.executeSubCommandAsync","(close)"))}):c.on("close",De.exit.bind(De)),c.on("error",u=>{if(u.code==="ENOENT"){let d=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",b=`'${i}' does not exist
16
16
  - if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
17
17
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
18
- - ${d}`;throw new Error(b)}else if(u.code==="EACCES")throw new Error(`'${i}' not executable`);if(!l)Me.exit(1);else{let d=new Hc(1,"commander.executeSubCommandAsync","(error)");d.nestedError=u,l(d)}}),this.runningCommand=c}_dispatchSubcommand(e,r,n){let o=this._findCommand(e);o||this.help({error:!0});let s;return s=this._chainOrCallSubCommandHook(s,o,"preSubcommand"),s=this._chainOrCall(s,()=>{if(o._executableHandler)this._executeSubCommand(o,r.concat(n));else return o._parseCommand(r,n)}),s}_dispatchHelpCommand(e){e||this.help();let r=this._findCommand(e);return r&&!r._executableHandler&&r.help(),this._dispatchSubcommand(e,[],[this._helpLongFlag||this._helpShortFlag])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,r)=>{e.required&&this.args[r]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,o,s)=>{let i=o;if(o!==null&&n.parseArg){let a=`error: command-argument value '${o}' is invalid for argument '${n.name()}'.`;i=this._callParseArg(n,o,s,a)}return i};this._checkNumberOfArguments();let r=[];this.registeredArguments.forEach((n,o)=>{let s=n.defaultValue;n.variadic?o<this.args.length?(s=this.args.slice(o),n.parseArg&&(s=s.reduce((i,a)=>e(n,a,i),n.defaultValue))):s===void 0&&(s=[]):o<this.args.length&&(s=this.args[o],n.parseArg&&(s=e(n,s,n.defaultValue))),r[o]=s}),this.processedArgs=r}_chainOrCall(e,r){return e&&e.then&&typeof e.then=="function"?e.then(()=>r()):r()}_chainOrCallHooks(e,r){let n=e,o=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[r]!==void 0).forEach(s=>{s._lifeCycleHooks[r].forEach(i=>{o.push({hookedCommand:s,callback:i})})}),r==="postAction"&&o.reverse(),o.forEach(s=>{n=this._chainOrCall(n,()=>s.callback(s.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,r,n){let o=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(s=>{o=this._chainOrCall(o,()=>s(this,r))}),o}_parseCommand(e,r){let n=this.parseOptions(r);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),r=n.unknown,this.args=e.concat(r),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),r);if(this._hasImplicitHelpCommand()&&e[0]===this._helpCommandName)return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return _m(this,r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),_m(this,n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){o(),this._processArguments();let i;return i=this._chainOrCallHooks(i,"preAction"),i=this._chainOrCall(i,()=>this._actionHandler(this.processedArgs)),this.parent&&(i=this._chainOrCall(i,()=>{this.parent.emit(s,e,r)})),i=this._chainOrCallHooks(i,"postAction"),i}if(this.parent&&this.parent.listenerCount(s))o(),this._processArguments(),this.parent.emit(s,e,r);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,r);this.listenerCount("command:*")?this.emit("command:*",e,r):this.commands.length?this.unknownCommand():(o(),this._processArguments())}else this.commands.length?(o(),this.help({error:!0})):(o(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(r=>r._name===e||r._aliases.includes(e))}_findOption(e){return this.options.find(r=>r.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(r=>{r.mandatory&&e.getOptionValue(r.attributeName())===void 0&&e.missingMandatoryOptionValue(r)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let o=n.attributeName();return this.getOptionValue(o)===void 0?!1:this.getOptionValueSource(o)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let o=e.find(s=>n.conflictsWith.includes(s.attributeName()));o&&this._conflictingOption(n,o)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let r=[],n=[],o=r,s=e.slice();function i(c){return c.length>1&&c[0]==="-"}let a=null;for(;s.length;){let c=s.shift();if(c==="--"){o===n&&o.push(c),o.push(...s);break}if(a&&!i(c)){this.emit(`option:${a.name()}`,c);continue}if(a=null,i(c)){let l=this._findOption(c);if(l){if(l.required){let u=s.shift();u===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,u)}else if(l.optional){let u=null;s.length>0&&!i(s[0])&&(u=s.shift()),this.emit(`option:${l.name()}`,u)}else this.emit(`option:${l.name()}`);a=l.variadic?l:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let l=this._findOption(`-${c[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,c.slice(2)):(this.emit(`option:${l.name()}`),s.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){let l=c.indexOf("="),u=this._findOption(c.slice(0,l));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,c.slice(l+1));continue}}if(i(c)&&(o=n),(this._enablePositionalOptions||this._passThroughOptions)&&r.length===0&&n.length===0){if(this._findCommand(c)){r.push(c),s.length>0&&n.push(...s);break}else if(c===this._helpCommandName&&this._hasImplicitHelpCommand()){r.push(c),s.length>0&&r.push(...s);break}else if(this._defaultCommandName){n.push(c),s.length>0&&n.push(...s);break}}if(this._passThroughOptions){o.push(c),s.length>0&&o.push(...s);break}o.push(c)}return{operands:r,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},r=this.options.length;for(let n=0;n<r;n++){let o=this.options[n].attributeName();e[o]=o===this._versionOptionName?this._version:this[o]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,r)=>Object.assign(e,r.opts()),{})}error(e,r){this._outputConfiguration.outputError(`${e}
18
+ - ${d}`;throw new Error(b)}else if(u.code==="EACCES")throw new Error(`'${i}' not executable`);if(!l)De.exit(1);else{let d=new Qc(1,"commander.executeSubCommandAsync","(error)");d.nestedError=u,l(d)}}),this.runningCommand=c}_dispatchSubcommand(e,r,n){let o=this._findCommand(e);o||this.help({error:!0});let s;return s=this._chainOrCallSubCommandHook(s,o,"preSubcommand"),s=this._chainOrCall(s,()=>{if(o._executableHandler)this._executeSubCommand(o,r.concat(n));else return o._parseCommand(r,n)}),s}_dispatchHelpCommand(e){e||this.help();let r=this._findCommand(e);return r&&!r._executableHandler&&r.help(),this._dispatchSubcommand(e,[],[this._helpLongFlag||this._helpShortFlag])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,r)=>{e.required&&this.args[r]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,o,s)=>{let i=o;if(o!==null&&n.parseArg){let a=`error: command-argument value '${o}' is invalid for argument '${n.name()}'.`;i=this._callParseArg(n,o,s,a)}return i};this._checkNumberOfArguments();let r=[];this.registeredArguments.forEach((n,o)=>{let s=n.defaultValue;n.variadic?o<this.args.length?(s=this.args.slice(o),n.parseArg&&(s=s.reduce((i,a)=>e(n,a,i),n.defaultValue))):s===void 0&&(s=[]):o<this.args.length&&(s=this.args[o],n.parseArg&&(s=e(n,s,n.defaultValue))),r[o]=s}),this.processedArgs=r}_chainOrCall(e,r){return e&&e.then&&typeof e.then=="function"?e.then(()=>r()):r()}_chainOrCallHooks(e,r){let n=e,o=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[r]!==void 0).forEach(s=>{s._lifeCycleHooks[r].forEach(i=>{o.push({hookedCommand:s,callback:i})})}),r==="postAction"&&o.reverse(),o.forEach(s=>{n=this._chainOrCall(n,()=>s.callback(s.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,r,n){let o=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(s=>{o=this._chainOrCall(o,()=>s(this,r))}),o}_parseCommand(e,r){let n=this.parseOptions(r);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),r=n.unknown,this.args=e.concat(r),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),r);if(this._hasImplicitHelpCommand()&&e[0]===this._helpCommandName)return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return Pm(this,r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),Pm(this,n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){o(),this._processArguments();let i;return i=this._chainOrCallHooks(i,"preAction"),i=this._chainOrCall(i,()=>this._actionHandler(this.processedArgs)),this.parent&&(i=this._chainOrCall(i,()=>{this.parent.emit(s,e,r)})),i=this._chainOrCallHooks(i,"postAction"),i}if(this.parent&&this.parent.listenerCount(s))o(),this._processArguments(),this.parent.emit(s,e,r);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,r);this.listenerCount("command:*")?this.emit("command:*",e,r):this.commands.length?this.unknownCommand():(o(),this._processArguments())}else this.commands.length?(o(),this.help({error:!0})):(o(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(r=>r._name===e||r._aliases.includes(e))}_findOption(e){return this.options.find(r=>r.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(r=>{r.mandatory&&e.getOptionValue(r.attributeName())===void 0&&e.missingMandatoryOptionValue(r)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let o=n.attributeName();return this.getOptionValue(o)===void 0?!1:this.getOptionValueSource(o)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let o=e.find(s=>n.conflictsWith.includes(s.attributeName()));o&&this._conflictingOption(n,o)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let r=[],n=[],o=r,s=e.slice();function i(c){return c.length>1&&c[0]==="-"}let a=null;for(;s.length;){let c=s.shift();if(c==="--"){o===n&&o.push(c),o.push(...s);break}if(a&&!i(c)){this.emit(`option:${a.name()}`,c);continue}if(a=null,i(c)){let l=this._findOption(c);if(l){if(l.required){let u=s.shift();u===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,u)}else if(l.optional){let u=null;s.length>0&&!i(s[0])&&(u=s.shift()),this.emit(`option:${l.name()}`,u)}else this.emit(`option:${l.name()}`);a=l.variadic?l:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let l=this._findOption(`-${c[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,c.slice(2)):(this.emit(`option:${l.name()}`),s.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){let l=c.indexOf("="),u=this._findOption(c.slice(0,l));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,c.slice(l+1));continue}}if(i(c)&&(o=n),(this._enablePositionalOptions||this._passThroughOptions)&&r.length===0&&n.length===0){if(this._findCommand(c)){r.push(c),s.length>0&&n.push(...s);break}else if(c===this._helpCommandName&&this._hasImplicitHelpCommand()){r.push(c),s.length>0&&r.push(...s);break}else if(this._defaultCommandName){n.push(c),s.length>0&&n.push(...s);break}}if(this._passThroughOptions){o.push(c),s.length>0&&o.push(...s);break}o.push(c)}return{operands:r,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},r=this.options.length;for(let n=0;n<r;n++){let o=this.options[n].attributeName();e[o]=o===this._versionOptionName?this._version:this[o]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,r)=>Object.assign(e,r.opts()),{})}error(e,r){this._outputConfiguration.outputError(`${e}
19
19
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
20
20
  `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
21
- `),this.outputHelp({error:!0}));let n=r||{},o=n.exitCode||1,s=n.code||"commander.error";this._exit(o,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in Me.env){let r=e.attributeName();(this.getOptionValue(r)===void 0||["default","config","env"].includes(this.getOptionValueSource(r)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,Me.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new C$(this.options),r=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&r(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(o=>!r(o)).forEach(o=>{this.setOptionValueWithSource(o,n.implied[o],"implied")})})}missingArgument(e){let r=`error: missing required argument '${e}'`;this.error(r,{code:"commander.missingArgument"})}optionMissingArgument(e){let r=`error: option '${e.flags}' argument missing`;this.error(r,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let r=`error: required option '${e.flags}' not specified`;this.error(r,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,r){let n=i=>{let a=i.attributeName(),c=this.getOptionValue(a),l=this.options.find(d=>d.negate&&a===d.attributeName()),u=this.options.find(d=>!d.negate&&a===d.attributeName());return l&&(l.presetArg===void 0&&c===!1||l.presetArg!==void 0&&c===l.presetArg)?l:u||i},o=i=>{let a=n(i),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},s=`error: ${o(e)} cannot be used with ${o(r)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let r="";if(e.startsWith("--")&&this._showSuggestionAfterError){let o=[],s=this;do{let i=s.createHelp().visibleOptions(s).filter(a=>a.long).map(a=>a.long);o=o.concat(i),s=s.parent}while(s&&!s._enablePositionalOptions);r=wm(e,o)}let n=`error: unknown option '${e}'${r}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let r=this.registeredArguments.length,n=r===1?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${r} argument${n} but got ${e.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],r="";if(this._showSuggestionAfterError){let o=[];this.createHelp().visibleCommands(this).forEach(s=>{o.push(s.name()),s.alias()&&o.push(s.alias())}),r=wm(e,o)}let n=`error: unknown command '${e}'${r}`;this.error(n,{code:"commander.unknownCommand"})}version(e,r,n){if(e===void 0)return this._version;this._version=e,r=r||"-V, --version",n=n||"output the version number";let o=this.createOption(r,n);return this._versionOptionName=o.attributeName(),this.options.push(o),this.on("option:"+o.name(),()=>{this._outputConfiguration.writeOut(`${e}
22
- `),this._exit(0,"commander.version",e)}),this}description(e,r){return e===void 0&&r===void 0?this._description:(this._description=e,r&&(this._argsDescription=r),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let r=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(r=this.commands[this.commands.length-1]),e===r._name)throw new Error("Command alias can't be the same as its name");return r._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(r=>this.alias(r)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let r=this.registeredArguments.map(n=>A$(n));return[].concat(this.options.length||this._hasHelpOption?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?r:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=gr.basename(e,gr.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let r=this.createHelp();return r.helpWidth===void 0&&(r.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),r.formatHelp(this,r)}_getHelpContext(e){e=e||{};let r={error:!!e.error},n;return r.error?n=o=>this._outputConfiguration.writeErr(o):n=o=>this._outputConfiguration.writeOut(o),r.write=e.write||n,r.command=this,r}outputHelp(e){let r;typeof e=="function"&&(r=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let o=this.helpInformation(n);if(r&&(o=r(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(o),this._helpLongFlag&&this.emit(this._helpLongFlag),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",n))}helpOption(e,r){if(typeof e=="boolean")return this._hasHelpOption=e,this;this._helpFlags=e||this._helpFlags,this._helpDescription=r||this._helpDescription;let n=O$(this._helpFlags);return this._helpShortFlag=n.shortFlag,this._helpLongFlag=n.longFlag,this}help(e){this.outputHelp(e);let r=Me.exitCode||0;r===0&&e&&typeof e!="function"&&e.error&&(r=1),this._exit(r,"commander.help","(outputHelp)")}addHelpText(e,r){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
21
+ `),this.outputHelp({error:!0}));let n=r||{},o=n.exitCode||1,s=n.code||"commander.error";this._exit(o,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in De.env){let r=e.attributeName();(this.getOptionValue(r)===void 0||["default","config","env"].includes(this.getOptionValueSource(r)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,De.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Q$(this.options),r=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&r(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(o=>!r(o)).forEach(o=>{this.setOptionValueWithSource(o,n.implied[o],"implied")})})}missingArgument(e){let r=`error: missing required argument '${e}'`;this.error(r,{code:"commander.missingArgument"})}optionMissingArgument(e){let r=`error: option '${e.flags}' argument missing`;this.error(r,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let r=`error: required option '${e.flags}' not specified`;this.error(r,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,r){let n=i=>{let a=i.attributeName(),c=this.getOptionValue(a),l=this.options.find(d=>d.negate&&a===d.attributeName()),u=this.options.find(d=>!d.negate&&a===d.attributeName());return l&&(l.presetArg===void 0&&c===!1||l.presetArg!==void 0&&c===l.presetArg)?l:u||i},o=i=>{let a=n(i),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},s=`error: ${o(e)} cannot be used with ${o(r)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let r="";if(e.startsWith("--")&&this._showSuggestionAfterError){let o=[],s=this;do{let i=s.createHelp().visibleOptions(s).filter(a=>a.long).map(a=>a.long);o=o.concat(i),s=s.parent}while(s&&!s._enablePositionalOptions);r=Rm(e,o)}let n=`error: unknown option '${e}'${r}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let r=this.registeredArguments.length,n=r===1?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${r} argument${n} but got ${e.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],r="";if(this._showSuggestionAfterError){let o=[];this.createHelp().visibleCommands(this).forEach(s=>{o.push(s.name()),s.alias()&&o.push(s.alias())}),r=Rm(e,o)}let n=`error: unknown command '${e}'${r}`;this.error(n,{code:"commander.unknownCommand"})}version(e,r,n){if(e===void 0)return this._version;this._version=e,r=r||"-V, --version",n=n||"output the version number";let o=this.createOption(r,n);return this._versionOptionName=o.attributeName(),this.options.push(o),this.on("option:"+o.name(),()=>{this._outputConfiguration.writeOut(`${e}
22
+ `),this._exit(0,"commander.version",e)}),this}description(e,r){return e===void 0&&r===void 0?this._description:(this._description=e,r&&(this._argsDescription=r),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let r=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(r=this.commands[this.commands.length-1]),e===r._name)throw new Error("Command alias can't be the same as its name");return r._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(r=>this.alias(r)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let r=this.registeredArguments.map(n=>J$(n));return[].concat(this.options.length||this._hasHelpOption?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?r:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=mr.basename(e,mr.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let r=this.createHelp();return r.helpWidth===void 0&&(r.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),r.formatHelp(this,r)}_getHelpContext(e){e=e||{};let r={error:!!e.error},n;return r.error?n=o=>this._outputConfiguration.writeErr(o):n=o=>this._outputConfiguration.writeOut(o),r.write=e.write||n,r.command=this,r}outputHelp(e){let r;typeof e=="function"&&(r=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let o=this.helpInformation(n);if(r&&(o=r(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(o),this._helpLongFlag&&this.emit(this._helpLongFlag),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",n))}helpOption(e,r){if(typeof e=="boolean")return this._hasHelpOption=e,this;this._helpFlags=e||this._helpFlags,this._helpDescription=r||this._helpDescription;let n=X$(this._helpFlags);return this._helpShortFlag=n.shortFlag,this._helpLongFlag=n.longFlag,this}help(e){this.outputHelp(e);let r=De.exitCode||0;r===0&&e&&typeof e!="function"&&e.error&&(r=1),this._exit(r,"commander.help","(outputHelp)")}addHelpText(e,r){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
23
23
  Expecting one of '${n.join("', '")}'`);let o=`${e}Help`;return this.on(o,s=>{let i;typeof r=="function"?i=r({error:s.error,command:s.command}):i=r,i&&s.write(`${i}
24
- `)}),this}};function _m(t,e){t._hasHelpOption&&e.find(n=>n===t._helpLongFlag||n===t._helpShortFlag)&&(t.outputHelp(),t._exit(0,"commander.helpDisplayed","(outputHelp)"))}function vm(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let r,n="127.0.0.1",o="9229",s;return(s=e.match(/^(--inspect(-brk)?)$/))!==null?r=s[1]:(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(r=s[1],/^\d+$/.test(s[3])?o=s[3]:n=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(r=s[1],n=s[3],o=s[4]),r&&o!=="0"?`${r}=${n}:${parseInt(o)+1}`:e})}xm.Command=Kc});var Em=Z((Bt,Tm)=>{var{Argument:z$}=ui(),{Command:$m}=km(),{CommanderError:N$,InvalidArgumentError:Sm}=Do(),{Help:j$}=Uc(),{Option:L$}=Fc();Bt=Tm.exports=new $m;Bt.program=Bt;Bt.Command=$m;Bt.Option=L$;Bt.Argument=z$;Bt.Help=j$;Bt.CommanderError=N$;Bt.InvalidArgumentError=Sm;Bt.InvalidOptionArgumentError=Sm});function Uo(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var pi=O(()=>{});var ge,Wc,F,nr,Zo=O(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(ge||(ge={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Wc||(Wc={}));F=ge.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),nr=t=>{switch(typeof t){case"undefined":return F.undefined;case"string":return F.string;case"number":return Number.isNaN(t)?F.nan:F.number;case"boolean":return F.boolean;case"function":return F.function;case"bigint":return F.bigint;case"symbol":return F.symbol;case"object":return Array.isArray(t)?F.array:t===null?F.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?F.promise:typeof Map<"u"&&t instanceof Map?F.map:typeof Set<"u"&&t instanceof Set?F.set:typeof Date<"u"&&t instanceof Date?F.date:F.object;default:return F.unknown}}});var j,M$,mt,fi=O(()=>{Zo();j=ge.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),M$=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),mt=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ge.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};mt.create=t=>new mt(t)});var D$,yr,Gc=O(()=>{fi();Zo();D$=(t,e)=>{let r;switch(t.code){case j.invalid_type:t.received===F.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case j.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ge.jsonStringifyReplacer)}`;break;case j.unrecognized_keys:r=`Unrecognized key(s) in object: ${ge.joinValues(t.keys,", ")}`;break;case j.invalid_union:r="Invalid input";break;case j.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ge.joinValues(t.options)}`;break;case j.invalid_enum_value:r=`Invalid enum value. Expected ${ge.joinValues(t.options)}, received '${t.received}'`;break;case j.invalid_arguments:r="Invalid function arguments";break;case j.invalid_return_type:r="Invalid function return type";break;case j.invalid_date:r="Invalid date";break;case j.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ge.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case j.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case j.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case j.custom:r="Invalid input";break;case j.invalid_intersection_types:r="Intersection results could not be merged";break;case j.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case j.not_finite:r="Number must be finite";break;default:r=e.defaultError,ge.assertNever(t)}return{message:r}},yr=D$});function U$(t){Am=t}function Fn(){return Am}var Am,hi=O(()=>{Gc();Am=yr});function q(t,e){let r=Fn(),n=qo({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===yr?void 0:yr].filter(o=>!!o)});t.common.issues.push(n)}var qo,Z$,Qe,X,rn,st,mi,gi,Pr,Bn,Jc=O(()=>{hi();Gc();qo=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)a=l(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},Z$=[];Qe=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return X;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return X;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},X=Object.freeze({status:"aborted"}),rn=t=>({status:"dirty",value:t}),st=t=>({status:"valid",value:t}),mi=t=>t.status==="aborted",gi=t=>t.status==="dirty",Pr=t=>t.status==="valid",Bn=t=>typeof Promise<"u"&&t instanceof Promise});var Im=O(()=>{});var H,Om=O(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(H||(H={}))});function ie(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}function jm(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function oS(t){return new RegExp(`^${jm(t)}$`)}function Lm(t){let e=`${Nm}T${jm(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function sS(t,e){return!!((e==="v4"||!e)&&Y$.test(t)||(e==="v6"||!e)&&Q$.test(t))}function iS(t,e){if(!K$.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function aS(t,e){return!!((e==="v4"||!e)&&X$.test(t)||(e==="v6"||!e)&&eS.test(t))}function cS(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function Vn(t){if(t instanceof yt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=gt.create(Vn(n))}return new yt({...t._def,shape:()=>e})}else return t instanceof _r?new _r({...t._def,type:Vn(t.element)}):t instanceof gt?gt.create(Vn(t.unwrap())):t instanceof sr?sr.create(Vn(t.unwrap())):t instanceof or?or.create(t.items.map(e=>Vn(e))):t}function Xc(t,e){let r=nr(t),n=nr(e);if(t===e)return{valid:!0,data:t};if(r===F.object&&n===F.object){let o=ge.objectKeys(e),s=ge.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=Xc(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===F.array&&n===F.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=Xc(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===F.date&&n===F.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function Mm(t,e){return new hn({values:t,typeName:M.ZodEnum,...ie(e)})}function zm(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Dm(t,e={},r){return t?Ir.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=zm(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=zm(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Ir.create()}var At,Cm,ce,q$,F$,B$,V$,H$,K$,W$,G$,J$,Yc,Y$,X$,Q$,eS,tS,rS,Nm,nS,Ar,nn,on,sn,an,Hn,cn,ln,Ir,wr,Vt,Kn,_r,yt,un,br,yi,dn,or,bi,Wn,Gn,wi,pn,fn,hn,mn,Or,It,gt,sr,gn,yn,Jn,lS,Fo,Bo,bn,uS,M,dS,Um,Zm,pS,fS,qm,hS,mS,gS,yS,bS,wS,_S,vS,xS,Qc,kS,$S,SS,TS,ES,RS,PS,AS,IS,OS,CS,zS,NS,jS,LS,MS,DS,US,ZS,qS,FS,BS,VS,HS,Fm=O(()=>{fi();hi();Om();Jc();Zo();At=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Cm=(t,e)=>{if(Pr(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new mt(t.common.issues);return this._error=r,this._error}}};ce=class{get description(){return this._def.description}_getType(e){return nr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:nr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Qe,ctx:{common:e.parent.common,data:e.data,parsedType:nr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Bn(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:nr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Cm(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:nr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Pr(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Pr(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:nr(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(Bn(o)?o:Promise.resolve(o));return Cm(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:j.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new It({schema:this,typeName:M.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return gt.create(this,this._def)}nullable(){return sr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return _r.create(this)}promise(){return Or.create(this,this._def)}or(e){return un.create([this,e],this._def)}and(e){return dn.create(this,e,this._def)}transform(e){return new It({...ie(this._def),schema:this,typeName:M.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new gn({...ie(this._def),innerType:this,defaultValue:r,typeName:M.ZodDefault})}brand(){return new Fo({typeName:M.ZodBranded,type:this,...ie(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new yn({...ie(this._def),innerType:this,catchValue:r,typeName:M.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Bo.create(this,e)}readonly(){return bn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},q$=/^c[^\s-]{8,}$/i,F$=/^[0-9a-z]+$/,B$=/^[0-9A-HJKMNP-TV-Z]{26}$/i,V$=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,H$=/^[a-z0-9_-]{21}$/i,K$=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,W$=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,G$=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,J$="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Y$=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,X$=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Q$=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,eS=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,tS=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,rS=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Nm="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",nS=new RegExp(`^${Nm}$`);Ar=class t extends ce{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==F.string){let s=this._getOrReturnCtx(e);return q(s,{code:j.invalid_type,expected:F.string,received:s.parsedType}),X}let n=new Qe,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),q(o,{code:j.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),q(o,{code:j.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?q(o,{code:j.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&q(o,{code:j.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")G$.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"email",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Yc||(Yc=new RegExp(J$,"u")),Yc.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"emoji",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")V$.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"uuid",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")H$.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"nanoid",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")q$.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"cuid",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")F$.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"cuid2",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")B$.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"ulid",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),q(o,{validation:"url",code:j.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"regex",code:j.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),q(o,{code:j.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),q(o,{code:j.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),q(o,{code:j.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Lm(s).test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{code:j.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?nS.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{code:j.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?oS(s).test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{code:j.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?W$.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"duration",code:j.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?sS(e.data,s.version)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"ip",code:j.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?iS(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"jwt",code:j.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?aS(e.data,s.version)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"cidr",code:j.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?tS.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"base64",code:j.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?rS.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"base64url",code:j.invalid_string,message:s.message}),n.dirty()):ge.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:j.invalid_string,...H.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...H.errToObj(e)})}url(e){return this._addCheck({kind:"url",...H.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...H.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...H.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...H.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...H.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...H.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...H.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...H.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...H.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...H.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...H.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...H.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...H.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...H.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...H.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...H.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...H.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...H.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...H.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...H.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...H.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...H.errToObj(r)})}nonempty(e){return this.min(1,H.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Ar.create=t=>new Ar({checks:[],typeName:M.ZodString,coerce:t?.coerce??!1,...ie(t)});nn=class t extends ce{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==F.number){let s=this._getOrReturnCtx(e);return q(s,{code:j.invalid_type,expected:F.number,received:s.parsedType}),X}let n,o=new Qe;for(let s of this._def.checks)s.kind==="int"?ge.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),q(n,{code:j.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),q(n,{code:j.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),q(n,{code:j.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?cS(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),q(n,{code:j.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),q(n,{code:j.not_finite,message:s.message}),o.dirty()):ge.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,H.toString(r))}gt(e,r){return this.setLimit("min",e,!1,H.toString(r))}lte(e,r){return this.setLimit("max",e,!0,H.toString(r))}lt(e,r){return this.setLimit("max",e,!1,H.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:H.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:H.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:H.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:H.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:H.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:H.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:H.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:H.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:H.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:H.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ge.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};nn.create=t=>new nn({checks:[],typeName:M.ZodNumber,coerce:t?.coerce||!1,...ie(t)});on=class t extends ce{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==F.bigint)return this._getInvalidInput(e);let n,o=new Qe;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),q(n,{code:j.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),q(n,{code:j.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),q(n,{code:j.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ge.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return q(r,{code:j.invalid_type,expected:F.bigint,received:r.parsedType}),X}gte(e,r){return this.setLimit("min",e,!0,H.toString(r))}gt(e,r){return this.setLimit("min",e,!1,H.toString(r))}lte(e,r){return this.setLimit("max",e,!0,H.toString(r))}lt(e,r){return this.setLimit("max",e,!1,H.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:H.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:H.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:H.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:H.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:H.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:H.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};on.create=t=>new on({checks:[],typeName:M.ZodBigInt,coerce:t?.coerce??!1,...ie(t)});sn=class extends ce{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==F.boolean){let n=this._getOrReturnCtx(e);return q(n,{code:j.invalid_type,expected:F.boolean,received:n.parsedType}),X}return st(e.data)}};sn.create=t=>new sn({typeName:M.ZodBoolean,coerce:t?.coerce||!1,...ie(t)});an=class t extends ce{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==F.date){let s=this._getOrReturnCtx(e);return q(s,{code:j.invalid_type,expected:F.date,received:s.parsedType}),X}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return q(s,{code:j.invalid_date}),X}let n=new Qe,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),q(o,{code:j.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),q(o,{code:j.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ge.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:H.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:H.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};an.create=t=>new an({checks:[],coerce:t?.coerce||!1,typeName:M.ZodDate,...ie(t)});Hn=class extends ce{_parse(e){if(this._getType(e)!==F.symbol){let n=this._getOrReturnCtx(e);return q(n,{code:j.invalid_type,expected:F.symbol,received:n.parsedType}),X}return st(e.data)}};Hn.create=t=>new Hn({typeName:M.ZodSymbol,...ie(t)});cn=class extends ce{_parse(e){if(this._getType(e)!==F.undefined){let n=this._getOrReturnCtx(e);return q(n,{code:j.invalid_type,expected:F.undefined,received:n.parsedType}),X}return st(e.data)}};cn.create=t=>new cn({typeName:M.ZodUndefined,...ie(t)});ln=class extends ce{_parse(e){if(this._getType(e)!==F.null){let n=this._getOrReturnCtx(e);return q(n,{code:j.invalid_type,expected:F.null,received:n.parsedType}),X}return st(e.data)}};ln.create=t=>new ln({typeName:M.ZodNull,...ie(t)});Ir=class extends ce{constructor(){super(...arguments),this._any=!0}_parse(e){return st(e.data)}};Ir.create=t=>new Ir({typeName:M.ZodAny,...ie(t)});wr=class extends ce{constructor(){super(...arguments),this._unknown=!0}_parse(e){return st(e.data)}};wr.create=t=>new wr({typeName:M.ZodUnknown,...ie(t)});Vt=class extends ce{_parse(e){let r=this._getOrReturnCtx(e);return q(r,{code:j.invalid_type,expected:F.never,received:r.parsedType}),X}};Vt.create=t=>new Vt({typeName:M.ZodNever,...ie(t)});Kn=class extends ce{_parse(e){if(this._getType(e)!==F.undefined){let n=this._getOrReturnCtx(e);return q(n,{code:j.invalid_type,expected:F.void,received:n.parsedType}),X}return st(e.data)}};Kn.create=t=>new Kn({typeName:M.ZodVoid,...ie(t)});_r=class t extends ce{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==F.array)return q(r,{code:j.invalid_type,expected:F.array,received:r.parsedType}),X;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(q(r,{code:i?j.too_big:j.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(q(r,{code:j.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(q(r,{code:j.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new At(r,i,r.path,a)))).then(i=>Qe.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new At(r,i,r.path,a)));return Qe.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:H.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:H.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:H.toString(r)}})}nonempty(e){return this.min(1,e)}};_r.create=(t,e)=>new _r({type:t,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...ie(e)});yt=class t extends ce{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=ge.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==F.object){let l=this._getOrReturnCtx(e);return q(l,{code:j.invalid_type,expected:F.object,received:l.parsedType}),X}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Vt&&this._def.unknownKeys==="strip"))for(let l in o.data)i.includes(l)||a.push(l);let c=[];for(let l of i){let u=s[l],d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new At(o,d,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Vt){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(l==="strict")a.length>0&&(q(o,{code:j.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new At(o,d,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let d=await u.key,b=await u.value;l.push({key:d,value:b,alwaysSet:u.alwaysSet})}return l}).then(l=>Qe.mergeObjectSync(n,l)):Qe.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return H.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:H.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:M.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of ge.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of ge.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Vn(this)}partial(e){let r={};for(let n of ge.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ge.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof gt;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Mm(ge.objectKeys(this.shape))}};yt.create=(t,e)=>new yt({shape:()=>t,unknownKeys:"strip",catchall:Vt.create(),typeName:M.ZodObject,...ie(e)});yt.strictCreate=(t,e)=>new yt({shape:()=>t,unknownKeys:"strict",catchall:Vt.create(),typeName:M.ZodObject,...ie(e)});yt.lazycreate=(t,e)=>new yt({shape:t,unknownKeys:"strip",catchall:Vt.create(),typeName:M.ZodObject,...ie(e)});un=class extends ce{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new mt(a.ctx.common.issues));return q(r,{code:j.invalid_union,unionErrors:i}),X}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let l={...r,common:{...r.common,issues:[]},parent:null},u=c._parseSync({data:r.data,path:r.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new mt(c));return q(r,{code:j.invalid_union,unionErrors:a}),X}}get options(){return this._def.options}};un.create=(t,e)=>new un({options:t,typeName:M.ZodUnion,...ie(e)});br=t=>t instanceof pn?br(t.schema):t instanceof It?br(t.innerType()):t instanceof fn?[t.value]:t instanceof hn?t.options:t instanceof mn?ge.objectValues(t.enum):t instanceof gn?br(t._def.innerType):t instanceof cn?[void 0]:t instanceof ln?[null]:t instanceof gt?[void 0,...br(t.unwrap())]:t instanceof sr?[null,...br(t.unwrap())]:t instanceof Fo||t instanceof bn?br(t.unwrap()):t instanceof yn?br(t._def.innerType):[],yi=class t extends ce{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==F.object)return q(r,{code:j.invalid_type,expected:F.object,received:r.parsedType}),X;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(q(r,{code:j.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),X)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=br(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:M.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...ie(n)})}};dn=class extends ce{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(mi(s)||mi(i))return X;let a=Xc(s.value,i.value);return a.valid?((gi(s)||gi(i))&&r.dirty(),{status:r.value,value:a.data}):(q(n,{code:j.invalid_intersection_types}),X)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};dn.create=(t,e,r)=>new dn({left:t,right:e,typeName:M.ZodIntersection,...ie(r)});or=class t extends ce{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==F.array)return q(n,{code:j.invalid_type,expected:F.array,received:n.parsedType}),X;if(n.data.length<this._def.items.length)return q(n,{code:j.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),X;!this._def.rest&&n.data.length>this._def.items.length&&(q(n,{code:j.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new At(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Qe.mergeArray(r,i)):Qe.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};or.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new or({items:t,typeName:M.ZodTuple,rest:null,...ie(e)})};bi=class t extends ce{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==F.object)return q(n,{code:j.invalid_type,expected:F.object,received:n.parsedType}),X;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new At(n,a,n.path,a)),value:i._parse(new At(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Qe.mergeObjectAsync(r,o):Qe.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof ce?new t({keyType:e,valueType:r,typeName:M.ZodRecord,...ie(n)}):new t({keyType:Ar.create(),valueType:e,typeName:M.ZodRecord,...ie(r)})}},Wn=class extends ce{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==F.map)return q(n,{code:j.invalid_type,expected:F.map,received:n.parsedType}),X;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],l)=>({key:o._parse(new At(n,a,n.path,[l,"key"])),value:s._parse(new At(n,c,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return X;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return X;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}}}};Wn.create=(t,e,r)=>new Wn({valueType:e,keyType:t,typeName:M.ZodMap,...ie(r)});Gn=class t extends ce{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==F.set)return q(n,{code:j.invalid_type,expected:F.set,received:n.parsedType}),X;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(q(n,{code:j.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(q(n,{code:j.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let l=new Set;for(let u of c){if(u.status==="aborted")return X;u.status==="dirty"&&r.dirty(),l.add(u.value)}return{status:r.value,value:l}}let a=[...n.data.values()].map((c,l)=>s._parse(new At(n,c,n.path,l)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:H.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:H.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Gn.create=(t,e)=>new Gn({valueType:t,minSize:null,maxSize:null,typeName:M.ZodSet,...ie(e)});wi=class t extends ce{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==F.function)return q(r,{code:j.invalid_type,expected:F.function,received:r.parsedType}),X;function n(a,c){return qo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Fn(),yr].filter(l=>!!l),issueData:{code:j.invalid_arguments,argumentsError:c}})}function o(a,c){return qo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Fn(),yr].filter(l=>!!l),issueData:{code:j.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Or){let a=this;return st(async function(...c){let l=new mt([]),u=await a._def.args.parseAsync(c,s).catch(m=>{throw l.addIssue(n(c,m)),l}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,s).catch(m=>{throw l.addIssue(o(d,m)),l})})}else{let a=this;return st(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new mt([n(c,l.error)]);let u=Reflect.apply(i,this,l.data),d=a._def.returns.safeParse(u,s);if(!d.success)throw new mt([o(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:or.create(e).rest(wr.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||or.create([]).rest(wr.create()),returns:r||wr.create(),typeName:M.ZodFunction,...ie(n)})}},pn=class extends ce{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};pn.create=(t,e)=>new pn({getter:t,typeName:M.ZodLazy,...ie(e)});fn=class extends ce{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return q(r,{received:r.data,code:j.invalid_literal,expected:this._def.value}),X}return{status:"valid",value:e.data}}get value(){return this._def.value}};fn.create=(t,e)=>new fn({value:t,typeName:M.ZodLiteral,...ie(e)});hn=class t extends ce{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return q(r,{expected:ge.joinValues(n),received:r.parsedType,code:j.invalid_type}),X}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return q(r,{received:r.data,code:j.invalid_enum_value,options:n}),X}return st(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};hn.create=Mm;mn=class extends ce{_parse(e){let r=ge.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==F.string&&n.parsedType!==F.number){let o=ge.objectValues(r);return q(n,{expected:ge.joinValues(o),received:n.parsedType,code:j.invalid_type}),X}if(this._cache||(this._cache=new Set(ge.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ge.objectValues(r);return q(n,{received:n.data,code:j.invalid_enum_value,options:o}),X}return st(e.data)}get enum(){return this._def.values}};mn.create=(t,e)=>new mn({values:t,typeName:M.ZodNativeEnum,...ie(e)});Or=class extends ce{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==F.promise&&r.common.async===!1)return q(r,{code:j.invalid_type,expected:F.promise,received:r.parsedType}),X;let n=r.parsedType===F.promise?r.data:Promise.resolve(r.data);return st(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Or.create=(t,e)=>new Or({type:t,typeName:M.ZodPromise,...ie(e)});It=class extends ce{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===M.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{q(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return X;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?X:c.status==="dirty"?rn(c.value):r.value==="dirty"?rn(c.value):c});{if(r.value==="aborted")return X;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?X:a.status==="dirty"?rn(a.value):r.value==="dirty"?rn(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?X:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?X:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Pr(i))return X;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Pr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):X);ge.assertNever(o)}};It.create=(t,e,r)=>new It({schema:t,typeName:M.ZodEffects,effect:e,...ie(r)});It.createWithPreprocess=(t,e,r)=>new It({schema:e,effect:{type:"preprocess",transform:t},typeName:M.ZodEffects,...ie(r)});gt=class extends ce{_parse(e){return this._getType(e)===F.undefined?st(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};gt.create=(t,e)=>new gt({innerType:t,typeName:M.ZodOptional,...ie(e)});sr=class extends ce{_parse(e){return this._getType(e)===F.null?st(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};sr.create=(t,e)=>new sr({innerType:t,typeName:M.ZodNullable,...ie(e)});gn=class extends ce{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===F.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};gn.create=(t,e)=>new gn({innerType:t,typeName:M.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ie(e)});yn=class extends ce{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Bn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new mt(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new mt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};yn.create=(t,e)=>new yn({innerType:t,typeName:M.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ie(e)});Jn=class extends ce{_parse(e){if(this._getType(e)!==F.nan){let n=this._getOrReturnCtx(e);return q(n,{code:j.invalid_type,expected:F.nan,received:n.parsedType}),X}return{status:"valid",value:e.data}}};Jn.create=t=>new Jn({typeName:M.ZodNaN,...ie(t)});lS=Symbol("zod_brand"),Fo=class extends ce{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Bo=class t extends ce{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?X:s.status==="dirty"?(r.dirty(),rn(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?X:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:M.ZodPipeline})}},bn=class extends ce{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Pr(o)&&(o.value=Object.freeze(o.value)),o);return Bn(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};bn.create=(t,e)=>new bn({innerType:t,typeName:M.ZodReadonly,...ie(e)});uS={object:yt.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(M||(M={}));dS=(t,e={message:`Input not instance of ${t.name}`})=>Dm(r=>r instanceof t,e),Um=Ar.create,Zm=nn.create,pS=Jn.create,fS=on.create,qm=sn.create,hS=an.create,mS=Hn.create,gS=cn.create,yS=ln.create,bS=Ir.create,wS=wr.create,_S=Vt.create,vS=Kn.create,xS=_r.create,Qc=yt.create,kS=yt.strictCreate,$S=un.create,SS=yi.create,TS=dn.create,ES=or.create,RS=bi.create,PS=Wn.create,AS=Gn.create,IS=wi.create,OS=pn.create,CS=fn.create,zS=hn.create,NS=mn.create,jS=Or.create,LS=It.create,MS=gt.create,DS=sr.create,US=It.createWithPreprocess,ZS=Bo.create,qS=()=>Um().optional(),FS=()=>Zm().optional(),BS=()=>qm().optional(),VS={string:(t=>Ar.create({...t,coerce:!0})),number:(t=>nn.create({...t,coerce:!0})),boolean:(t=>sn.create({...t,coerce:!0})),bigint:(t=>on.create({...t,coerce:!0})),date:(t=>an.create({...t,coerce:!0}))},HS=X});var N={};Mo(N,{BRAND:()=>lS,DIRTY:()=>rn,EMPTY_PATH:()=>Z$,INVALID:()=>X,NEVER:()=>HS,OK:()=>st,ParseStatus:()=>Qe,Schema:()=>ce,ZodAny:()=>Ir,ZodArray:()=>_r,ZodBigInt:()=>on,ZodBoolean:()=>sn,ZodBranded:()=>Fo,ZodCatch:()=>yn,ZodDate:()=>an,ZodDefault:()=>gn,ZodDiscriminatedUnion:()=>yi,ZodEffects:()=>It,ZodEnum:()=>hn,ZodError:()=>mt,ZodFirstPartyTypeKind:()=>M,ZodFunction:()=>wi,ZodIntersection:()=>dn,ZodIssueCode:()=>j,ZodLazy:()=>pn,ZodLiteral:()=>fn,ZodMap:()=>Wn,ZodNaN:()=>Jn,ZodNativeEnum:()=>mn,ZodNever:()=>Vt,ZodNull:()=>ln,ZodNullable:()=>sr,ZodNumber:()=>nn,ZodObject:()=>yt,ZodOptional:()=>gt,ZodParsedType:()=>F,ZodPipeline:()=>Bo,ZodPromise:()=>Or,ZodReadonly:()=>bn,ZodRecord:()=>bi,ZodSchema:()=>ce,ZodSet:()=>Gn,ZodString:()=>Ar,ZodSymbol:()=>Hn,ZodTransformer:()=>It,ZodTuple:()=>or,ZodType:()=>ce,ZodUndefined:()=>cn,ZodUnion:()=>un,ZodUnknown:()=>wr,ZodVoid:()=>Kn,addIssueToContext:()=>q,any:()=>bS,array:()=>xS,bigint:()=>fS,boolean:()=>qm,coerce:()=>VS,custom:()=>Dm,date:()=>hS,datetimeRegex:()=>Lm,defaultErrorMap:()=>yr,discriminatedUnion:()=>SS,effect:()=>LS,enum:()=>zS,function:()=>IS,getErrorMap:()=>Fn,getParsedType:()=>nr,instanceof:()=>dS,intersection:()=>TS,isAborted:()=>mi,isAsync:()=>Bn,isDirty:()=>gi,isValid:()=>Pr,late:()=>uS,lazy:()=>OS,literal:()=>CS,makeIssue:()=>qo,map:()=>PS,nan:()=>pS,nativeEnum:()=>NS,never:()=>_S,null:()=>yS,nullable:()=>DS,number:()=>Zm,object:()=>Qc,objectUtil:()=>Wc,oboolean:()=>BS,onumber:()=>FS,optional:()=>MS,ostring:()=>qS,pipeline:()=>ZS,preprocess:()=>US,promise:()=>jS,quotelessJson:()=>M$,record:()=>RS,set:()=>AS,setErrorMap:()=>U$,strictObject:()=>kS,string:()=>Um,symbol:()=>mS,transformer:()=>LS,tuple:()=>ES,undefined:()=>gS,union:()=>$S,unknown:()=>wS,util:()=>ge,void:()=>vS});var _i=O(()=>{hi();Jc();Im();Zo();Fm();fi()});var Yn=O(()=>{_i();_i()});function vi(t){let e=el.safeParse(t);return e.success?(e.data.inputs??[]).filter(r=>r.type==="connection"):[]}function tl(t,e){let r=el.safeParse(t);if(!r.success)throw new Cr(`invalid manifest: ${r.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}`);if(Bm.test(e))throw new Cr('a literal connection_id is baked into the bundle source \u2014 connection binding is an install-time input, not a published value. Declare an inputs[] entry { type: "connection", source_system } instead.');let n=JSON.stringify(r.data);if(Bm.test(n))throw new Cr("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var Vm,Hm,el,Cr,Bm,Km=O(()=>{Yn();Vm=N.object({type:N.literal("connection"),source_system:N.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:N.string().min(1).max(200).optional()}),Hm=N.discriminatedUnion("type",[Vm]),el=N.object({inputs:N.array(Hm).optional()}).passthrough(),Cr=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};Bm=/\bconnection[_-]?id\b["']?\s*[:=]/i});var xi,rl=O(()=>{xi=["before_read","before_save","after_save","before_sync","after_sync","on_sync_failure"]});var nl,Wm,Gm=O(()=>{Yn();pi();rl();nl=N.object({id:N.string().min(1,"hook id must be non-empty"),recordType:N.union([N.string().min(1),N.array(N.string().min(1)).min(1),N.literal("*")]),event:N.enum(xi),source:N.string().min(1).optional(),when:N.unknown().optional(),run:N.unknown(),failClosed:N.boolean().optional(),timeoutMs:N.number().int().positive().optional(),description:N.string().optional(),systemReserved:N.boolean().optional()}).superRefine((t,e)=>{typeof t.run!="function"&&e.addIssue({code:"custom",path:["run"],message:"run must be a function"}),"when"in t&&t.when!==void 0&&typeof t.when!="function"&&e.addIssue({code:"custom",path:["when"],message:"when, when present, must be a function"})}),Wm=Uo({kind:"hook",schema:nl,factoryName:"defineHook"})});var Jm=O(()=>{Gm();rl()});var ki,ol=O(()=>{ki=["after_canonicalize_inbound","after_sync_success_outbound"]});var sl,Ym,Xm=O(()=>{Yn();pi();ol();sl=N.object({id:N.string().min(1,"conduit id must be non-empty"),on:N.enum(ki),from:N.object({source:N.string().min(1,"from.source must be non-empty"),recordType:N.string().min(1,"from.recordType must be non-empty"),when:N.unknown().optional()}),to:N.object({source:N.string().min(1,"to.source must be non-empty"),recordType:N.string().min(1,"to.recordType must be non-empty")}),mode:N.enum(["dual-bind","one-shot"]).optional(),transform:N.unknown(),idempotencyKey:N.unknown().optional(),cycleBudget:N.number().int().positive().optional(),conflictStrategy:N.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:N.number().int().positive().optional(),description:N.string().optional(),systemReserved:N.boolean().optional()}).superRefine((t,e)=>{typeof t.transform!="function"&&e.addIssue({code:"custom",path:["transform"],message:"transform must be a function"});let r=t.from?.when;r!==void 0&&typeof r!="function"&&e.addIssue({code:"custom",path:["from","when"],message:"from.when, when present, must be a function"});let n=t.idempotencyKey;n!==void 0&&typeof n!="function"&&e.addIssue({code:"custom",path:["idempotencyKey"],message:"idempotencyKey, when present, must be a function"});let o=t.from,s=t.to;o?.source&&s?.source&&o.source===s.source&&e.addIssue({code:"custom",path:["to","source"],message:"a conduit must bridge two DIFFERENT sources (from.source === to.source) \u2014 use a hook for an intra-source transform"})}),Ym=Uo({kind:"conduit",schema:sl,factoryName:"defineConduit"})});var Qm=O(()=>{Xm();ol()});async function YS(t){let e;try{e=await import("openapi-typescript")}catch{throw new Error("types-gen: 'openapi-typescript' is not installed. Add it to the environment running `turbobase project types`, or pass a `transform` override to generateTypes().")}let r=await e.default(t,{defaultNonNullable:!1});return e.astToString(r)}async function $i(t,e={}){return(e.transform??YS)(t)}var il=O(()=>{});function al(t){switch(t.toLowerCase().trim()){case"boolean":return"boolean";case"smallint":case"integer":case"bigint":case"numeric":case"decimal":case"real":case"double precision":return"number";case"text":case"character varying":case"character":case"varchar":case"char":case"uuid":case"name":case"citext":return"string";case"timestamp with time zone":case"timestamp without time zone":case"timestamp":case"date":case"time":case"time with time zone":case"time without time zone":return"string";case"json":case"jsonb":return"unknown";case"array":return"unknown[]";default:return"unknown"}}function eg(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function cl(t){return`${eg(t.source)}${eg(t.recordType)}`}function XS(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function QS(t){let e=[t.pgType];return t.label&&e.push(`"${t.label}"`),t.role==="display"&&t.displayFor?e.push(`display column for ${t.displayFor} \u2014 render this, filter/join on ${t.displayFor}`):t.role==="identifier"&&t.idFor?e.push(`identifier \u2014 render ${t.idFor} instead`):t.role&&e.push(t.role),t.format&&e.push(`format: ${t.format}`),t.description&&e.push(t.description),e.join(" \xB7 ")}function ll(t){let e=cl(t),r=[`${t.source}:${t.recordType}`+(t.table?` \u2192 turbobase.${t.table}`:" (no backing table)")+`${t.listOnly?" (list-only)":""} \u2014 origin: ${t.origin}.`];t.description&&r.push(t.description);let n=r.length===1?`/** ${r[0]} */`:`/**
24
+ `)}),this}};function Pm(t,e){t._hasHelpOption&&e.find(n=>n===t._helpLongFlag||n===t._helpShortFlag)&&(t.outputHelp(),t._exit(0,"commander.helpDisplayed","(outputHelp)"))}function Am(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let r,n="127.0.0.1",o="9229",s;return(s=e.match(/^(--inspect(-brk)?)$/))!==null?r=s[1]:(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(r=s[1],/^\d+$/.test(s[3])?o=s[3]:n=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(r=s[1],n=s[3],o=s[4]),r&&o!=="0"?`${r}=${n}:${parseInt(o)+1}`:e})}Im.Command=el});var jm=Z((Ht,Nm)=>{var{Argument:eS}=gi(),{Command:Cm}=Om(),{CommanderError:tS,InvalidArgumentError:zm}=Fo(),{Help:rS}=Kc(),{Option:nS}=Jc();Ht=Nm.exports=new Cm;Ht.program=Ht;Ht.Command=Cm;Ht.Option=nS;Ht.Argument=eS;Ht.Help=rS;Ht.CommanderError=tS;Ht.InvalidArgumentError=zm;Ht.InvalidOptionArgumentError=zm});function Bo(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var bi=O(()=>{});var ye,tl,F,or,Vo=O(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(ye||(ye={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(tl||(tl={}));F=ye.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),or=t=>{switch(typeof t){case"undefined":return F.undefined;case"string":return F.string;case"number":return Number.isNaN(t)?F.nan:F.number;case"boolean":return F.boolean;case"function":return F.function;case"bigint":return F.bigint;case"symbol":return F.symbol;case"object":return Array.isArray(t)?F.array:t===null?F.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?F.promise:typeof Map<"u"&&t instanceof Map?F.map:typeof Set<"u"&&t instanceof Set?F.set:typeof Date<"u"&&t instanceof Date?F.date:F.object;default:return F.unknown}}});var j,oS,gt,wi=O(()=>{Vo();j=ye.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),oS=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),gt=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ye.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};gt.create=t=>new gt(t)});var sS,gr,rl=O(()=>{wi();Vo();sS=(t,e)=>{let r;switch(t.code){case j.invalid_type:t.received===F.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case j.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ye.jsonStringifyReplacer)}`;break;case j.unrecognized_keys:r=`Unrecognized key(s) in object: ${ye.joinValues(t.keys,", ")}`;break;case j.invalid_union:r="Invalid input";break;case j.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ye.joinValues(t.options)}`;break;case j.invalid_enum_value:r=`Invalid enum value. Expected ${ye.joinValues(t.options)}, received '${t.received}'`;break;case j.invalid_arguments:r="Invalid function arguments";break;case j.invalid_return_type:r="Invalid function return type";break;case j.invalid_date:r="Invalid date";break;case j.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ye.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case j.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case j.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case j.custom:r="Invalid input";break;case j.invalid_intersection_types:r="Intersection results could not be merged";break;case j.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case j.not_finite:r="Number must be finite";break;default:r=e.defaultError,ye.assertNever(t)}return{message:r}},gr=sS});function iS(t){Mm=t}function qn(){return Mm}var Mm,_i=O(()=>{rl();Mm=gr});function q(t,e){let r=qn(),n=Ho({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===gr?void 0:gr].filter(o=>!!o)});t.common.issues.push(n)}var Ho,aS,et,ee,on,it,vi,xi,Ar,Fn,nl=O(()=>{_i();rl();Ho=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)a=l(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},aS=[];et=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return ee;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return ee;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},ee=Object.freeze({status:"aborted"}),on=t=>({status:"dirty",value:t}),it=t=>({status:"valid",value:t}),vi=t=>t.status==="aborted",xi=t=>t.status==="dirty",Ar=t=>t.status==="valid",Fn=t=>typeof Promise<"u"&&t instanceof Promise});var Um=O(()=>{});var K,Zm=O(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(K||(K={}))});function ce(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}function Vm(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function $S(t){return new RegExp(`^${Vm(t)}$`)}function Hm(t){let e=`${Bm}T${Vm(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function SS(t,e){return!!((e==="v4"||!e)&&yS.test(t)||(e==="v6"||!e)&&wS.test(t))}function TS(t,e){if(!fS.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function ES(t,e){return!!((e==="v4"||!e)&&bS.test(t)||(e==="v6"||!e)&&_S.test(t))}function RS(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function Bn(t){if(t instanceof bt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=yt.create(Bn(n))}return new bt({...t._def,shape:()=>e})}else return t instanceof wr?new wr({...t._def,type:Bn(t.element)}):t instanceof yt?yt.create(Bn(t.unwrap())):t instanceof ir?ir.create(Bn(t.unwrap())):t instanceof sr?sr.create(t.items.map(e=>Bn(e))):t}function sl(t,e){let r=or(t),n=or(e);if(t===e)return{valid:!0,data:t};if(r===F.object&&n===F.object){let o=ye.objectKeys(e),s=ye.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=sl(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===F.array&&n===F.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=sl(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===F.date&&n===F.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function Km(t,e){return new gn({values:t,typeName:D.ZodEnum,...ce(e)})}function Fm(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Gm(t,e={},r){return t?Or.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Fm(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Fm(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Or.create()}var Ot,qm,de,cS,lS,uS,dS,pS,fS,hS,mS,gS,ol,yS,bS,wS,_S,vS,xS,Bm,kS,Ir,sn,an,cn,ln,Vn,un,dn,Or,br,Kt,Hn,wr,bt,pn,yr,ki,fn,sr,$i,Kn,Gn,Si,hn,mn,gn,yn,Cr,Ct,yt,ir,bn,wn,Wn,PS,Ko,Go,_n,AS,D,IS,Wm,Jm,OS,CS,Ym,zS,NS,jS,LS,DS,MS,US,ZS,qS,il,FS,BS,VS,HS,KS,GS,WS,JS,YS,XS,QS,eT,tT,rT,nT,oT,sT,iT,aT,cT,lT,uT,dT,pT,Xm=O(()=>{wi();_i();Zm();nl();Vo();Ot=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},qm=(t,e)=>{if(Ar(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new gt(t.common.issues);return this._error=r,this._error}}};de=class{get description(){return this._def.description}_getType(e){return or(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:or(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new et,ctx:{common:e.parent.common,data:e.data,parsedType:or(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Fn(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:or(e)},o=this._parseSync({data:e,path:n.path,parent:n});return qm(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:or(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Ar(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Ar(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:or(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(Fn(o)?o:Promise.resolve(o));return qm(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:j.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new Ct({schema:this,typeName:D.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return yt.create(this,this._def)}nullable(){return ir.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return wr.create(this)}promise(){return Cr.create(this,this._def)}or(e){return pn.create([this,e],this._def)}and(e){return fn.create(this,e,this._def)}transform(e){return new Ct({...ce(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new bn({...ce(this._def),innerType:this,defaultValue:r,typeName:D.ZodDefault})}brand(){return new Ko({typeName:D.ZodBranded,type:this,...ce(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new wn({...ce(this._def),innerType:this,catchValue:r,typeName:D.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Go.create(this,e)}readonly(){return _n.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},cS=/^c[^\s-]{8,}$/i,lS=/^[0-9a-z]+$/,uS=/^[0-9A-HJKMNP-TV-Z]{26}$/i,dS=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,pS=/^[a-z0-9_-]{21}$/i,fS=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,hS=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,mS=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,gS="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",yS=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,bS=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,wS=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,_S=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,vS=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,xS=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Bm="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",kS=new RegExp(`^${Bm}$`);Ir=class t extends de{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==F.string){let s=this._getOrReturnCtx(e);return q(s,{code:j.invalid_type,expected:F.string,received:s.parsedType}),ee}let n=new et,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),q(o,{code:j.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),q(o,{code:j.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?q(o,{code:j.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&q(o,{code:j.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")mS.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"email",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")ol||(ol=new RegExp(gS,"u")),ol.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"emoji",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")dS.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"uuid",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")pS.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"nanoid",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")cS.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"cuid",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")lS.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"cuid2",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")uS.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"ulid",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),q(o,{validation:"url",code:j.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"regex",code:j.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),q(o,{code:j.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),q(o,{code:j.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),q(o,{code:j.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Hm(s).test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{code:j.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?kS.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{code:j.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?$S(s).test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{code:j.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?hS.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"duration",code:j.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?SS(e.data,s.version)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"ip",code:j.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?TS(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"jwt",code:j.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?ES(e.data,s.version)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"cidr",code:j.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?vS.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"base64",code:j.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?xS.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"base64url",code:j.invalid_string,message:s.message}),n.dirty()):ye.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:j.invalid_string,...K.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...K.errToObj(e)})}url(e){return this._addCheck({kind:"url",...K.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...K.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...K.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...K.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...K.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...K.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...K.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...K.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...K.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...K.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...K.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...K.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...K.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...K.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...K.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...K.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...K.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...K.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...K.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...K.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...K.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...K.errToObj(r)})}nonempty(e){return this.min(1,K.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Ir.create=t=>new Ir({checks:[],typeName:D.ZodString,coerce:t?.coerce??!1,...ce(t)});sn=class t extends de{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==F.number){let s=this._getOrReturnCtx(e);return q(s,{code:j.invalid_type,expected:F.number,received:s.parsedType}),ee}let n,o=new et;for(let s of this._def.checks)s.kind==="int"?ye.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),q(n,{code:j.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),q(n,{code:j.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),q(n,{code:j.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?RS(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),q(n,{code:j.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),q(n,{code:j.not_finite,message:s.message}),o.dirty()):ye.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,K.toString(r))}gt(e,r){return this.setLimit("min",e,!1,K.toString(r))}lte(e,r){return this.setLimit("max",e,!0,K.toString(r))}lt(e,r){return this.setLimit("max",e,!1,K.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:K.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:K.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:K.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:K.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:K.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:K.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:K.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:K.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:K.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:K.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ye.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};sn.create=t=>new sn({checks:[],typeName:D.ZodNumber,coerce:t?.coerce||!1,...ce(t)});an=class t extends de{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==F.bigint)return this._getInvalidInput(e);let n,o=new et;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),q(n,{code:j.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),q(n,{code:j.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),q(n,{code:j.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ye.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return q(r,{code:j.invalid_type,expected:F.bigint,received:r.parsedType}),ee}gte(e,r){return this.setLimit("min",e,!0,K.toString(r))}gt(e,r){return this.setLimit("min",e,!1,K.toString(r))}lte(e,r){return this.setLimit("max",e,!0,K.toString(r))}lt(e,r){return this.setLimit("max",e,!1,K.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:K.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:K.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:K.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:K.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:K.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:K.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};an.create=t=>new an({checks:[],typeName:D.ZodBigInt,coerce:t?.coerce??!1,...ce(t)});cn=class extends de{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==F.boolean){let n=this._getOrReturnCtx(e);return q(n,{code:j.invalid_type,expected:F.boolean,received:n.parsedType}),ee}return it(e.data)}};cn.create=t=>new cn({typeName:D.ZodBoolean,coerce:t?.coerce||!1,...ce(t)});ln=class t extends de{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==F.date){let s=this._getOrReturnCtx(e);return q(s,{code:j.invalid_type,expected:F.date,received:s.parsedType}),ee}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return q(s,{code:j.invalid_date}),ee}let n=new et,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),q(o,{code:j.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),q(o,{code:j.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ye.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:K.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:K.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};ln.create=t=>new ln({checks:[],coerce:t?.coerce||!1,typeName:D.ZodDate,...ce(t)});Vn=class extends de{_parse(e){if(this._getType(e)!==F.symbol){let n=this._getOrReturnCtx(e);return q(n,{code:j.invalid_type,expected:F.symbol,received:n.parsedType}),ee}return it(e.data)}};Vn.create=t=>new Vn({typeName:D.ZodSymbol,...ce(t)});un=class extends de{_parse(e){if(this._getType(e)!==F.undefined){let n=this._getOrReturnCtx(e);return q(n,{code:j.invalid_type,expected:F.undefined,received:n.parsedType}),ee}return it(e.data)}};un.create=t=>new un({typeName:D.ZodUndefined,...ce(t)});dn=class extends de{_parse(e){if(this._getType(e)!==F.null){let n=this._getOrReturnCtx(e);return q(n,{code:j.invalid_type,expected:F.null,received:n.parsedType}),ee}return it(e.data)}};dn.create=t=>new dn({typeName:D.ZodNull,...ce(t)});Or=class extends de{constructor(){super(...arguments),this._any=!0}_parse(e){return it(e.data)}};Or.create=t=>new Or({typeName:D.ZodAny,...ce(t)});br=class extends de{constructor(){super(...arguments),this._unknown=!0}_parse(e){return it(e.data)}};br.create=t=>new br({typeName:D.ZodUnknown,...ce(t)});Kt=class extends de{_parse(e){let r=this._getOrReturnCtx(e);return q(r,{code:j.invalid_type,expected:F.never,received:r.parsedType}),ee}};Kt.create=t=>new Kt({typeName:D.ZodNever,...ce(t)});Hn=class extends de{_parse(e){if(this._getType(e)!==F.undefined){let n=this._getOrReturnCtx(e);return q(n,{code:j.invalid_type,expected:F.void,received:n.parsedType}),ee}return it(e.data)}};Hn.create=t=>new Hn({typeName:D.ZodVoid,...ce(t)});wr=class t extends de{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==F.array)return q(r,{code:j.invalid_type,expected:F.array,received:r.parsedType}),ee;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(q(r,{code:i?j.too_big:j.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(q(r,{code:j.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(q(r,{code:j.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new Ot(r,i,r.path,a)))).then(i=>et.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new Ot(r,i,r.path,a)));return et.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:K.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:K.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:K.toString(r)}})}nonempty(e){return this.min(1,e)}};wr.create=(t,e)=>new wr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...ce(e)});bt=class t extends de{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=ye.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==F.object){let l=this._getOrReturnCtx(e);return q(l,{code:j.invalid_type,expected:F.object,received:l.parsedType}),ee}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Kt&&this._def.unknownKeys==="strip"))for(let l in o.data)i.includes(l)||a.push(l);let c=[];for(let l of i){let u=s[l],d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Ot(o,d,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Kt){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(l==="strict")a.length>0&&(q(o,{code:j.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Ot(o,d,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let d=await u.key,b=await u.value;l.push({key:d,value:b,alwaysSet:u.alwaysSet})}return l}).then(l=>et.mergeObjectSync(n,l)):et.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return K.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:K.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:D.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of ye.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of ye.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Bn(this)}partial(e){let r={};for(let n of ye.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ye.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof yt;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Km(ye.objectKeys(this.shape))}};bt.create=(t,e)=>new bt({shape:()=>t,unknownKeys:"strip",catchall:Kt.create(),typeName:D.ZodObject,...ce(e)});bt.strictCreate=(t,e)=>new bt({shape:()=>t,unknownKeys:"strict",catchall:Kt.create(),typeName:D.ZodObject,...ce(e)});bt.lazycreate=(t,e)=>new bt({shape:t,unknownKeys:"strip",catchall:Kt.create(),typeName:D.ZodObject,...ce(e)});pn=class extends de{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new gt(a.ctx.common.issues));return q(r,{code:j.invalid_union,unionErrors:i}),ee}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let l={...r,common:{...r.common,issues:[]},parent:null},u=c._parseSync({data:r.data,path:r.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new gt(c));return q(r,{code:j.invalid_union,unionErrors:a}),ee}}get options(){return this._def.options}};pn.create=(t,e)=>new pn({options:t,typeName:D.ZodUnion,...ce(e)});yr=t=>t instanceof hn?yr(t.schema):t instanceof Ct?yr(t.innerType()):t instanceof mn?[t.value]:t instanceof gn?t.options:t instanceof yn?ye.objectValues(t.enum):t instanceof bn?yr(t._def.innerType):t instanceof un?[void 0]:t instanceof dn?[null]:t instanceof yt?[void 0,...yr(t.unwrap())]:t instanceof ir?[null,...yr(t.unwrap())]:t instanceof Ko||t instanceof _n?yr(t.unwrap()):t instanceof wn?yr(t._def.innerType):[],ki=class t extends de{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==F.object)return q(r,{code:j.invalid_type,expected:F.object,received:r.parsedType}),ee;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(q(r,{code:j.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),ee)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=yr(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:D.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...ce(n)})}};fn=class extends de{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(vi(s)||vi(i))return ee;let a=sl(s.value,i.value);return a.valid?((xi(s)||xi(i))&&r.dirty(),{status:r.value,value:a.data}):(q(n,{code:j.invalid_intersection_types}),ee)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};fn.create=(t,e,r)=>new fn({left:t,right:e,typeName:D.ZodIntersection,...ce(r)});sr=class t extends de{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==F.array)return q(n,{code:j.invalid_type,expected:F.array,received:n.parsedType}),ee;if(n.data.length<this._def.items.length)return q(n,{code:j.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ee;!this._def.rest&&n.data.length>this._def.items.length&&(q(n,{code:j.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Ot(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>et.mergeArray(r,i)):et.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};sr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new sr({items:t,typeName:D.ZodTuple,rest:null,...ce(e)})};$i=class t extends de{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==F.object)return q(n,{code:j.invalid_type,expected:F.object,received:n.parsedType}),ee;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new Ot(n,a,n.path,a)),value:i._parse(new Ot(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?et.mergeObjectAsync(r,o):et.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof de?new t({keyType:e,valueType:r,typeName:D.ZodRecord,...ce(n)}):new t({keyType:Ir.create(),valueType:e,typeName:D.ZodRecord,...ce(r)})}},Kn=class extends de{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==F.map)return q(n,{code:j.invalid_type,expected:F.map,received:n.parsedType}),ee;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],l)=>({key:o._parse(new Ot(n,a,n.path,[l,"key"])),value:s._parse(new Ot(n,c,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return ee;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return ee;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}}}};Kn.create=(t,e,r)=>new Kn({valueType:e,keyType:t,typeName:D.ZodMap,...ce(r)});Gn=class t extends de{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==F.set)return q(n,{code:j.invalid_type,expected:F.set,received:n.parsedType}),ee;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(q(n,{code:j.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(q(n,{code:j.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let l=new Set;for(let u of c){if(u.status==="aborted")return ee;u.status==="dirty"&&r.dirty(),l.add(u.value)}return{status:r.value,value:l}}let a=[...n.data.values()].map((c,l)=>s._parse(new Ot(n,c,n.path,l)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:K.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:K.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Gn.create=(t,e)=>new Gn({valueType:t,minSize:null,maxSize:null,typeName:D.ZodSet,...ce(e)});Si=class t extends de{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==F.function)return q(r,{code:j.invalid_type,expected:F.function,received:r.parsedType}),ee;function n(a,c){return Ho({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,qn(),gr].filter(l=>!!l),issueData:{code:j.invalid_arguments,argumentsError:c}})}function o(a,c){return Ho({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,qn(),gr].filter(l=>!!l),issueData:{code:j.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Cr){let a=this;return it(async function(...c){let l=new gt([]),u=await a._def.args.parseAsync(c,s).catch(m=>{throw l.addIssue(n(c,m)),l}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,s).catch(m=>{throw l.addIssue(o(d,m)),l})})}else{let a=this;return it(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new gt([n(c,l.error)]);let u=Reflect.apply(i,this,l.data),d=a._def.returns.safeParse(u,s);if(!d.success)throw new gt([o(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:sr.create(e).rest(br.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||sr.create([]).rest(br.create()),returns:r||br.create(),typeName:D.ZodFunction,...ce(n)})}},hn=class extends de{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};hn.create=(t,e)=>new hn({getter:t,typeName:D.ZodLazy,...ce(e)});mn=class extends de{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return q(r,{received:r.data,code:j.invalid_literal,expected:this._def.value}),ee}return{status:"valid",value:e.data}}get value(){return this._def.value}};mn.create=(t,e)=>new mn({value:t,typeName:D.ZodLiteral,...ce(e)});gn=class t extends de{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return q(r,{expected:ye.joinValues(n),received:r.parsedType,code:j.invalid_type}),ee}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return q(r,{received:r.data,code:j.invalid_enum_value,options:n}),ee}return it(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};gn.create=Km;yn=class extends de{_parse(e){let r=ye.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==F.string&&n.parsedType!==F.number){let o=ye.objectValues(r);return q(n,{expected:ye.joinValues(o),received:n.parsedType,code:j.invalid_type}),ee}if(this._cache||(this._cache=new Set(ye.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ye.objectValues(r);return q(n,{received:n.data,code:j.invalid_enum_value,options:o}),ee}return it(e.data)}get enum(){return this._def.values}};yn.create=(t,e)=>new yn({values:t,typeName:D.ZodNativeEnum,...ce(e)});Cr=class extends de{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==F.promise&&r.common.async===!1)return q(r,{code:j.invalid_type,expected:F.promise,received:r.parsedType}),ee;let n=r.parsedType===F.promise?r.data:Promise.resolve(r.data);return it(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Cr.create=(t,e)=>new Cr({type:t,typeName:D.ZodPromise,...ce(e)});Ct=class extends de{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{q(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return ee;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?ee:c.status==="dirty"?on(c.value):r.value==="dirty"?on(c.value):c});{if(r.value==="aborted")return ee;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?ee:a.status==="dirty"?on(a.value):r.value==="dirty"?on(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?ee:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?ee:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Ar(i))return ee;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Ar(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):ee);ye.assertNever(o)}};Ct.create=(t,e,r)=>new Ct({schema:t,typeName:D.ZodEffects,effect:e,...ce(r)});Ct.createWithPreprocess=(t,e,r)=>new Ct({schema:e,effect:{type:"preprocess",transform:t},typeName:D.ZodEffects,...ce(r)});yt=class extends de{_parse(e){return this._getType(e)===F.undefined?it(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};yt.create=(t,e)=>new yt({innerType:t,typeName:D.ZodOptional,...ce(e)});ir=class extends de{_parse(e){return this._getType(e)===F.null?it(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ir.create=(t,e)=>new ir({innerType:t,typeName:D.ZodNullable,...ce(e)});bn=class extends de{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===F.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};bn.create=(t,e)=>new bn({innerType:t,typeName:D.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ce(e)});wn=class extends de{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Fn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new gt(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new gt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};wn.create=(t,e)=>new wn({innerType:t,typeName:D.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ce(e)});Wn=class extends de{_parse(e){if(this._getType(e)!==F.nan){let n=this._getOrReturnCtx(e);return q(n,{code:j.invalid_type,expected:F.nan,received:n.parsedType}),ee}return{status:"valid",value:e.data}}};Wn.create=t=>new Wn({typeName:D.ZodNaN,...ce(t)});PS=Symbol("zod_brand"),Ko=class extends de{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Go=class t extends de{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?ee:s.status==="dirty"?(r.dirty(),on(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?ee:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:D.ZodPipeline})}},_n=class extends de{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Ar(o)&&(o.value=Object.freeze(o.value)),o);return Fn(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};_n.create=(t,e)=>new _n({innerType:t,typeName:D.ZodReadonly,...ce(e)});AS={object:bt.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(D||(D={}));IS=(t,e={message:`Input not instance of ${t.name}`})=>Gm(r=>r instanceof t,e),Wm=Ir.create,Jm=sn.create,OS=Wn.create,CS=an.create,Ym=cn.create,zS=ln.create,NS=Vn.create,jS=un.create,LS=dn.create,DS=Or.create,MS=br.create,US=Kt.create,ZS=Hn.create,qS=wr.create,il=bt.create,FS=bt.strictCreate,BS=pn.create,VS=ki.create,HS=fn.create,KS=sr.create,GS=$i.create,WS=Kn.create,JS=Gn.create,YS=Si.create,XS=hn.create,QS=mn.create,eT=gn.create,tT=yn.create,rT=Cr.create,nT=Ct.create,oT=yt.create,sT=ir.create,iT=Ct.createWithPreprocess,aT=Go.create,cT=()=>Wm().optional(),lT=()=>Jm().optional(),uT=()=>Ym().optional(),dT={string:(t=>Ir.create({...t,coerce:!0})),number:(t=>sn.create({...t,coerce:!0})),boolean:(t=>cn.create({...t,coerce:!0})),bigint:(t=>an.create({...t,coerce:!0})),date:(t=>ln.create({...t,coerce:!0}))},pT=ee});var N={};qo(N,{BRAND:()=>PS,DIRTY:()=>on,EMPTY_PATH:()=>aS,INVALID:()=>ee,NEVER:()=>pT,OK:()=>it,ParseStatus:()=>et,Schema:()=>de,ZodAny:()=>Or,ZodArray:()=>wr,ZodBigInt:()=>an,ZodBoolean:()=>cn,ZodBranded:()=>Ko,ZodCatch:()=>wn,ZodDate:()=>ln,ZodDefault:()=>bn,ZodDiscriminatedUnion:()=>ki,ZodEffects:()=>Ct,ZodEnum:()=>gn,ZodError:()=>gt,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>Si,ZodIntersection:()=>fn,ZodIssueCode:()=>j,ZodLazy:()=>hn,ZodLiteral:()=>mn,ZodMap:()=>Kn,ZodNaN:()=>Wn,ZodNativeEnum:()=>yn,ZodNever:()=>Kt,ZodNull:()=>dn,ZodNullable:()=>ir,ZodNumber:()=>sn,ZodObject:()=>bt,ZodOptional:()=>yt,ZodParsedType:()=>F,ZodPipeline:()=>Go,ZodPromise:()=>Cr,ZodReadonly:()=>_n,ZodRecord:()=>$i,ZodSchema:()=>de,ZodSet:()=>Gn,ZodString:()=>Ir,ZodSymbol:()=>Vn,ZodTransformer:()=>Ct,ZodTuple:()=>sr,ZodType:()=>de,ZodUndefined:()=>un,ZodUnion:()=>pn,ZodUnknown:()=>br,ZodVoid:()=>Hn,addIssueToContext:()=>q,any:()=>DS,array:()=>qS,bigint:()=>CS,boolean:()=>Ym,coerce:()=>dT,custom:()=>Gm,date:()=>zS,datetimeRegex:()=>Hm,defaultErrorMap:()=>gr,discriminatedUnion:()=>VS,effect:()=>nT,enum:()=>eT,function:()=>YS,getErrorMap:()=>qn,getParsedType:()=>or,instanceof:()=>IS,intersection:()=>HS,isAborted:()=>vi,isAsync:()=>Fn,isDirty:()=>xi,isValid:()=>Ar,late:()=>AS,lazy:()=>XS,literal:()=>QS,makeIssue:()=>Ho,map:()=>WS,nan:()=>OS,nativeEnum:()=>tT,never:()=>US,null:()=>LS,nullable:()=>sT,number:()=>Jm,object:()=>il,objectUtil:()=>tl,oboolean:()=>uT,onumber:()=>lT,optional:()=>oT,ostring:()=>cT,pipeline:()=>aT,preprocess:()=>iT,promise:()=>rT,quotelessJson:()=>oS,record:()=>GS,set:()=>JS,setErrorMap:()=>iS,strictObject:()=>FS,string:()=>Wm,symbol:()=>NS,transformer:()=>nT,tuple:()=>KS,undefined:()=>jS,union:()=>BS,unknown:()=>MS,util:()=>ye,void:()=>ZS});var Ti=O(()=>{_i();nl();Um();Vo();Xm();wi()});var Jn=O(()=>{Ti();Ti()});function Ei(t){let e=al.safeParse(t);return e.success?(e.data.inputs??[]).filter(r=>r.type==="connection"):[]}function cl(t,e){let r=al.safeParse(t);if(!r.success)throw new zr(`invalid manifest: ${r.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}`);if(Qm.test(e))throw new zr('a literal connection_id is baked into the bundle source \u2014 connection binding is an install-time input, not a published value. Declare an inputs[] entry { type: "connection", source_system } instead.');let n=JSON.stringify(r.data);if(Qm.test(n))throw new zr("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var eg,tg,al,zr,Qm,rg=O(()=>{Jn();eg=N.object({type:N.literal("connection"),source_system:N.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:N.string().min(1).max(200).optional()}),tg=N.discriminatedUnion("type",[eg]),al=N.object({inputs:N.array(tg).optional()}).passthrough(),zr=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};Qm=/\bconnection[_-]?id\b["']?\s*[:=]/i});var Ri,ll=O(()=>{Ri=["before_read","before_save","after_save","before_sync","after_sync","on_sync_failure"]});var ul,ng,og=O(()=>{Jn();bi();ll();ul=N.object({id:N.string().min(1,"hook id must be non-empty"),recordType:N.union([N.string().min(1),N.array(N.string().min(1)).min(1),N.literal("*")]),event:N.enum(Ri),source:N.string().min(1).optional(),when:N.unknown().optional(),run:N.unknown(),failClosed:N.boolean().optional(),timeoutMs:N.number().int().positive().optional(),description:N.string().optional(),systemReserved:N.boolean().optional()}).superRefine((t,e)=>{typeof t.run!="function"&&e.addIssue({code:"custom",path:["run"],message:"run must be a function"}),"when"in t&&t.when!==void 0&&typeof t.when!="function"&&e.addIssue({code:"custom",path:["when"],message:"when, when present, must be a function"})}),ng=Bo({kind:"hook",schema:ul,factoryName:"defineHook"})});var sg=O(()=>{og();ll()});var Pi,dl=O(()=>{Pi=["after_canonicalize_inbound","after_sync_success_outbound"]});var pl,ig,ag=O(()=>{Jn();bi();dl();pl=N.object({id:N.string().min(1,"conduit id must be non-empty"),on:N.enum(Pi),from:N.object({source:N.string().min(1,"from.source must be non-empty"),recordType:N.string().min(1,"from.recordType must be non-empty"),when:N.unknown().optional()}),to:N.object({source:N.string().min(1,"to.source must be non-empty"),recordType:N.string().min(1,"to.recordType must be non-empty")}),mode:N.enum(["dual-bind","one-shot"]).optional(),transform:N.unknown(),idempotencyKey:N.unknown().optional(),cycleBudget:N.number().int().positive().optional(),conflictStrategy:N.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:N.number().int().positive().optional(),description:N.string().optional(),systemReserved:N.boolean().optional()}).superRefine((t,e)=>{typeof t.transform!="function"&&e.addIssue({code:"custom",path:["transform"],message:"transform must be a function"});let r=t.from?.when;r!==void 0&&typeof r!="function"&&e.addIssue({code:"custom",path:["from","when"],message:"from.when, when present, must be a function"});let n=t.idempotencyKey;n!==void 0&&typeof n!="function"&&e.addIssue({code:"custom",path:["idempotencyKey"],message:"idempotencyKey, when present, must be a function"});let o=t.from,s=t.to;o?.source&&s?.source&&o.source===s.source&&e.addIssue({code:"custom",path:["to","source"],message:"a conduit must bridge two DIFFERENT sources (from.source === to.source) \u2014 use a hook for an intra-source transform"})}),ig=Bo({kind:"conduit",schema:pl,factoryName:"defineConduit"})});var cg=O(()=>{ag();dl()});async function yT(t){let e;try{e=await import("openapi-typescript")}catch{throw new Error("types-gen: 'openapi-typescript' is not installed. Add it to the environment running `turbobase project types`, or pass a `transform` override to generateTypes().")}let r=await e.default(t,{defaultNonNullable:!1});return e.astToString(r)}async function Ai(t,e={}){return(e.transform??yT)(t)}var fl=O(()=>{});function hl(t){switch(t.toLowerCase().trim()){case"boolean":return"boolean";case"smallint":case"integer":case"bigint":case"numeric":case"decimal":case"real":case"double precision":return"number";case"text":case"character varying":case"character":case"varchar":case"char":case"uuid":case"name":case"citext":return"string";case"timestamp with time zone":case"timestamp without time zone":case"timestamp":case"date":case"time":case"time with time zone":case"time without time zone":return"string";case"json":case"jsonb":return"unknown";case"array":return"unknown[]";default:return"unknown"}}function lg(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function ml(t){return`${lg(t.source)}${lg(t.recordType)}`}function bT(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function wT(t){let e=[t.pgType];return t.label&&e.push(`"${t.label}"`),t.role==="display"&&t.displayFor?e.push(`display column for ${t.displayFor} \u2014 render this, filter/join on ${t.displayFor}`):t.role==="identifier"&&t.idFor?e.push(`identifier \u2014 render ${t.idFor} instead`):t.role&&e.push(t.role),t.format&&e.push(`format: ${t.format}`),t.description&&e.push(t.description),e.join(" \xB7 ")}function gl(t){let e=ml(t),r=[`${t.source}:${t.recordType}`+(t.table?` \u2192 turbobase.${t.table}`:" (no backing table)")+`${t.listOnly?" (list-only)":""} \u2014 origin: ${t.origin}.`];t.description&&r.push(t.description);let n=r.length===1?`/** ${r[0]} */`:`/**
25
25
  * ${r.join(`
26
26
  * `)}
27
27
  */`;if(t.columns.length===0)return`${n}
28
28
  export interface ${e} {
29
29
  // no columns introspected
30
30
  [key: string]: unknown;
31
- }`;let o=t.columns.map(s=>{let i=al(s.pgType),a=s.nullable?"?":"",c=s.nullable?" | null":"";return` /** ${QS(s)} */
32
- ${XS(s.name)}${a}: ${i}${c};`});return`${n}
31
+ }`;let o=t.columns.map(s=>{let i=hl(s.pgType),a=s.nullable?"?":"",c=s.nullable?" | null":"";return` /** ${wT(s)} */
32
+ ${bT(s.name)}${a}: ${i}${c};`});return`${n}
33
33
  export interface ${e} {
34
34
  ${o.join(`
35
35
  `)}
36
- }`}function Si(t){return[...t.records].sort((n,o)=>`${n.source}:${n.recordType}`.localeCompare(`${o.source}:${o.recordType}`)).map(ll).join(`
36
+ }`}function Ii(t){return[...t.records].sort((n,o)=>`${n.source}:${n.recordType}`.localeCompare(`${o.source}:${o.recordType}`)).map(gl).join(`
37
37
 
38
- `)}function tg(t){let e=new Map;for(let n of t.records){if(!n.table)continue;let o=e.get(n.table);o||e.set(n.table,o=new Map);for(let s of n.columns)o.set(s.name,(o.get(s.name)??!0)&&s.nullable)}let r={};for(let[n,o]of[...e].sort(([s],[i])=>s.localeCompare(i)))o.get("pg_row_id")===!1?r[n]="pg_row_id":o.get("external_id")===!1&&(r[n]="external_id");return r}function eT(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function ul(t){let e=tg(t);return["/**"," * The column each table can be keyset-seeked on \u2014 pass it to `selectPage`:"," *"," * selectPage(`vendor_credit?select=*`, { sortKey: SEEK_KEYS.vendor_credit })"," *"," * A seek key must be NOT NULL and UNIQUE. Hard-coding one instead goes stale"," * silently: a table that gains `pg_row_id` has its `external_id` made"," * nullable in the same change, and seeking on a nullable column drops rows",' * with no error \u2014 the column still exists, so an "is it there?" check on the'," * override stays green. Read it from here and regenerating types fixes it."," *"," * A table with no entry has no safe single-column key (line tables: their key"," * is the composite `(parent_pg_row_id, line_index)`). Page those by filtering"," * to one parent rather than seeking across all of them."," */","export const SEEK_KEYS = {",...Object.entries(e).map(([n,o])=>` ${eT(n)}: '${o}',`),"} as const satisfies Record<string, string>;","","/** Tables with a keyset-safe seek key. */","export type SeekableTable = keyof typeof SEEK_KEYS;"].join(`
39
- `)}var dl=O(()=>{});function tT(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function rg(t,e,r){let n=await r(t,{headers:{Accept:"application/json",Authorization:`Bearer ${e}`}});if(!n.ok)throw new Error(`types-gen: GET ${t} failed (${n.status} ${n.statusText})`);return n.json()}async function zr(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let r=tT(t.baseUrl),n=await rg(r.records,t.token,e);if(!n||!Array.isArray(n.records))throw new Error("types-gen: /v1/catalog/records did not return a { records: [...] } envelope");let o=Si(n),s=[rT,"// ----- Record shapes (from /v1/catalog/records) -----",o,"// ----- Keyset seek keys (derived from column nullability) -----",ul(n)];if(!t.recordsOnly){let i=await rg(r.openapi,t.token,e),a=await $i(i,t.openApi);s.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return s.join(`
38
+ `)}function ug(t){let e=new Map,r=(o,s)=>{let i=e.get(o);i||e.set(o,i=new Map);for(let a of s)i.set(a.name,(i.get(a.name)??!0)&&a.nullable)};for(let o of t.records){o.table&&r(o.table,o.columns);for(let s of o.lines??[])r(s.table,s.columns)}let n={};for(let[o,s]of[...e].sort(([i],[a])=>i.localeCompare(a))){let i=["line_index","line_number"].find(a=>s.get(a)===!1);if(s.get("parent_pg_row_id")===!1&&i){n[o]=["parent_pg_row_id",i];continue}if(s.get("pg_row_id")===!1){n[o]="pg_row_id";continue}if(s.get("external_id")===!1){n[o]="external_id";continue}}return n}function _T(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function yl(t){let e=ug(t);return["/**"," * The seek key each table can be keyset-paged on \u2014 pass it to `selectPage`:"," *"," * selectPage(`vendor_credit?select=*`, { sortKey: SEEK_KEYS.vendor_credit })"," *"," * A seek key must be NOT NULL and UNIQUE. Hard-coding one instead goes stale"," * silently: a table that gains `pg_row_id` has its `external_id` made"," * nullable in the same change, and seeking on a nullable column drops rows",' * with no error \u2014 the column still exists, so an "is it there?" check on the'," * override stays green. Read it from here and regenerating types fixes it."," *"," * An entry may be a TUPLE, and it is passed exactly the same way. A line"," * table is keyed `(parent_pg_row_id, line_index)` and has no correct single"," * column \u2014 every line of one parent shares `parent_pg_row_id`, and"," * `line_index` is unique only within a parent \u2014 so `selectPage` seeks the"," * pair with a row-wise comparison."," *"," * A table with no entry has no keyset-safe key at all; page it by filtering"," * to a bounded subset rather than seeking across the whole table."," */","export const SEEK_KEYS = {",...Object.entries(e).map(([n,o])=>{let s=Array.isArray(o)?`[${o.map(i=>`'${i}'`).join(", ")}]`:`'${o}'`;return` ${_T(n)}: ${s},`}),"} as const satisfies Record<string, string | readonly string[]>;","","/** Tables with a keyset-safe seek key. */","export type SeekableTable = keyof typeof SEEK_KEYS;"].join(`
39
+ `)}var bl=O(()=>{});function vT(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function dg(t,e,r){let n=await r(t,{headers:{Accept:"application/json",Authorization:`Bearer ${e}`}});if(!n.ok)throw new Error(`types-gen: GET ${t} failed (${n.status} ${n.statusText})`);return n.json()}async function Nr(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let r=vT(t.baseUrl),n=await dg(r.records,t.token,e);if(!n||!Array.isArray(n.records))throw new Error("types-gen: /v1/catalog/records did not return a { records: [...] } envelope");let o=Ii(n),s=[xT,"// ----- Record shapes (from /v1/catalog/records) -----",o,"// ----- Keyset seek keys (derived from column nullability) -----",yl(n)];if(!t.recordsOnly){let i=await dg(r.openapi,t.token,e),a=await Ai(i,t.openApi);s.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return s.join(`
40
40
 
41
41
  `)+`
42
- `}var rT,ng=O(()=>{il();dl();dl();il();rT=["/**"," * GENERATED by `turbobase project types` (@turbobase/extensions). DO NOT EDIT."," *"," * Record shapes from /v1/catalog/records + PostgREST operations from"," * /v1/catalog/openapi.json, RLS-scoped to the token used to generate this."," */","","/* eslint-disable */"].join(`
43
- `)});var pl=O(()=>{pi();Km();Jm();Qm();ng()});import{homedir as nT}from"node:os";import{join as og}from"node:path";import{promises as fl}from"node:fs";function Ot(t){return t.trim().replace(/\/+$/,"")}function ig(){let t=process.env.TURBOBASE_HOME??og(nT(),".turbobase");return{dir:t,file:og(t,"credentials")}}function sg(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function Vo(){let{file:t}=ig(),e;try{let s=await fl.readFile(t,"utf8");e=JSON.parse(s)}catch(s){if(s.code==="ENOENT")return{tenants:{}};throw s}if(!e||typeof e!="object")return{tenants:{}};let r=e;if(r.tenants&&typeof r.tenants=="object"){let s={};for(let[a,c]of Object.entries(r.tenants))sg(c)&&(s[a]={token:c.token,updatedAt:c.updatedAt});return{active:typeof r.active=="string"&&s[r.active]?r.active:void 0,tenants:s}}let n={};for(let[s,i]of Object.entries(r))sg(i)&&(n[s]={token:i.token,updatedAt:i.updatedAt});return{active:oT(n),tenants:n}}function oT(t){let e,r="";for(let[n,o]of Object.entries(t))(!e||String(o.updatedAt)>r)&&(e=n,r=String(o.updatedAt));return e}async function hl(t){let{dir:e,file:r}=ig();await fl.mkdir(e,{recursive:!0,mode:448}),await fl.writeFile(r,JSON.stringify(t,null,2)+`
44
- `,{mode:384})}async function ag(t){let e=Ot(t.baseUrl),r=await Vo(),n=new Date().toISOString();return r.tenants[e]={token:t.token,updatedAt:n},r.active=e,await hl(r),{baseUrl:e,token:t.token,updatedAt:n}}async function ir(t){let e=await Vo();if(t){let s=Ot(t),i=e.tenants[s];return i?{baseUrl:s,token:i.token,updatedAt:i.updatedAt}:null}let r=Object.keys(e.tenants),n=e.active&&e.tenants[e.active]?e.active:r.length===1?r[0]:void 0;if(!n)return null;let o=e.tenants[n];return{baseUrl:n,token:o.token,updatedAt:o.updatedAt}}async function Ti(t){let e=Ot(t),r=await Vo(),n=r.tenants[e];return n?(r.active=e,await hl(r),{baseUrl:e,token:n.token,updatedAt:n.updatedAt}):null}async function ml(t){let e=await Vo(),r=t?Ot(t):e.active&&e.tenants[e.active]?e.active:Object.keys(e.tenants).length===1?Object.keys(e.tenants)[0]:void 0;if(!r||!e.tenants[r])return null;if(delete e.tenants[r],e.active===r){let n=Object.keys(e.tenants);e.active=n.length===1?n[0]:void 0}return await hl(e),r}async function Nr(){let t=await Vo();return Object.entries(t.tenants).map(([e,r])=>({baseUrl:e,token:r.token,updatedAt:r.updatedAt}))}var Ei=O(()=>{});function cg(t){if(typeof t=="string")return t.trim().slice(0,200);if(!t||typeof t!="object")return"";let e=t,r=typeof e.message=="string"&&e.message?e.message:e.error;return typeof r=="string"?r.trim().slice(0,200):""}function lg(t){return t.replace(/\/+$/,"")}function gl(t=process.env){let e=(t[Xn]??"").trim(),r=(t[Ri]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function yl(t){let e;try{e=new URL(t)}catch{return`${Xn} is not a valid URL: ${t}`}if(e.protocol==="https:")return null;let r=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]";return e.protocol==="http:"&&r?null:`${Xn} must be https:// (got ${e.protocol}//${e.hostname}). The registry bearer is sent as an Authorization header and must not cross a plaintext connection.`}var be,ee,Xn,Ri,Ho,wn=O(()=>{be=class extends Error{constructor(r,n,o){super(r);this.status=n;this.body=o;this.name="ApiError"}status;body};ee=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=lg(e.baseUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("ExtensionsApi: no fetch implementation available");this.fetchImpl=r}async request(e,r,n,o){let s=await this.fetchImpl(`${this.baseUrl}${r}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/json",...n!==void 0?{"Content-Type":"application/json"}:{},...o??{}},...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await s.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!s.ok){let c=cg(a);throw new be(`${e} ${r} \u2192 ${s.status}${c?`: ${c}`:""}`,s.status,a)}return a}deploy(e){return this.request("POST","/v1/extensions",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli",...e.connectionId?{connectionId:e.connectionId}:{}})}async list(e){let r=e?`?kind=${encodeURIComponent(e)}`:"";return(await this.request("GET",`/v1/extensions${r}`)).extensions??[]}test(e){return this.request("POST","/v1/extensions/test",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli"})}async logs(e,r){let n=r&&r>0?`?limit=${Math.floor(r)}`:"";return(await this.request("GET",`/v1/extensions/${encodeURIComponent(e)}/logs${n}`)).logs??[]}async catalogRecords(){return(await this.request("GET","/v1/catalog/records")).records??[]}async conduitEvents(e,r={}){let n=new URLSearchParams;r.since&&n.set("since",r.since),r.limit&&r.limit>0&&n.set("limit",String(Math.floor(r.limit)));let o=n.toString()?`?${n.toString()}`:"";return(await this.request("GET",`/v1/conduits/${encodeURIComponent(e)}/events${o}`)).events??[]}async bindings(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/bindings${n}`)).bindings??[]}async appsList(){return(await this.request("GET","/v1/apps")).apps??[]}appsCreate(e){return this.request("POST","/v1/apps",{slug:e.slug,name:e.name??e.slug,description:e.description})}appsPull(e){return this.request("GET",`/v1/apps/${encodeURIComponent(e)}/pull`)}appPullContext(e){return this.request("GET",`/v1/apps/proposals/${encodeURIComponent(e)}/pull-context`)}appsPush(e,r,n={}){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/push`,{files:r,...n.note?{note:n.note}:{},...n.meta?{meta:n.meta}:{}},n.proposalId?{"x-proposal-id":n.proposalId}:void 0)}learningsPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.section&&r.set("section",e.section),e.limit!==void 0&&r.set("limit",String(e.limit)),e.group===!1&&r.set("group","false");let n=r.toString();return this.request("GET",`/v1/learnings/pending${n?`?${n}`:""}`)}rulesPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.limit!==void 0&&r.set("limit",String(e.limit));let n=r.toString();return this.request("GET",`/v1/learnings/rules-pending${n?`?${n}`:""}`)}rulesPush(e,r={}){return this.request("POST","/v1/learnings/push-rules",{planToken:e,...r.app?{app:r.app}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{}})}skillsList(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status);let n=r.toString();return this.request("GET",`/v1/skills${n?`?${n}`:""}`)}skillsPublish(e){return this.request("POST","/v1/skills/publish",{slugs:[...e]})}skillsUnpublish(e){return this.request("POST","/v1/skills/unpublish",{slugs:[...e]})}skillsRollback(e){return this.request("POST","/v1/skills/rollback",{versionNo:e})}skillsReleases(){return this.request("GET","/v1/skills/releases")}skillsDelete(e){return this.request("DELETE",`/v1/skills/${encodeURIComponent(e)}`)}learningsPushKb(e,r={}){return this.request("POST","/v1/learnings/push-kb",{planToken:e,...r.app?{app:r.app}:{},...r.section?{section:r.section}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{}})}retryBinding(e){return this.request("POST",`/v1/bindings/${encodeURIComponent(e)}/retry`)}configExport(){return this.request("GET","/v1/config/export")}configPlan(e){return this.request("POST","/v1/config/plan",{bundle:e})}configApply(e){return this.request("POST","/v1/config/apply",{bundle:e})}async tablesList(){return(await this.request("GET","/v1/tables")).tables??[]}tablesPlan(e){return this.request("POST","/v1/tables/plan",e)}tablesApply(e){return this.request("POST","/v1/tables/apply",e)}tablesDrop(e,r){return this.request("DELETE",`/v1/tables/${encodeURIComponent(e)}?confirm=${encodeURIComponent(r)}`)}async guardrailsList(){return(await this.request("GET","/v1/guardrails")).guardrails??[]}async guardrailCreate(e){return(await this.request("POST","/v1/guardrails",e)).guardrail}async guardrailUpdate(e,r){return(await this.request("PATCH",`/v1/guardrails/${encodeURIComponent(e)}`,r)).guardrail}guardrailDelete(e){return this.request("DELETE",`/v1/guardrails/${encodeURIComponent(e)}`)}guardrailTest(e){return this.request("POST","/v1/guardrails/test",e)}releaseDeploy(e){return this.request("POST","/v1/releases/deploy",{...e.solutionId?{solutionId:e.solutionId}:{},target:e.target,...e.approvedBy?{approvedBy:e.approvedBy}:{},...e.files?{files:e.files}:{},...e.gitRepo?{gitRepo:e.gitRepo}:{},...e.gitRef?{gitRef:e.gitRef}:{},...e.gitSha?{gitSha:e.gitSha}:{},...e.prUrl?{prUrl:e.prUrl}:{}})}async releaseList(){return(await this.request("GET","/v1/releases")).releases??[]}releaseGet(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}`)}releaseFiles(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/files`)}releasePush(e,r){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/push`,{files:r.files,target:r.target,...r.approvedBy?{approvedBy:r.approvedBy}:{}})}releaseStatus(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/status`)}releaseRollback(e){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/rollback`)}},Xn="TURBOBASE_REGISTRY_URL",Ri="TURBOBASE_REGISTRY_TOKEN";Ho=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=lg(e.registryUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("RegistryApi: no fetch implementation available");this.fetchImpl=r}async request(e,r,n){let o={Authorization:`Bearer ${this.token}`,Accept:"application/json"};n!==void 0&&(o["Content-Type"]="application/json");let s=await this.fetchImpl(`${this.registryUrl}${r}`,{method:e,headers:o,...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await s.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!s.ok){let c=cg(a);throw new be(`${e} ${r} \u2192 ${s.status}${c?`: ${c}`:""}`,s.status,a)}return a}async list(){return(await this.request("GET","/extensions")).extensions??[]}fetchBundle(e,r){let n=r?`?version=${encodeURIComponent(r)}`:"";return this.request("GET",`/extensions/${encodeURIComponent(e)}${n}`)}publish(e){return this.request("POST","/extensions",{name:e.name,version:e.version,kind:e.kind,bundle:e.bundle,...e.manifest?{manifest:e.manifest}:{}})}}});function iT(t){if(sT.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function cT(){return{name:"extension-self-contained-fence",setup(t){t.onResolve({filter:/.*/},e=>e.kind==="entry-point"?null:iT(e.path)?{path:e.path,namespace:"extension-sdk"}:{errors:[{text:`extension ${e.path.startsWith(".")||e.path.startsWith("/")?`imports a sibling/local file ('${e.path}')`:e.path.startsWith("node:")||uT(e.path)?`imports a Node builtin ('${e.path}')`:`imports an external module ('${e.path}')`} \u2014 sandboxed extensions must be self-contained. The ONLY allowed import is the SDK factory ('@/sync/hooks' or '@turbobase/extensions'); inline everything else into the extension file.`}]}),t.onLoad({filter:/.*/,namespace:"extension-sdk"},()=>({contents:aT,loader:"js"}))}}}function uT(t){let e=t.startsWith("node:")?t.slice(5):t;return lT.has(e.split("/")[0])}function ug(t,e){return new Error(`'${t}' is not installed \u2014 \`turbobase ext test\` and \`turbobase ext replay\` compile and execute extensions locally, which needs the native sandbox extras. Run \`turbobase ext extras install\` once, then re-run this command. (cause: ${e instanceof Error?e.message:String(e)})`)}async function dT(){try{return(await import("esbuild")).build}catch(t){throw ug("esbuild",t)}}async function pT(){try{return(await import("isolated-vm")).default}catch(t){throw ug("isolated-vm",t)}}async function Pi(t){let e=await dT(),r;try{r=await e({stdin:{contents:t,loader:"ts",resolveDir:process.cwd(),sourcefile:"extension.ts"},bundle:!0,write:!1,format:"iife",globalName:"__tb_extension_module",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[cT()]})}catch(n){let s=n.errors?.map(i=>i.text).filter(Boolean).join("; ");throw new bl(s||`extension bundle failed: ${String(n)}`)}return r.outputFiles?.[0]?.text??""}async function Ko(t,e,r={}){let n=r.timeoutMs??200,o=r.memoryLimitMb??16,s=r.member??"run",i={patches:[],logs:[]},a=await pT(),c=new a.Isolate({memoryLimit:o});try{let l=await c.createContext(),u=l.global,d=new a.Callback(R=>{let z=JSON.parse(String(R));i.rejection||(i.rejection=z)}),b=new a.Callback(R=>{i.patches.push(JSON.parse(String(R)))}),m=new a.Callback(R=>{let z=JSON.parse(String(R));i.logs.push(z)}),f=new a.Callback(R=>{i.result=JSON.parse(String(R))});await u.set("__tb_reject",d),await u.set("__tb_patch",b),await u.set("__tb_log",m),await u.set("__tb_result",f),await u.set("__tb_ctx_json",JSON.stringify(fT(e)));let y=hT(t,s),E=await(await c.compileScript(y)).run(l,{timeout:n,promise:!0});return s==="when"?{effects:i,whenResult:!!E}:{effects:i}}finally{c.isDisposed||c.dispose()}}function fT(t){return{recordType:t.recordType,event:t.event,direction:t.direction,origin:t.origin,source:t.source,payload:t.payload??null,prior:t.prior??null,user:t.user??null,tenantConfig:t.tenantConfig??{},metadata:t.metadata??null,bindings:t.bindings??null,atlasLinks:t.atlasLinks??null}}function hT(t,e){return`
42
+ `}var xT,pg=O(()=>{fl();bl();bl();fl();xT=["/**"," * GENERATED by `turbobase project types` (@turbobase/extensions). DO NOT EDIT."," *"," * Record shapes from /v1/catalog/records + PostgREST operations from"," * /v1/catalog/openapi.json, RLS-scoped to the token used to generate this."," */","","/* eslint-disable */"].join(`
43
+ `)});var wl=O(()=>{bi();rg();sg();cg();pg()});import{homedir as kT}from"node:os";import{join as fg}from"node:path";import{promises as _l}from"node:fs";function zt(t){return t.trim().replace(/\/+$/,"")}function Oi(){let t=process.env.TURBOBASE_HOME??fg(kT(),".turbobase");return{dir:t,file:fg(t,"credentials")}}function hg(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function Wo(){let{file:t}=Oi(),e;try{let s=await _l.readFile(t,"utf8");e=JSON.parse(s)}catch(s){if(s.code==="ENOENT")return{tenants:{}};throw s}if(!e||typeof e!="object")return{tenants:{}};let r=e;if(r.tenants&&typeof r.tenants=="object"){let s={};for(let[a,c]of Object.entries(r.tenants))hg(c)&&(s[a]={token:c.token,updatedAt:c.updatedAt});return{active:typeof r.active=="string"&&s[r.active]?r.active:void 0,tenants:s}}let n={};for(let[s,i]of Object.entries(r))hg(i)&&(n[s]={token:i.token,updatedAt:i.updatedAt});return{active:$T(n),tenants:n}}function $T(t){let e,r="";for(let[n,o]of Object.entries(t))(!e||String(o.updatedAt)>r)&&(e=n,r=String(o.updatedAt));return e}async function vl(t){let{dir:e,file:r}=Oi();await _l.mkdir(e,{recursive:!0,mode:448}),await _l.writeFile(r,JSON.stringify(t,null,2)+`
44
+ `,{mode:384})}async function mg(t){let e=zt(t.baseUrl),r=await Wo(),n=new Date().toISOString();return r.tenants[e]={token:t.token,updatedAt:n},r.active=e,await vl(r),{baseUrl:e,token:t.token,updatedAt:n}}async function Gt(t){let e=await Wo();if(t){let s=zt(t),i=e.tenants[s];return i?{baseUrl:s,token:i.token,updatedAt:i.updatedAt}:null}let r=Object.keys(e.tenants),n=e.active&&e.tenants[e.active]?e.active:r.length===1?r[0]:void 0;if(!n)return null;let o=e.tenants[n];return{baseUrl:n,token:o.token,updatedAt:o.updatedAt}}async function Ci(t){let e=zt(t),r=await Wo(),n=r.tenants[e];return n?(r.active=e,await vl(r),{baseUrl:e,token:n.token,updatedAt:n.updatedAt}):null}async function xl(t){let e=await Wo(),r=t?zt(t):e.active&&e.tenants[e.active]?e.active:Object.keys(e.tenants).length===1?Object.keys(e.tenants)[0]:void 0;if(!r||!e.tenants[r])return null;if(delete e.tenants[r],e.active===r){let n=Object.keys(e.tenants);e.active=n.length===1?n[0]:void 0}return await vl(e),r}async function _r(){let t=await Wo();return Object.entries(t.tenants).map(([e,r])=>({baseUrl:e,token:r.token,updatedAt:r.updatedAt}))}var Jo=O(()=>{});function gg(t){if(typeof t=="string")return t.trim().slice(0,200);if(!t||typeof t!="object")return"";let e=t,r=typeof e.message=="string"&&e.message?e.message:e.error;return typeof r=="string"?r.trim().slice(0,200):""}function yg(t){return t.replace(/\/+$/,"")}function kl(t=process.env){let e=(t[Yn]??"").trim(),r=(t[zi]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function $l(t){let e;try{e=new URL(t)}catch{return`${Yn} is not a valid URL: ${t}`}if(e.protocol==="https:")return null;let r=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]";return e.protocol==="http:"&&r?null:`${Yn} must be https:// (got ${e.protocol}//${e.hostname}). The registry bearer is sent as an Authorization header and must not cross a plaintext connection.`}var be,Q,Yn,zi,Yo,jr=O(()=>{be=class extends Error{constructor(r,n,o){super(r);this.status=n;this.body=o;this.name="ApiError"}status;body};Q=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=yg(e.baseUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("ExtensionsApi: no fetch implementation available");this.fetchImpl=r}async request(e,r,n,o){let s=await this.fetchImpl(`${this.baseUrl}${r}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/json",...n!==void 0?{"Content-Type":"application/json"}:{},...o??{}},...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await s.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!s.ok){let c=gg(a);throw new be(`${e} ${r} \u2192 ${s.status}${c?`: ${c}`:""}`,s.status,a)}return a}deploy(e){return this.request("POST","/v1/extensions",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli",...e.connectionId?{connectionId:e.connectionId}:{}})}async list(e){let r=e?`?kind=${encodeURIComponent(e)}`:"";return(await this.request("GET",`/v1/extensions${r}`)).extensions??[]}test(e){return this.request("POST","/v1/extensions/test",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli"})}async logs(e,r){let n=r&&r>0?`?limit=${Math.floor(r)}`:"";return(await this.request("GET",`/v1/extensions/${encodeURIComponent(e)}/logs${n}`)).logs??[]}async catalogRecords(){return(await this.request("GET","/v1/catalog/records")).records??[]}async conduitEvents(e,r={}){let n=new URLSearchParams;r.since&&n.set("since",r.since),r.limit&&r.limit>0&&n.set("limit",String(Math.floor(r.limit)));let o=n.toString()?`?${n.toString()}`:"";return(await this.request("GET",`/v1/conduits/${encodeURIComponent(e)}/events${o}`)).events??[]}async bindings(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/bindings${n}`)).bindings??[]}async appsList(){return(await this.request("GET","/v1/apps")).apps??[]}appsCreate(e){return this.request("POST","/v1/apps",{slug:e.slug,name:e.name??e.slug,description:e.description})}appsPull(e){return this.request("GET",`/v1/apps/${encodeURIComponent(e)}/pull`)}appPullContext(e){return this.request("GET",`/v1/apps/proposals/${encodeURIComponent(e)}/pull-context`)}appsPush(e,r,n={}){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/push`,{files:r,...n.note?{note:n.note}:{},...n.meta?{meta:n.meta}:{}},n.proposalId?{"x-proposal-id":n.proposalId}:void 0)}learningsPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.section&&r.set("section",e.section),e.limit!==void 0&&r.set("limit",String(e.limit)),e.group===!1&&r.set("group","false");let n=r.toString();return this.request("GET",`/v1/learnings/pending${n?`?${n}`:""}`)}learningsIngest(e){return this.request("POST","/v1/learnings/ingest",{...e?{app:e}:{}})}rulesPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.limit!==void 0&&r.set("limit",String(e.limit)),e.group===!1&&r.set("group","false"),e.reapply&&r.set("reapply","true");let n=r.toString();return this.request("GET",`/v1/learnings/rules-pending${n?`?${n}`:""}`)}rulesPush(e,r={}){return this.request("POST","/v1/learnings/push-rules",{planToken:e,...r.app?{app:r.app}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{},...r.reapply?{reapply:!0}:{}})}skillsList(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status);let n=r.toString();return this.request("GET",`/v1/skills${n?`?${n}`:""}`)}skillsPublish(e){return this.request("POST","/v1/skills/publish",{slugs:[...e]})}skillsUnpublish(e){return this.request("POST","/v1/skills/unpublish",{slugs:[...e]})}skillsRollback(e){return this.request("POST","/v1/skills/rollback",{versionNo:e})}skillsReleases(){return this.request("GET","/v1/skills/releases")}skillsDelete(e){return this.request("DELETE",`/v1/skills/${encodeURIComponent(e)}`)}docsList(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status);let n=r.toString();return this.request("GET",`/v1/docs${n?`?${n}`:""}`)}docsPublish(e){return this.request("POST","/v1/docs/publish",{slugs:[...e]})}docsUnpublish(e){return this.request("POST","/v1/docs/unpublish",{slugs:[...e]})}docsVersions(){return this.request("GET","/v1/docs/versions")}docsRollback(e){return this.request("POST","/v1/docs/rollback",{versionNo:e})}docsDelete(e){return this.request("DELETE",`/v1/docs/${encodeURIComponent(e)}`)}learningsPushKb(e,r={}){return this.request("POST","/v1/learnings/push-kb",{planToken:e,...r.app?{app:r.app}:{},...r.section?{section:r.section}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{}})}retryBinding(e){return this.request("POST",`/v1/bindings/${encodeURIComponent(e)}/retry`)}configExport(){return this.request("GET","/v1/config/export")}configPlan(e){return this.request("POST","/v1/config/plan",{bundle:e})}configApply(e){return this.request("POST","/v1/config/apply",{bundle:e})}async tablesList(){return(await this.request("GET","/v1/tables")).tables??[]}tablesPlan(e){return this.request("POST","/v1/tables/plan",e)}tablesApply(e){return this.request("POST","/v1/tables/apply",e)}tablesDrop(e,r){return this.request("DELETE",`/v1/tables/${encodeURIComponent(e)}?confirm=${encodeURIComponent(r)}`)}async guardrailsList(){return(await this.request("GET","/v1/guardrails")).guardrails??[]}async guardrailCreate(e){return(await this.request("POST","/v1/guardrails",e)).guardrail}async guardrailUpdate(e,r){return(await this.request("PATCH",`/v1/guardrails/${encodeURIComponent(e)}`,r)).guardrail}guardrailDelete(e){return this.request("DELETE",`/v1/guardrails/${encodeURIComponent(e)}`)}guardrailTest(e){return this.request("POST","/v1/guardrails/test",e)}releaseDeploy(e){return this.request("POST","/v1/releases/deploy",{...e.solutionId?{solutionId:e.solutionId}:{},target:e.target,...e.approvedBy?{approvedBy:e.approvedBy}:{},...e.files?{files:e.files}:{},...e.gitRepo?{gitRepo:e.gitRepo}:{},...e.gitRef?{gitRef:e.gitRef}:{},...e.gitSha?{gitSha:e.gitSha}:{},...e.prUrl?{prUrl:e.prUrl}:{}})}async releaseList(){return(await this.request("GET","/v1/releases")).releases??[]}releaseGet(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}`)}releaseFiles(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/files`)}releasePush(e,r){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/push`,{files:r.files,target:r.target,...r.approvedBy?{approvedBy:r.approvedBy}:{}})}releaseStatus(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/status`)}releaseRollback(e){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/rollback`)}},Yn="TURBOBASE_REGISTRY_URL",zi="TURBOBASE_REGISTRY_TOKEN";Yo=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=yg(e.registryUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("RegistryApi: no fetch implementation available");this.fetchImpl=r}async request(e,r,n){let o={Authorization:`Bearer ${this.token}`,Accept:"application/json"};n!==void 0&&(o["Content-Type"]="application/json");let s=await this.fetchImpl(`${this.registryUrl}${r}`,{method:e,headers:o,...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await s.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!s.ok){let c=gg(a);throw new be(`${e} ${r} \u2192 ${s.status}${c?`: ${c}`:""}`,s.status,a)}return a}async list(){return(await this.request("GET","/extensions")).extensions??[]}fetchBundle(e,r){let n=r?`?version=${encodeURIComponent(r)}`:"";return this.request("GET",`/extensions/${encodeURIComponent(e)}${n}`)}publish(e){return this.request("POST","/extensions",{name:e.name,version:e.version,kind:e.kind,bundle:e.bundle,...e.manifest?{manifest:e.manifest}:{}})}}});function TT(t){if(ST.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function RT(){return{name:"extension-self-contained-fence",setup(t){t.onResolve({filter:/.*/},e=>e.kind==="entry-point"?null:TT(e.path)?{path:e.path,namespace:"extension-sdk"}:{errors:[{text:`extension ${e.path.startsWith(".")||e.path.startsWith("/")?`imports a sibling/local file ('${e.path}')`:e.path.startsWith("node:")||AT(e.path)?`imports a Node builtin ('${e.path}')`:`imports an external module ('${e.path}')`} \u2014 sandboxed extensions must be self-contained. The ONLY allowed import is the SDK factory ('@/sync/hooks' or '@turbobase/extensions'); inline everything else into the extension file.`}]}),t.onLoad({filter:/.*/,namespace:"extension-sdk"},()=>({contents:ET,loader:"js"}))}}}function AT(t){let e=t.startsWith("node:")?t.slice(5):t;return PT.has(e.split("/")[0])}function bg(t,e){return new Error(`'${t}' is not installed \u2014 \`turbobase ext test\` and \`turbobase ext replay\` compile and execute extensions locally, which needs the native sandbox extras. Run \`turbobase ext extras install\` once, then re-run this command. (cause: ${e instanceof Error?e.message:String(e)})`)}async function IT(){try{return(await import("esbuild")).build}catch(t){throw bg("esbuild",t)}}async function OT(){try{return(await import("isolated-vm")).default}catch(t){throw bg("isolated-vm",t)}}async function Ni(t){let e=await IT(),r;try{r=await e({stdin:{contents:t,loader:"ts",resolveDir:process.cwd(),sourcefile:"extension.ts"},bundle:!0,write:!1,format:"iife",globalName:"__tb_extension_module",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[RT()]})}catch(n){let s=n.errors?.map(i=>i.text).filter(Boolean).join("; ");throw new Sl(s||`extension bundle failed: ${String(n)}`)}return r.outputFiles?.[0]?.text??""}async function Xo(t,e,r={}){let n=r.timeoutMs??200,o=r.memoryLimitMb??16,s=r.member??"run",i={patches:[],logs:[]},a=await OT(),c=new a.Isolate({memoryLimit:o});try{let l=await c.createContext(),u=l.global,d=new a.Callback(R=>{let z=JSON.parse(String(R));i.rejection||(i.rejection=z)}),b=new a.Callback(R=>{i.patches.push(JSON.parse(String(R)))}),m=new a.Callback(R=>{let z=JSON.parse(String(R));i.logs.push(z)}),f=new a.Callback(R=>{i.result=JSON.parse(String(R))});await u.set("__tb_reject",d),await u.set("__tb_patch",b),await u.set("__tb_log",m),await u.set("__tb_result",f),await u.set("__tb_ctx_json",JSON.stringify(CT(e)));let y=zT(t,s),E=await(await c.compileScript(y)).run(l,{timeout:n,promise:!0});return s==="when"?{effects:i,whenResult:!!E}:{effects:i}}finally{c.isDisposed||c.dispose()}}function CT(t){return{recordType:t.recordType,event:t.event,direction:t.direction,origin:t.origin,source:t.source,payload:t.payload??null,prior:t.prior??null,user:t.user??null,tenantConfig:t.tenantConfig??{},metadata:t.metadata??null,bindings:t.bindings??null,atlasLinks:t.atlasLinks??null}}function zT(t,e){return`
45
45
  "use strict";
46
46
  (async () => {
47
47
  const __tb_ctx = JSON.parse(__tb_ctx_json);
@@ -110,16 +110,16 @@ ${o.join(`
110
110
  ${e==="transform"?"__tb_result(JSON.stringify(out == null ? null : out));":""}
111
111
  return ${e==="when"?"out":"undefined"};
112
112
  })()
113
- `}var sT,aT,bl,lT,wl=O(()=>{sT=new Set(["@/sync/hooks","@/sync/hooks/index.js","@/sync/conduits","@/sync/conduits/index.js","@turbobase/extensions","@turbobase/extensions/hook","@turbobase/extensions/conduit"]);aT=`
113
+ `}var ST,ET,Sl,PT,Tl=O(()=>{ST=new Set(["@/sync/hooks","@/sync/hooks/index.js","@/sync/conduits","@/sync/conduits/index.js","@turbobase/extensions","@turbobase/extensions/hook","@turbobase/extensions/conduit"]);ET=`
114
114
  export const defineHook = (def) => def;
115
115
  export const defineConduit = (def) => def;
116
116
  export default defineHook;
117
- `,bl=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};lT=new Set(["assert","buffer","child_process","cluster","crypto","dns","events","fs","http","http2","https","net","os","path","process","querystring","readline","stream","string_decoder","timers","tls","tty","url","util","v8","vm","worker_threads","zlib"])});import{promises as _l}from"node:fs";import{join as mT}from"node:path";function gT(t){return{recordType:t.recordType??"unknown",event:t.event??"before_save",direction:t.direction??"standalone",origin:t.origin??"user",source:t.source??null,payload:t.payload??{},prior:t.prior,user:t.user,tenantConfig:t.tenantConfig??{},metadata:t.metadata}}async function yT(t,e,r){let n=e.name??r,o=e.expect??"pass";try{let{effects:s}=await Ko(t,gT(e.context)),i=s.rejection?"reject":"pass";return{name:n,expected:o,observed:i,pass:i===o,rejection:s.rejection,patchCount:s.patches.length}}catch(s){return{name:n,expected:o,observed:"pass",pass:!1,patchCount:0,error:s instanceof Error?s.message:String(s)}}}async function Ai(t,e){let r=await Pi(t),n=[];for(let o=0;o<e.length;o+=1)n.push(await yT(r,e[o],`sample[${o}]`));return n}async function Wo(t){let e;try{e=await _l.readdir(t)}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of e.sort()){if(!n.endsWith(".json"))continue;let o=await _l.readFile(mT(t,n),"utf8"),s=JSON.parse(o),i=Array.isArray(s)?s:[s];for(let a=0;a<i.length;a+=1){let c=i[a];r.push({file:n,fixture:{...c,name:c.name??`${n}${i.length>1?`#${a}`:""}`}})}}return r}function Go(t){return _l.readFile(t,"utf8")}var vl=O(()=>{wl()});function Mr(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function WT(t){let e=t.recordType;if(!e)throw new jt("record type is required (e.g. --record=salesOrder)");let r=t.event??"before_save",n=t.template??"require-field",o=t.source,s=o?`
117
+ `,Sl=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};PT=new Set(["assert","buffer","child_process","cluster","crypto","dns","events","fs","http","http2","https","net","os","path","process","querystring","readline","stream","string_decoder","timers","tls","tty","url","util","v8","vm","worker_threads","zlib"])});import{promises as El}from"node:fs";import{join as NT}from"node:path";function jT(t){return{recordType:t.recordType??"unknown",event:t.event??"before_save",direction:t.direction??"standalone",origin:t.origin??"user",source:t.source??null,payload:t.payload??{},prior:t.prior,user:t.user,tenantConfig:t.tenantConfig??{},metadata:t.metadata}}async function LT(t,e,r){let n=e.name??r,o=e.expect??"pass";try{let{effects:s}=await Xo(t,jT(e.context)),i=s.rejection?"reject":"pass";return{name:n,expected:o,observed:i,pass:i===o,rejection:s.rejection,patchCount:s.patches.length}}catch(s){return{name:n,expected:o,observed:"pass",pass:!1,patchCount:0,error:s instanceof Error?s.message:String(s)}}}async function ji(t,e){let r=await Ni(t),n=[];for(let o=0;o<e.length;o+=1)n.push(await LT(r,e[o],`sample[${o}]`));return n}async function Qo(t){let e;try{e=await El.readdir(t)}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of e.sort()){if(!n.endsWith(".json"))continue;let o=await El.readFile(NT(t,n),"utf8"),s=JSON.parse(o),i=Array.isArray(s)?s:[s];for(let a=0;a<i.length;a+=1){let c=i[a];r.push({file:n,fixture:{...c,name:c.name??`${n}${i.length>1?`#${a}`:""}`}})}}return r}function es(t){return El.readFile(t,"utf8")}var Rl=O(()=>{Tl()});function Ur(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function h0(t){let e=t.recordType;if(!e)throw new Dt("record type is required (e.g. --record=salesOrder)");let r=t.event??"before_save",n=t.template??"require-field",o=t.source,s=o?`
118
118
  source: ${JSON.stringify(o)},`:"",i,a;if(n==="blank")i=`
119
119
  run: (ctx) => {
120
120
  // Validate or mutate ctx.payload here. Reject with ctx.reject({...}); mutate
121
121
  // with ctx.patch({...}); observe with ctx.log('info', '...').
122
- },`,a="custom";else if(n==="require-field"){let b=t.field;if(!b)throw new jt("require-field template needs --field=<name>");i=`
122
+ },`,a="custom";else if(n==="require-field"){let b=t.field;if(!b)throw new Dt("require-field template needs --field=<name>");i=`
123
123
  run: (ctx) => {
124
124
  const v = ctx.payload[${JSON.stringify(b)}];
125
125
  if (v === undefined || v === null || v === '') {
@@ -129,7 +129,7 @@ export default defineHook;
129
129
  message: ${JSON.stringify(`${b} is required`)},
130
130
  });
131
131
  }
132
- },`,a=`require-field-${b}`}else if(n==="enforce-format"){let b=t.field;if(!b)throw new jt("enforce-format template needs --field=<name>");if(!t.regex)throw new jt("enforce-format template needs --regex=<pattern>");i=`
132
+ },`,a=`require-field-${b}`}else if(n==="enforce-format"){let b=t.field;if(!b)throw new Dt("enforce-format template needs --field=<name>");if(!t.regex)throw new Dt("enforce-format template needs --regex=<pattern>");i=`
133
133
  run: (ctx) => {
134
134
  const v = ctx.payload[${JSON.stringify(b)}];
135
135
  if (typeof v === 'string' && v && !/${t.regex}/.test(v)) {
@@ -139,7 +139,7 @@ export default defineHook;
139
139
  message: ${JSON.stringify(`${b} does not match expected format`)},
140
140
  });
141
141
  }
142
- },`,a=`enforce-format-${b}`}else throw new jt(`unsupported template: ${n}. Supported: require-field | enforce-format | blank.`);let c=t.id??`custom:${e}:${a}${t.regex?`-${Mr(t.regex).slice(0,24)}`:""}`,u=`/**
142
+ },`,a=`enforce-format-${b}`}else throw new Dt(`unsupported template: ${n}. Supported: require-field | enforce-format | blank.`);let c=t.id??`custom:${e}:${a}${t.regex?`-${Ur(t.regex).slice(0,24)}`:""}`,u=`/**
143
143
  * ${t.description??`${a} on ${e}.${r}`}
144
144
  *
145
145
  * Scaffolded by \`turbobase ext new hook\`. Edit freely, then \`turbobase ext test\` and
@@ -152,7 +152,7 @@ export default defineHook<Record<string, unknown>>({
152
152
  recordType: ${JSON.stringify(e)},
153
153
  event: ${JSON.stringify(r)},${s}${i}
154
154
  });
155
- `;return{relativePath:`hooks/${e}/${r}.${a}.ts`,content:u}}function GT(t){let e=t.recordType;if(!e)throw new jt("record type is required (e.g. --record=order)");let r=t.source;if(!r)throw new jt("--source is required (the origin source, e.g. --source=shopify)");let n=t.to;if(!n)throw new jt("--to is required (the target source, e.g. --to=netsuite)");if(r===n)throw new jt(`a conduit must bridge two DIFFERENT sources (got --source=${r} --to=${n}); use \`turbobase ext new hook\` for an intra-source transform`);let o=t.toRecordType??e,s=t.event??"after_canonicalize_inbound",i=t.id??`${Mr(r)}2${Mr(n)}:${Mr(e)}`,c=`/**
155
+ `;return{relativePath:`hooks/${e}/${r}.${a}.ts`,content:u}}function m0(t){let e=t.recordType;if(!e)throw new Dt("record type is required (e.g. --record=order)");let r=t.source;if(!r)throw new Dt("--source is required (the origin source, e.g. --source=shopify)");let n=t.to;if(!n)throw new Dt("--to is required (the target source, e.g. --to=netsuite)");if(r===n)throw new Dt(`a conduit must bridge two DIFFERENT sources (got --source=${r} --to=${n}); use \`turbobase ext new hook\` for an intra-source transform`);let o=t.toRecordType??e,s=t.event??"after_canonicalize_inbound",i=t.id??`${Ur(r)}2${Ur(n)}:${Ur(e)}`,c=`/**
156
156
  * ${t.description??`Bridge ${r} ${e} \u2192 ${n} ${o} (${s}).`}
157
157
  *
158
158
  * Scaffolded by \`turbobase ext new conduit\`. A conduit is a PURE canonical\u2192canonical
@@ -195,7 +195,7 @@ export default defineConduit<Record<string, unknown>>({
195
195
  },
196
196
  idempotencyKey: (ctx) => ${JSON.stringify(`${i}:`)} + ctx.externalId,
197
197
  });
198
- `;return{relativePath:`conduits/${Mr(r)}-${Mr(e)}-to-${Mr(n)}-${Mr(o)}.ts`,content:c}}function ro(t,e){let r=JT[t];if(!r)throw new jt(`unknown extension kind '${t}'. Scaffoldable kinds: ${Ng.join(", ")}.`);return r(e)}var Ng,jt,JT,Rl=O(()=>{Ng=["hook","conduit"];jt=class extends Error{};JT={hook:WT,conduit:GT}});function yE(t){let e=2166136261;for(let r=0;r<t.length;r+=1)e^=t.charCodeAt(r),e=Math.imul(e,16777619)>>>0;return e>>>0}function bE(t){return _y[yE(t)%_y.length]}function wE(t){let e=t.trim().split(/[\s\-_.]+/).filter(r=>/[a-z0-9]/i.test(r));return e.length===0?t.trim().slice(0,1).toUpperCase()||"\u2022":e.length===1?e[0].slice(0,2).toUpperCase():(e[0][0]+e[1][0]).toUpperCase()}function vy(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function xy(t,e){let[r,n]=bE(t),o=vy(wE(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${vy(e)}">
198
+ `;return{relativePath:`conduits/${Ur(r)}-${Ur(e)}-to-${Ur(n)}-${Ur(o)}.ts`,content:c}}function to(t,e){let r=g0[t];if(!r)throw new Dt(`unknown extension kind '${t}'. Scaffoldable kinds: ${Fg.join(", ")}.`);return r(e)}var Fg,Dt,g0,Nl=O(()=>{Fg=["hook","conduit"];Dt=class extends Error{};g0={hook:h0,conduit:m0}});function JE(t){let e=2166136261;for(let r=0;r<t.length;r+=1)e^=t.charCodeAt(r),e=Math.imul(e,16777619)>>>0;return e>>>0}function YE(t){return Uy[JE(t)%Uy.length]}function XE(t){let e=t.trim().split(/[\s\-_.]+/).filter(r=>/[a-z0-9]/i.test(r));return e.length===0?t.trim().slice(0,1).toUpperCase()||"\u2022":e.length===1?e[0].slice(0,2).toUpperCase():(e[0][0]+e[1][0]).toUpperCase()}function Zy(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function qy(t,e){let[r,n]=YE(t),o=Zy(XE(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${Zy(e)}">
199
199
  <defs>
200
200
  <linearGradient id="tile" x1="0" y1="0" x2="1" y2="1">
201
201
  <stop offset="0" stop-color="${r}"/>
@@ -205,9 +205,9 @@ export default defineConduit<Record<string, unknown>>({
205
205
  <rect width="64" height="64" rx="14" fill="url(#tile)"/>
206
206
  <text x="32" y="34" text-anchor="middle" dominant-baseline="central" font-family="system-ui, -apple-system, Segoe UI, sans-serif" font-size="26" font-weight="600" fill="#ffffff">${o}</text>
207
207
  </svg>
208
- `}var _y,ky=O(()=>{_y=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var $y,Sy=O(()=>{$y=Object.freeze({instance:!0,platform:!0,share:"inherit"})});var Cy={};Mo(Cy,{MAIN_TSX:()=>Iy,STYLES_CSS:()=>Oy,TSCONFIG:()=>Py,TURBOBASE_CLIENT:()=>Ty,indexHtml:()=>Ay,instanceOriginFromEnv:()=>SE,packageJson:()=>Ey,scaffoldAppFiles:()=>EE,starterApp:()=>RE,viteConfig:()=>Ry});function vE(t){let e={name:t.title},r=(t.description??"").trim().slice(0,_E);return r&&(e.description=r),e.icon="favicon.svg",e.learnings={...$y},JSON.stringify(e,null,2)+`
209
- `}function Ey(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview"},dependencies:{react:"^18.3.1","react-dom":"^18.3.1"},devDependencies:{"@types/react":"^18.3.3","@types/react-dom":"^18.3.0","@vitejs/plugin-react":"^4.3.1",typescript:"^5.5.3",vite:"^5.4.0"}},null,2)}
210
- `}function $E(t){if(!t)return null;try{let e=new URL(t);return e.protocol!=="http:"&&e.protocol!=="https:"?null:e.origin}catch{return null}}function SE(t=process.env){let e=(t.TENANT_SLUG??"").trim(),r=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!r))return`https://${e}.${r}`}function Ry(t,e={}){let r=$E(e.instanceOrigin);return`import { defineConfig } from 'vite';
208
+ `}var Uy,Fy=O(()=>{Uy=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var By,Vy=O(()=>{By=Object.freeze({instance:!0,platform:!0,share:"inherit"})});var Qy={};qo(Qy,{MAIN_TSX:()=>Yy,STYLES_CSS:()=>Xy,TSCONFIG:()=>Wy,TURBOBASE_CLIENT:()=>Hy,indexHtml:()=>Jy,instanceOriginFromEnv:()=>sR,packageJson:()=>Ky,scaffoldAppFiles:()=>aR,starterApp:()=>cR,viteConfig:()=>Gy});function eR(t){let e={name:t.title},r=(t.description??"").trim().slice(0,QE);return r&&(e.description=r),e.icon="favicon.svg",e.learnings={...By},JSON.stringify(e,null,2)+`
209
+ `}function Ky(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview",pretest:tR},dependencies:{react:"^18.3.1","react-dom":"^18.3.1"},devDependencies:{"@types/react":"^18.3.3","@types/react-dom":"^18.3.0","@vitejs/plugin-react":"^4.3.1",typescript:"^5.5.3",vite:"^5.4.0"}},null,2)}
210
+ `}function oR(t){if(!t)return null;try{let e=new URL(t);return e.protocol!=="http:"&&e.protocol!=="https:"?null:e.origin}catch{return null}}function sR(t=process.env){let e=(t.TENANT_SLUG??"").trim(),r=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!r))return`https://${e}.${r}`}function Gy(t,e={}){let r=oR(e.instanceOrigin);return`import { defineConfig } from 'vite';
211
211
  import react from '@vitejs/plugin-react';
212
212
 
213
213
  // A same-origin static SPA served at /a/${t}. \`base\` MUST match that mount
@@ -221,8 +221,8 @@ import react from '@vitejs/plugin-react';
221
221
  // you sign in, and the cookies land on localhost:3000. Override the targets
222
222
  // with SUPABASE_URL / TURBOBASE_API_URL without editing this file (Vite reads
223
223
  // them at boot; restart the dev server after changing one).
224
- const TENANT = process.env.SUPABASE_URL || '${r??xE}'; // /rest + the Realtime WS
225
- const API = process.env.TURBOBASE_API_URL || '${r??kE}'; // /v1, /auth, /login, /_app
224
+ const TENANT = process.env.SUPABASE_URL || '${r??rR}'; // /rest + the Realtime WS
225
+ const API = process.env.TURBOBASE_API_URL || '${r??nR}'; // /v1, /auth, /login, /_app
226
226
 
227
227
  // Where this bundle's assets are requested from. \`turbobase apps deploy\` sets
228
228
  // this to /_tb/app-assets/<build-id>/ so the asset URLs name the BUILD, not the
@@ -254,7 +254,7 @@ export default defineConfig({
254
254
  },
255
255
  build: { outDir: 'dist' },
256
256
  });
257
- `}function Ay(t){return`<!doctype html>
257
+ `}function Jy(t){return`<!doctype html>
258
258
  <html lang="en">
259
259
  <head>
260
260
  <meta charset="UTF-8" />
@@ -267,7 +267,7 @@ export default defineConfig({
267
267
  <script type="module" src="/src/main.tsx"></script>
268
268
  </body>
269
269
  </html>
270
- `}function EE(t){return{"package.json":Ey(t.slug),"vite.config.ts":Ry(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":TE,"tsconfig.json":Py,"index.html":Ay(t.title),"public/turbobase.json":vE(t),"public/favicon.svg":xy(t.slug,t.title),"src/main.tsx":Iy,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":Ty,"src/styles.css":Oy,"README.md":`# ${t.title}
270
+ `}function aR(t){return{"package.json":Ky(t.slug),"vite.config.ts":Gy(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":iR,"tsconfig.json":Wy,"index.html":Jy(t.title),"public/turbobase.json":eR(t),"public/favicon.svg":qy(t.slug,t.title),"src/main.tsx":Yy,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":Hy,"src/styles.css":Xy,"README.md":`# ${t.title}
271
271
 
272
272
  \`\`\`sh
273
273
  npm install
@@ -288,7 +288,7 @@ every read comes back "permission denied", which looks like an RLS problem.
288
288
 
289
289
  \`CLAUDE.md\` + \`.mcp.json\` wire Claude Code to this instance. \`.mcp.json\` holds a
290
290
  live access token and is gitignored \u2014 keep it that way.
291
- `}}function RE(t){return`import React from 'react';
291
+ `}}function cR(t){return`import React from 'react';
292
292
  import { select } from './lib/turbobase';
293
293
 
294
294
  /** Swap for any record type \u2014 GET /v1/catalog/records lists what this instance has. */
@@ -314,7 +314,7 @@ export default function App() {
314
314
  </main>
315
315
  );
316
316
  }
317
- `}var _E,Ty,xE,kE,TE,Py,Iy,Oy,zy=O(()=>{ky();Sy();_E=200;Ty=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
317
+ `}var QE,Hy,ls,tR,rR,nR,iR,Wy,Yy,Xy,eb=O(()=>{Fy();Vy();QE=200;Hy=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
318
318
  // Reads go through PostgREST (RLS-scoped); writes go through POST /v1/data/<recordType>.
319
319
  // A cold first paint that fans out many reads should use batch() \u2014 ONE request
320
320
  // that multiplexes them, sidestepping the per-request rate limiter.
@@ -708,12 +708,23 @@ async function batchChunk<T>(queries: string[]): Promise<BatchResult<T>[]> {
708
708
  //
709
709
  // pg_row_id in the type -> seek on pg_row_id. It is the default; pass nothing.
710
710
  // no pg_row_id -> pass { sortKey: 'external_id' }.
711
+ // neither -> the key is COMPOSITE. Pass the tuple, in order:
712
+ // { sortKey: ['parent_pg_row_id', 'line_index'] }.
711
713
  //
712
714
  // Re-check that when you regenerate types. Several mirror tables gained
713
715
  // \`pg_row_id\` after they were first read, and the same release made their
714
716
  // \`external_id\` nullable and unique only per connection \u2014 so a \`sortKey\`
715
717
  // override that was correct when it was written silently became a row-dropping
716
718
  // bug, on a table whose seek column still existed.
719
+ //
720
+ // A LINE table is the composite case, and it has NO correct single column:
721
+ // \`tran_internal_id\` repeats for every line of one transaction, \`line_index\`
722
+ // (\`line_number\` on some) is unique only WITHIN one parent, and
723
+ // \`parent_pg_row_id\` is NOT NULL but shared by every line of that parent. Its
724
+ // key is the PAIR \u2014 \`(parent_pg_row_id, line_index)\` \u2014 so the seek is a
725
+ // row-wise comparison over the pair, which is what a tuple \`sortKey\` builds.
726
+ // \`SEEK_KEYS\` in your generated types carries the right value for every table,
727
+ // single column or tuple, so you never have to know which shape a table is.
717
728
  // ---------------------------------------------------------------------------
718
729
 
719
730
  /** One page of a keyset read: the trimmed rows, plus the token to fetch the next
@@ -723,12 +734,21 @@ export interface Page<T = unknown> {
723
734
  nextCursor: string | null;
724
735
  }
725
736
 
726
- /** Opaque cursor payload \u2014 the same compact { t, k, v, h } shape Turbobase's
727
- * server-side cursors use (table, sort key, last value, query hash). */
737
+ /** Opaque cursor payload: format version, table, the seek columns IN ORDER, the
738
+ * last row's value for each of them, the direction the page was ordered in, and
739
+ * the query hash.
740
+ *
741
+ * \`c\` is the CURSOR FORMAT version, and it is why a stale token is refused
742
+ * rather than reinterpreted. A v1 token carried a single-string \`k\`/\`v\` pair;
743
+ * read as a one-column tuple it would page a line table on \`parent_pg_row_id\`
744
+ * alone and drop every line after the first of each parent \u2014 a wrong answer
745
+ * with no error, which is exactly what this whole path exists to prevent. */
728
746
  interface CursorToken {
747
+ c: 2;
729
748
  t: string;
730
- k: string;
731
- v: string;
749
+ k: string[];
750
+ v: string[];
751
+ d: 'asc' | 'desc';
732
752
  h: string;
733
753
  }
734
754
 
@@ -750,10 +770,14 @@ function b64urlDecode(s: string): string {
750
770
 
751
771
  /** Mint an opaque next-page cursor. */
752
772
  function encodeCursor(p: CursorToken): string {
753
- return b64urlEncode(JSON.stringify({ t: p.t, k: p.k, v: p.v, h: p.h }));
773
+ return b64urlEncode(JSON.stringify({ c: 2, t: p.t, k: p.k, v: p.v, d: p.d, h: p.h }));
754
774
  }
755
775
 
756
- /** Decode a cursor token; throws TurbobaseCursorError on a malformed one. */
776
+ /** Decode a cursor token; throws TurbobaseCursorError on a malformed, tampered
777
+ * or stale one. A cursor is caller-supplied input, so nothing here is trusted:
778
+ * every field is type-checked, the two arrays must be the same length, and a
779
+ * token that fails ANY check throws \u2014 it never degrades to "no seek predicate",
780
+ * which would silently re-read the table from the top. */
757
781
  function decodeCursor(token: string): CursorToken {
758
782
  let parsed: unknown;
759
783
  try {
@@ -762,16 +786,29 @@ function decodeCursor(token: string): CursorToken {
762
786
  throw new TurbobaseCursorError('cursor is malformed (not a valid token)');
763
787
  }
764
788
  const o = parsed as Record<string, unknown> | null;
789
+ if (!o || typeof o !== 'object') {
790
+ throw new TurbobaseCursorError('cursor is malformed (not a valid token)');
791
+ }
792
+ if (o.c !== 2) {
793
+ throw new TurbobaseCursorError(
794
+ 'cursor was minted by an older client (single-column format) and is not readable: a seek ' +
795
+ 'key is now an ordered tuple of columns. Drop the cursor and re-read from the first ' +
796
+ 'page \u2014 passing no cursor.',
797
+ );
798
+ }
799
+ const strArray = (x: unknown): x is string[] =>
800
+ Array.isArray(x) && x.length > 0 && x.every((s) => typeof s === 'string');
765
801
  if (
766
- !o ||
767
802
  typeof o.t !== 'string' ||
768
- typeof o.k !== 'string' ||
769
- typeof o.v !== 'string' ||
770
- typeof o.h !== 'string'
803
+ typeof o.h !== 'string' ||
804
+ (o.d !== 'asc' && o.d !== 'desc') ||
805
+ !strArray(o.k) ||
806
+ !strArray(o.v) ||
807
+ o.k.length !== o.v.length
771
808
  ) {
772
809
  throw new TurbobaseCursorError('cursor is malformed (missing fields)');
773
810
  }
774
- return { t: o.t, k: o.k, v: o.v, h: o.h };
811
+ return { c: 2, t: o.t, k: o.k, v: o.v, d: o.d, h: o.h };
775
812
  }
776
813
 
777
814
  /** FNV-1a 32-bit hex \u2014 a tiny, dependency-free hash. Not cryptographic: it only
@@ -785,17 +822,83 @@ function fnv1a(s: string): string {
785
822
  return h.toString(16).padStart(8, '0');
786
823
  }
787
824
 
788
- /** Hash the row-set-defining part of a query (table + sort key + every param
789
- * except paging: order/limit/offset). Two pages of the same query hash equal;
790
- * a changed filter/select hashes different and invalidates an old cursor. */
791
- function queryHash(table: string, params: URLSearchParams, sortKey: string): string {
825
+ /** Hash the row-set-defining part of a query (table + the seek spec \u2014 every seek
826
+ * column, in order, plus the direction \u2014 + every param except paging:
827
+ * order/limit/offset). Two pages of the same query hash equal; a changed
828
+ * filter/select/seek/direction hashes different and invalidates an old cursor. */
829
+ function queryHash(table: string, params: URLSearchParams, seekSpec: string): string {
792
830
  const parts: string[] = [];
793
831
  for (const [k, v] of params) {
794
832
  if (k === 'order' || k === 'limit' || k === 'offset') continue;
795
833
  parts.push(\`\${k}=\${v}\`);
796
834
  }
797
835
  parts.sort();
798
- return fnv1a(JSON.stringify([table, sortKey, parts]));
836
+ return fnv1a(JSON.stringify([table, seekSpec, parts]));
837
+ }
838
+
839
+ /** The seek key as an ordered tuple of columns \u2014 \`['pg_row_id']\` by default,
840
+ * the surrogate primary key almost every mirror table carries.
841
+ *
842
+ * Column names are validated as plain identifiers HERE, once, so that nothing
843
+ * unchecked is ever concatenated into \`order=\` or into a seek predicate. */
844
+ function seekColumns(sortKey: string | readonly string[] | undefined): string[] {
845
+ const cols =
846
+ sortKey === undefined ? ['pg_row_id'] : typeof sortKey === 'string' ? [sortKey] : [...sortKey];
847
+ if (cols.length === 0) {
848
+ throw new TurbobaseCursorError('sortKey must name at least one column');
849
+ }
850
+ for (const c of cols) {
851
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(c)) {
852
+ throw new TurbobaseCursorError(\`sortKey column "\${c}" is not a plain column name\`);
853
+ }
854
+ }
855
+ return cols;
856
+ }
857
+
858
+ /** Quote a value for use INSIDE a PostgREST logical expression, where \`,\` \`(\`
859
+ * and \`)\` are STRUCTURAL \u2014 an unquoted value could change the SHAPE of the
860
+ * predicate rather than only one of its operands. \`JSON.stringify\` emits
861
+ * exactly PostgREST's quoted-literal form (double quotes, with \`"\` and the
862
+ * escape character itself backslash-escaped), so a cursor value can only ever
863
+ * land as an operand. */
864
+ function quoteSeekValue(v: string): string {
865
+ return JSON.stringify(v);
866
+ }
867
+
868
+ /**
869
+ * Row-wise comparison over the seek tuple, as PostgREST can express it.
870
+ *
871
+ * \`(a, b) > (:a, :b)\` is NOT \`a >= :a AND b > :b\`. That second form is the
872
+ * classic off-by-one: it REPEATS the boundary row's siblings under the same
873
+ * parent and DROPS rows under the next one. The correct expansion is
874
+ * lexicographic \u2014
875
+ *
876
+ * a > :a OR (a = :a AND b > :b) OR (a = :a AND b = :b AND c > :c) \u2026
877
+ *
878
+ * \u2014 and that is what PostgREST's \`or=(\u2026, and(\u2026))\` tree spells.
879
+ *
880
+ * DESC flips every strict comparison to \`<\` and leaves the equality prefix
881
+ * alone. One direction covers the whole tuple: a mixed-direction seek is
882
+ * expressible in this shape, but nothing needs one, and every extra shape is
883
+ * another boundary to get wrong.
884
+ *
885
+ * Column names came from the CALLER and were validated by seekColumns(); values
886
+ * came from the cursor and are quoted. A cursor can therefore never introduce a
887
+ * column, an operator, or an ordering.
888
+ */
889
+ function seekOrExpr(cols: string[], values: string[], descending: boolean): string {
890
+ const cmp = descending ? 'lt' : 'gt';
891
+ const terms: string[] = [];
892
+ for (let i = 0; i < cols.length; i++) {
893
+ const strict = \`\${cols[i]}.\${cmp}.\${quoteSeekValue(values[i]!)}\`;
894
+ if (i === 0) {
895
+ terms.push(strict);
896
+ continue;
897
+ }
898
+ const eqPrefix = cols.slice(0, i).map((c, j) => \`\${c}.eq.\${quoteSeekValue(values[j]!)}\`);
899
+ terms.push(\`and(\${[...eqPrefix, strict].join(',')})\`);
900
+ }
901
+ return \`(\${terms.join(',')})\`;
799
902
  }
800
903
 
801
904
  /**
@@ -813,6 +916,16 @@ function queryHash(table: string, params: URLSearchParams, sortKey: string): str
813
916
  * \`pg_row_id\`, \`external_id\` is nullable and unique only per connection, so
814
917
  * seeking on it drops rows silently.
815
918
  *
919
+ * COMPOSITE KEYS: pass the columns as a tuple, in key order, and the seek
920
+ * becomes a row-wise comparison over all of them. A LINE table has no correct
921
+ * single column, so this is the only way to page one across parents:
922
+ *
923
+ * selectPage('vendor_bill_line?select=*', { sortKey: ['parent_pg_row_id', 'line_index'] })
924
+ *
925
+ * \`{ descending: true }\` walks the same key backwards. The direction applies to
926
+ * the whole tuple and is pinned into the cursor, so a cursor cannot be replayed
927
+ * against the other direction.
928
+ *
816
929
  * EMBEDS PAGE TOO: \`selectPage('purchase_order?select=*,receipt_lines(*)')\` keysets
817
930
  * the PARENT (purchase_order) and carries the embed with each parent row, so a
818
931
  * page is one request no matter how many related rows it pulls. If the instance
@@ -823,28 +936,38 @@ function queryHash(table: string, params: URLSearchParams, sortKey: string): str
823
936
  */
824
937
  export async function selectPage<T = unknown>(
825
938
  pathAndQuery: string,
826
- opts: { pageSize?: number; cursor?: string; sortKey?: string } = {},
939
+ opts: {
940
+ pageSize?: number;
941
+ cursor?: string;
942
+ sortKey?: string | readonly string[];
943
+ descending?: boolean;
944
+ } = {},
827
945
  ): Promise<Page<T>> {
828
946
  const pageSize = Math.max(1, Math.min(opts.pageSize ?? DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE));
829
947
  const qIndex = pathAndQuery.indexOf('?');
830
948
  const table = qIndex === -1 ? pathAndQuery : pathAndQuery.slice(0, qIndex);
831
949
  const params = new URLSearchParams(qIndex === -1 ? '' : pathAndQuery.slice(qIndex + 1));
832
- const sortKey = opts.sortKey ?? 'pg_row_id';
950
+ const seek = seekColumns(opts.sortKey);
951
+ const descending = opts.descending === true;
952
+ const dir = descending ? 'desc' : 'asc';
833
953
 
834
- // Guarantee the sort key is projected so nextCursor can always be minted from
835
- // the last row (mirrors the server's buildSelect). Split on TOP-LEVEL commas
836
- // only: \`select=*,rel(a,b)\` must not be torn into \`rel(a\` + \`b)\`.
954
+ // Guarantee every seek column is projected so nextCursor can always be minted
955
+ // from the last row (mirrors the server's buildSelect). Split on TOP-LEVEL
956
+ // commas only: \`select=*,rel(a,b)\` must not be torn into \`rel(a\` + \`b)\`.
837
957
  const sel = params.get('select');
838
958
  if (sel && sel !== '*') {
839
959
  const cols = splitTopLevel(sel);
840
- if (!cols.includes(sortKey)) params.set('select', [...cols, sortKey].join(','));
960
+ const missing = seek.filter((k) => !cols.includes(k));
961
+ if (missing.length > 0) params.set('select', [...cols, ...missing].join(','));
841
962
  }
842
963
 
843
964
  // Pin the cursor to the row-set-defining query BEFORE paging params are added.
844
- const filterHash = queryHash(table, params, sortKey);
965
+ const filterHash = queryHash(table, params, \`\${seek.join(',')}.\${dir}\`);
845
966
 
846
967
  // Keyset order + one probe row beyond the page \u2192 has-more without a count.
847
- params.set('order', \`\${sortKey}.asc\`);
968
+ // Ordering by the FULL tuple is half the correctness: a page boundary can only
969
+ // be expressed as "past this row" if the rows were totally ordered to begin with.
970
+ params.set('order', seek.map((k) => \`\${k}.\${dir}\`).join(','));
848
971
  params.set('limit', String(pageSize + 1));
849
972
  params.delete('offset');
850
973
 
@@ -858,8 +981,25 @@ export async function selectPage<T = unknown>(
858
981
  'cursor does not match this query (filters/select/sort key changed since it was minted)',
859
982
  );
860
983
  }
861
- // Strict total-order seek past the last row of the previous page.
862
- params.set(sortKey, \`gt.\${c.v}\`);
984
+ // The predicate is built from the CALLER's seek columns; the cursor supplies
985
+ // VALUES only. This check is what lets that be stated flatly \u2014 a cursor
986
+ // naming different columns is refused, never silently re-keyed. (filterHash
987
+ // already covers the case; the explicit comparison is what makes the message
988
+ // actionable rather than "does not match this query".)
989
+ if (c.k.length !== seek.length || c.k.some((name, i) => name !== seek[i])) {
990
+ throw new TurbobaseCursorError(
991
+ \`cursor is for seek key (\${c.k.join(', ')}), not (\${seek.join(', ')})\`,
992
+ );
993
+ }
994
+ if (seek.length === 1) {
995
+ // One column: the row-wise comparison IS \`a > :a\`, and PostgREST spells
996
+ // that as a plain column filter \u2014 shorter, and no quoting to get wrong.
997
+ params.set(seek[0]!, \`\${descending ? 'lt' : 'gt'}.\${c.v[0]}\`);
998
+ } else {
999
+ // append, not set: a caller may have their own \`or=\` filter, and PostgREST
1000
+ // ANDs repeated top-level conditions rather than replacing them.
1001
+ params.append('or', seekOrExpr(seek, c.v, descending));
1002
+ }
863
1003
  }
864
1004
 
865
1005
  // Same read primitive as select(), so a page whose \`select\` carries an embed
@@ -893,13 +1033,13 @@ export async function selectPage<T = unknown>(
893
1033
  // when the projection includes \`pg_row_id\` (\`select=*\`, or an explicit list
894
1034
  // naming it); a narrow select that omits it cannot be checked here, which is
895
1035
  // what SEEK_KEYS in your generated types is for.
896
- if (opts.sortKey && opts.sortKey !== 'pg_row_id' && rows.length > 0) {
1036
+ if (opts.sortKey !== undefined && !seek.includes('pg_row_id') && rows.length > 0) {
897
1037
  if (Object.prototype.hasOwnProperty.call(rows[0] as object, 'pg_row_id')) {
898
1038
  throw new TurbobaseCursorError(
899
- \`"\${table}" has a pg_row_id, so { sortKey: '\${opts.sortKey}' } is unsafe: on a table with \` +
900
- 'pg_row_id, external_id is nullable and unique only per connection, and a keyset seek ' +
901
- 'on it drops rows silently. Remove the sortKey override (pg_row_id is the default), or ' +
902
- 'read it from SEEK_KEYS in your generated types.',
1039
+ \`"\${table}" has a pg_row_id, so { sortKey: [\${seek.join(', ')}] } is unsafe: on a table \` +
1040
+ 'with pg_row_id, external_id is nullable and unique only per connection, and a keyset ' +
1041
+ 'seek on it drops rows silently. Remove the sortKey override (pg_row_id is the ' +
1042
+ 'default), or read it from SEEK_KEYS in your generated types.',
903
1043
  );
904
1044
  }
905
1045
  }
@@ -907,24 +1047,31 @@ export async function selectPage<T = unknown>(
907
1047
  let nextCursor: string | null = null;
908
1048
  if (hasMore && rows.length > 0) {
909
1049
  const last = rows[rows.length - 1] as Record<string, unknown>;
910
- const lastValue = last[sortKey];
911
- // A null here means the seek key is nullable, which means it is not a valid
912
- // seek key (see the NOT NULL + UNIQUE rule above). There is no correct
913
- // cursor to mint \u2014 but returning \`nextCursor: null\` alongside \`hasMore\`
914
- // would tell the caller the list ENDED, which is the silent truncation this
915
- // whole path exists to avoid. Say it instead.
916
- if (lastValue == null) {
917
- throw new TurbobaseCursorError(
918
- \`cannot page "\${table}": the sort key "\${sortKey}" is null on the last row of this page, \` +
919
- 'so there are more rows but no valid cursor. A seek key must be NOT NULL and UNIQUE \u2014 ' +
920
- 'seek on pg_row_id if this table has one.',
921
- );
1050
+ const values: string[] = [];
1051
+ for (const col of seek) {
1052
+ const lastValue = last[col];
1053
+ // A null in ANY member means the seek key is nullable, which means it is
1054
+ // not a valid seek key (see the NOT NULL + UNIQUE rule above) \u2014 row-wise
1055
+ // comparison with a NULL member is not TRUE, so the rows carrying it are
1056
+ // dropped at the boundary. There is no correct cursor to mint \u2014 but
1057
+ // returning \`nextCursor: null\` alongside \`hasMore\` would tell the caller
1058
+ // the list ENDED, which is the silent truncation this whole path exists to
1059
+ // avoid. Say it instead.
1060
+ if (lastValue == null) {
1061
+ throw new TurbobaseCursorError(
1062
+ \`cannot page "\${table}": the sort key "\${col}" is null on the last row of this page, \` +
1063
+ 'so there are more rows but no valid cursor. A seek key must be NOT NULL and UNIQUE ' +
1064
+ 'in EVERY column \u2014 seek on pg_row_id if this table has one, or on the composite ' +
1065
+ '(parent_pg_row_id, line_index) for a line table.',
1066
+ );
1067
+ }
1068
+ values.push(String(lastValue));
922
1069
  }
923
- nextCursor = encodeCursor({ t: table, k: sortKey, v: String(lastValue), h: filterHash });
1070
+ nextCursor = encodeCursor({ c: 2, t: table, k: seek, v: values, d: dir, h: filterHash });
924
1071
  }
925
1072
  return { rows, nextCursor };
926
1073
  }
927
- `;xE="http://localhost:54331",kE="http://localhost:4100";TE=`node_modules/
1074
+ `,ls="src/types.ts",tR=`turbobase project types -o ${ls} || node -e "if(require('node:fs').existsSync('${ls}')){console.error('turbobase: could not refresh ${ls} (offline or signed out) - testing against the copy on disk, which may be stale.')}else{console.error('turbobase: ${ls} is missing. It is generated from the instance catalog and gitignored, so a fresh checkout has no copy. Run: turbobase auth login --base-url <your-instance> --token tb_pat_... , then turbobase project types -o ${ls}');process.exit(1)}"`;rR="http://localhost:54331",nR="http://localhost:4100";iR=`node_modules/
928
1075
  dist/
929
1076
  build/
930
1077
 
@@ -936,8 +1083,8 @@ build/
936
1083
  !.env.example
937
1084
 
938
1085
  .DS_Store
939
- `,Py=`${JSON.stringify({compilerOptions:{target:"ES2022",lib:["ES2022","DOM","DOM.Iterable"],module:"ESNext",moduleResolution:"bundler",jsx:"react-jsx",strict:!0,skipLibCheck:!0,noEmit:!0},include:["src"]},null,2)}
940
- `;Iy=`import React from 'react';
1086
+ `,Wy=`${JSON.stringify({compilerOptions:{target:"ES2022",lib:["ES2022","DOM","DOM.Iterable"],module:"ESNext",moduleResolution:"bundler",jsx:"react-jsx",strict:!0,skipLibCheck:!0,noEmit:!0},include:["src"]},null,2)}
1087
+ `;Yy=`import React from 'react';
941
1088
  import { createRoot } from 'react-dom/client';
942
1089
  import App from './App';
943
1090
  import './styles.css';
@@ -947,80 +1094,80 @@ createRoot(document.getElementById('root')!).render(
947
1094
  <App />
948
1095
  </React.StrictMode>,
949
1096
  );
950
- `,Oy=`:root { color-scheme: light; font-family: ui-sans-serif, system-ui, sans-serif; }
1097
+ `,Xy=`:root { color-scheme: light; font-family: ui-sans-serif, system-ui, sans-serif; }
951
1098
  * { box-sizing: border-box; }
952
1099
  body { margin: 0; background: #f8fafc; color: #0f172a; }
953
- `});var ns=O(()=>{_i()});function I(t,e,r){function n(a,c){var l;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(l=a._zod).traits??(l.traits=new Set),a._zod.traits.add(t),e(a,c);for(let u in i.prototype)u in a||Object.defineProperty(a,u,{value:i.prototype[u].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let l=r?.Parent?new s:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function St(t){return t&&Object.assign(Di,t),Di}var AE,kr,Di,so=O(()=>{AE=Object.freeze({status:"aborted"});kr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Di={}});var we={};Mo(we,{BIGINT_FORMAT_RANGES:()=>jy,Class:()=>Vl,NUMBER_FORMAT_RANGES:()=>Xl,aborted:()=>kn,allowsEval:()=>Gl,assert:()=>NE,assertEqual:()=>IE,assertIs:()=>CE,assertNever:()=>zE,assertNotEqual:()=>OE,assignProp:()=>Wl,cached:()=>is,captureStackTrace:()=>Zi,cleanEnum:()=>WE,cleanRegex:()=>cs,clone:()=>Tt,createTransparentProxy:()=>ZE,defineLazy:()=>Oe,esc:()=>xn,escapeRegex:()=>Dr,extend:()=>BE,finalizeIssue:()=>Wt,floatSafeRemainder:()=>Kl,getElementAtPath:()=>jE,getEnumValues:()=>ss,getLengthableOrigin:()=>ls,getParsedType:()=>UE,getSizableOrigin:()=>Ly,isObject:()=>io,isPlainObject:()=>ao,issue:()=>Ql,joinValues:()=>Ui,jsonStringifyReplacer:()=>Hl,merge:()=>VE,normalizeParams:()=>Q,nullish:()=>as,numKeys:()=>DE,omit:()=>FE,optionalKeys:()=>Yl,partial:()=>HE,pick:()=>qE,prefixIssues:()=>ar,primitiveTypes:()=>Ny,promiseAllObject:()=>LE,propertyKeyTypes:()=>Jl,randomString:()=>ME,required:()=>KE,stringifyPrimitive:()=>qi,unwrapMessage:()=>os});function IE(t){return t}function OE(t){return t}function CE(t){}function zE(t){throw new Error}function NE(t){}function ss(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function Ui(t,e="|"){return t.map(r=>qi(r)).join(e)}function Hl(t,e){return typeof e=="bigint"?e.toString():e}function is(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function as(t){return t==null}function cs(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Kl(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function Oe(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Wl(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function jE(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function LE(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function ME(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function xn(t){return JSON.stringify(t)}function io(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ao(t){if(io(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(io(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function DE(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function Dr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Tt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function Q(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function ZE(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function qi(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Yl(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function qE(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return Tt(t,{...t._zod.def,shape:r,checks:[]})}function FE(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return Tt(t,{...t._zod.def,shape:r,checks:[]})}function BE(t,e){if(!ao(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return Wl(this,"shape",n),n},checks:[]};return Tt(t,r)}function VE(t,e){return Tt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Wl(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function HE(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return Tt(e,{...e._zod.def,shape:o,checks:[]})}function KE(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return Tt(e,{...e._zod.def,shape:o,checks:[]})}function kn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function ar(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function os(t){return typeof t=="string"?t:t?.message}function Wt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=os(t.inst?._zod.def?.error?.(t))??os(e?.error?.(t))??os(r.customError?.(t))??os(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Ly(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function ls(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Ql(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function WE(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Zi,Gl,UE,Jl,Ny,Xl,jy,Vl,cr=O(()=>{Zi=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};Gl=is(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});UE=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Jl=new Set(["string","number","symbol"]),Ny=new Set(["string","number","bigint","boolean","symbol","undefined"]);Xl={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},jy={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Vl=class{constructor(...e){}}});function eu(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function tu(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(t),n}var My,Fi,us,ru=O(()=>{so();cr();My=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,Hl,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Fi=I("$ZodError",My),us=I("$ZodError",My,{Parent:Error})});var nu,ou,su,iu,au,$n,cu,Sn,lu=O(()=>{so();ru();cr();nu=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new kr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Wt(c,s,St())));throw Zi(a,o?.callee),a}return i.value},ou=nu(us),su=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Wt(c,s,St())));throw Zi(a,o?.callee),a}return i.value},iu=su(us),au=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new kr;return s.issues.length?{success:!1,error:new(t??Fi)(s.issues.map(i=>Wt(i,o,St())))}:{success:!0,data:s.value}},$n=au(us),cu=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>Wt(i,o,St())))}:{success:!0,data:s.value}},Sn=cu(us)});function Wy(){return new RegExp(JE,"u")}function ob(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function sb(t){return new RegExp(`^${ob(t)}$`)}function ib(t){let e=ob({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${rb}T(?:${n})$`)}var Dy,Uy,Zy,qy,Fy,By,Vy,Hy,uu,Ky,JE,Gy,Jy,Yy,Xy,Qy,du,eb,tb,rb,nb,ab,cb,lb,ub,db,pb,fb,Vi=O(()=>{Dy=/^[cC][^\s-]{8,}$/,Uy=/^[0-9a-z]+$/,Zy=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,qy=/^[0-9a-vA-V]{20}$/,Fy=/^[A-Za-z0-9]{27}$/,By=/^[a-zA-Z0-9_-]{21}$/,Vy=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Hy=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uu=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,Ky=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,JE="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";Gy=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Jy=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,Yy=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Xy=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Qy=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,du=/^[A-Za-z0-9_-]*$/,eb=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,tb=/^\+(?:[0-9]){6,14}[0-9]$/,rb="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",nb=new RegExp(`^${rb}$`);ab=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},cb=/^\d+$/,lb=/^-?\d+(?:\.\d+)?/i,ub=/true|false/i,db=/null/i,pb=/^[^A-Z]*$/,fb=/^[^a-z]*$/});var et,hb,pu,fu,mb,gb,yb,bb,wb,ds,_b,vb,xb,kb,$b,Sb,Tb,Hi=O(()=>{so();Vi();cr();et=I("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),hb={number:"number",bigint:"bigint",object:"date"},pu=I("$ZodCheckLessThan",(t,e)=>{et.init(t,e);let r=hb[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),fu=I("$ZodCheckGreaterThan",(t,e)=>{et.init(t,e);let r=hb[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),mb=I("$ZodCheckMultipleOf",(t,e)=>{et.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):Kl(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),gb=I("$ZodCheckNumberFormat",(t,e)=>{et.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Xl[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=cb)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}}),yb=I("$ZodCheckMaxLength",(t,e)=>{var r;et.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!as(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=ls(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),bb=I("$ZodCheckMinLength",(t,e)=>{var r;et.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!as(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=ls(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),wb=I("$ZodCheckLengthEquals",(t,e)=>{var r;et.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!as(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=ls(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),ds=I("$ZodCheckStringFormat",(t,e)=>{var r,n;et.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),_b=I("$ZodCheckRegex",(t,e)=>{ds.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),vb=I("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=pb),ds.init(t,e)}),xb=I("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=fb),ds.init(t,e)}),kb=I("$ZodCheckIncludes",(t,e)=>{et.init(t,e);let r=Dr(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),$b=I("$ZodCheckStartsWith",(t,e)=>{et.init(t,e);let r=new RegExp(`^${Dr(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),Sb=I("$ZodCheckEndsWith",(t,e)=>{et.init(t,e);let r=new RegExp(`.*${Dr(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),Tb=I("$ZodCheckOverwrite",(t,e)=>{et.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Ki,hu=O(()=>{Ki=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
1100
+ `});var us=O(()=>{Ti()});function I(t,e,r){function n(a,c){var l;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(l=a._zod).traits??(l.traits=new Set),a._zod.traits.add(t),e(a,c);for(let u in i.prototype)u in a||Object.defineProperty(a,u,{value:i.prototype[u].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let l=r?.Parent?new s:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function Et(t){return t&&Object.assign(Hi,t),Hi}var uR,kr,Hi,ao=O(()=>{uR=Object.freeze({status:"aborted"});kr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Hi={}});var _e={};qo(_e,{BIGINT_FORMAT_RANGES:()=>rb,Class:()=>Ql,NUMBER_FORMAT_RANGES:()=>iu,aborted:()=>kn,allowsEval:()=>nu,assert:()=>mR,assertEqual:()=>dR,assertIs:()=>fR,assertNever:()=>hR,assertNotEqual:()=>pR,assignProp:()=>ru,cached:()=>fs,captureStackTrace:()=>Gi,cleanEnum:()=>RR,cleanRegex:()=>ms,clone:()=>Rt,createTransparentProxy:()=>vR,defineLazy:()=>Oe,esc:()=>xn,escapeRegex:()=>Zr,extend:()=>$R,finalizeIssue:()=>Wt,floatSafeRemainder:()=>tu,getElementAtPath:()=>gR,getEnumValues:()=>ps,getLengthableOrigin:()=>gs,getParsedType:()=>_R,getSizableOrigin:()=>nb,isObject:()=>co,isPlainObject:()=>lo,issue:()=>au,joinValues:()=>Ki,jsonStringifyReplacer:()=>eu,merge:()=>SR,normalizeParams:()=>te,nullish:()=>hs,numKeys:()=>wR,omit:()=>kR,optionalKeys:()=>su,partial:()=>TR,pick:()=>xR,prefixIssues:()=>ar,primitiveTypes:()=>tb,promiseAllObject:()=>yR,propertyKeyTypes:()=>ou,randomString:()=>bR,required:()=>ER,stringifyPrimitive:()=>Wi,unwrapMessage:()=>ds});function dR(t){return t}function pR(t){return t}function fR(t){}function hR(t){throw new Error}function mR(t){}function ps(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function Ki(t,e="|"){return t.map(r=>Wi(r)).join(e)}function eu(t,e){return typeof e=="bigint"?e.toString():e}function fs(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function hs(t){return t==null}function ms(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function tu(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function Oe(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function ru(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function gR(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function yR(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function bR(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function xn(t){return JSON.stringify(t)}function co(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function lo(t){if(co(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(co(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function wR(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function Zr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Rt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function te(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function vR(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function Wi(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function su(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function xR(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return Rt(t,{...t._zod.def,shape:r,checks:[]})}function kR(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return Rt(t,{...t._zod.def,shape:r,checks:[]})}function $R(t,e){if(!lo(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return ru(this,"shape",n),n},checks:[]};return Rt(t,r)}function SR(t,e){return Rt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return ru(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function TR(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return Rt(e,{...e._zod.def,shape:o,checks:[]})}function ER(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return Rt(e,{...e._zod.def,shape:o,checks:[]})}function kn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function ar(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function ds(t){return typeof t=="string"?t:t?.message}function Wt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=ds(t.inst?._zod.def?.error?.(t))??ds(e?.error?.(t))??ds(r.customError?.(t))??ds(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function nb(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function gs(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function au(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function RR(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Gi,nu,_R,ou,tb,iu,rb,Ql,cr=O(()=>{Gi=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};nu=fs(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});_R=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},ou=new Set(["string","number","symbol"]),tb=new Set(["string","number","bigint","boolean","symbol","undefined"]);iu={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},rb={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Ql=class{constructor(...e){}}});function cu(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function lu(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(t),n}var ob,Ji,ys,uu=O(()=>{ao();cr();ob=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,eu,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Ji=I("$ZodError",ob),ys=I("$ZodError",ob,{Parent:Error})});var du,pu,fu,hu,mu,$n,gu,Sn,yu=O(()=>{ao();uu();cr();du=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new kr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Wt(c,s,Et())));throw Gi(a,o?.callee),a}return i.value},pu=du(ys),fu=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Wt(c,s,Et())));throw Gi(a,o?.callee),a}return i.value},hu=fu(ys),mu=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new kr;return s.issues.length?{success:!1,error:new(t??Ji)(s.issues.map(i=>Wt(i,o,Et())))}:{success:!0,data:s.value}},$n=mu(ys),gu=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>Wt(i,o,Et())))}:{success:!0,data:s.value}},Sn=gu(ys)});function hb(){return new RegExp(AR,"u")}function $b(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Sb(t){return new RegExp(`^${$b(t)}$`)}function Tb(t){let e=$b({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${xb}T(?:${n})$`)}var sb,ib,ab,cb,lb,ub,db,pb,bu,fb,AR,mb,gb,yb,bb,wb,wu,_b,vb,xb,kb,Eb,Rb,Pb,Ab,Ib,Ob,Cb,Xi=O(()=>{sb=/^[cC][^\s-]{8,}$/,ib=/^[0-9a-z]+$/,ab=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,cb=/^[0-9a-vA-V]{20}$/,lb=/^[A-Za-z0-9]{27}$/,ub=/^[a-zA-Z0-9_-]{21}$/,db=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,pb=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,bu=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,fb=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,AR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";mb=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,gb=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,yb=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,bb=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,wb=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,wu=/^[A-Za-z0-9_-]*$/,_b=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,vb=/^\+(?:[0-9]){6,14}[0-9]$/,xb="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",kb=new RegExp(`^${xb}$`);Eb=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Rb=/^\d+$/,Pb=/^-?\d+(?:\.\d+)?/i,Ab=/true|false/i,Ib=/null/i,Ob=/^[^A-Z]*$/,Cb=/^[^a-z]*$/});var tt,zb,_u,vu,Nb,jb,Lb,Db,Mb,bs,Ub,Zb,qb,Fb,Bb,Vb,Hb,Qi=O(()=>{ao();Xi();cr();tt=I("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),zb={number:"number",bigint:"bigint",object:"date"},_u=I("$ZodCheckLessThan",(t,e)=>{tt.init(t,e);let r=zb[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),vu=I("$ZodCheckGreaterThan",(t,e)=>{tt.init(t,e);let r=zb[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Nb=I("$ZodCheckMultipleOf",(t,e)=>{tt.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):tu(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),jb=I("$ZodCheckNumberFormat",(t,e)=>{tt.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=iu[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=Rb)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}}),Lb=I("$ZodCheckMaxLength",(t,e)=>{var r;tt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!hs(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=gs(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Db=I("$ZodCheckMinLength",(t,e)=>{var r;tt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!hs(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=gs(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Mb=I("$ZodCheckLengthEquals",(t,e)=>{var r;tt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!hs(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=gs(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),bs=I("$ZodCheckStringFormat",(t,e)=>{var r,n;tt.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),Ub=I("$ZodCheckRegex",(t,e)=>{bs.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Zb=I("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Ob),bs.init(t,e)}),qb=I("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Cb),bs.init(t,e)}),Fb=I("$ZodCheckIncludes",(t,e)=>{tt.init(t,e);let r=Zr(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Bb=I("$ZodCheckStartsWith",(t,e)=>{tt.init(t,e);let r=new RegExp(`^${Zr(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),Vb=I("$ZodCheckEndsWith",(t,e)=>{tt.init(t,e);let r=new RegExp(`.*${Zr(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),Hb=I("$ZodCheckOverwrite",(t,e)=>{tt.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var ea,xu=O(()=>{ea=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
954
1101
  `).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...r,o.join(`
955
- `))}}});var Rb,mu=O(()=>{Rb={major:4,minor:0,patch:0}});function qb(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function YE(t){if(!du.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return qb(r)}function XE(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function Pb(t,e,r){t.issues.length&&e.issues.push(...ar(r,t.issues)),e.value[r]=t.value}function Wi(t,e,r){t.issues.length&&e.issues.push(...ar(r,t.issues)),e.value[r]=t.value}function Ab(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...ar(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function Ib(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>Wt(s,n,St())))}),e}function gu(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(ao(t)&&ao(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=gu(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],i=gu(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Ob(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),kn(t))return t;let n=gu(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}function Cb(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function zb(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function Nb(t,e,r){return kn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function jb(t){return t.value=Object.freeze(t.value),t}function Lb(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(Ql(o))}}var Pe,ps,Ce,yu,bu,wu,_u,vu,xu,ku,$u,Su,Tu,Eu,Mb,Db,Ub,Zb,Ru,Pu,Au,Iu,Ou,Cu,zu,Nu,Gi,ju,Lu,Mu,Du,Uu,Zu,Ji,Yi,qu,Fu,Bu,Vu,Hu,Ku,Wu,Gu,Ju,Yu,Xu,Qu,ed,td,rd,Fb=O(()=>{Hi();so();hu();lu();Vi();cr();mu();cr();Pe=I("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Rb;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=kn(s),l;for(let u of i){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,b=u._zod.check(s);if(b instanceof Promise&&a?.async===!1)throw new kr;if(l||b instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await b,s.issues.length!==d&&(c||(c=kn(s,d)))});else{if(s.issues.length===d)continue;c||(c=kn(s,d))}}return l?l.then(()=>s):s};t._zod.run=(s,i)=>{let a=t._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new kr;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=$n(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Sn(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),ps=I("$ZodString",(t,e)=>{Pe.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??ab(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),Ce=I("$ZodStringFormat",(t,e)=>{ds.init(t,e),ps.init(t,e)}),yu=I("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Hy),Ce.init(t,e)}),bu=I("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=uu(n))}else e.pattern??(e.pattern=uu());Ce.init(t,e)}),wu=I("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Ky),Ce.init(t,e)}),_u=I("$ZodURL",(t,e)=>{Ce.init(t,e),t._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:eb.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),vu=I("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Wy()),Ce.init(t,e)}),xu=I("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=By),Ce.init(t,e)}),ku=I("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Dy),Ce.init(t,e)}),$u=I("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Uy),Ce.init(t,e)}),Su=I("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Zy),Ce.init(t,e)}),Tu=I("$ZodXID",(t,e)=>{e.pattern??(e.pattern=qy),Ce.init(t,e)}),Eu=I("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Fy),Ce.init(t,e)}),Mb=I("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=ib(e)),Ce.init(t,e)}),Db=I("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=nb),Ce.init(t,e)}),Ub=I("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=sb(e)),Ce.init(t,e)}),Zb=I("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Vy),Ce.init(t,e)}),Ru=I("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Gy),Ce.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Pu=I("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Jy),Ce.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),Au=I("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Yy),Ce.init(t,e)}),Iu=I("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Xy),Ce.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});Ou=I("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Qy),Ce.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{qb(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});Cu=I("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=du),Ce.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{YE(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),zu=I("$ZodE164",(t,e)=>{e.pattern??(e.pattern=tb),Ce.init(t,e)});Nu=I("$ZodJWT",(t,e)=>{Ce.init(t,e),t._zod.check=r=>{XE(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Gi=I("$ZodNumber",(t,e)=>{Pe.init(t,e),t._zod.pattern=t._zod.bag.pattern??lb,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),ju=I("$ZodNumber",(t,e)=>{gb.init(t,e),Gi.init(t,e)}),Lu=I("$ZodBoolean",(t,e)=>{Pe.init(t,e),t._zod.pattern=ub,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}}),Mu=I("$ZodNull",(t,e)=>{Pe.init(t,e),t._zod.pattern=db,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}}),Du=I("$ZodUnknown",(t,e)=>{Pe.init(t,e),t._zod.parse=r=>r}),Uu=I("$ZodNever",(t,e)=>{Pe.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});Zu=I("$ZodArray",(t,e)=>{Pe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(l=>Pb(l,r,i))):Pb(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});Ji=I("$ZodObject",(t,e)=>{Pe.init(t,e);let r=is(()=>{let d=Object.keys(e.shape);for(let m of d)if(!(e.shape[m]instanceof Pe))throw new Error(`Invalid element at key "${m}": expected a Zod schema`);let b=Yl(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(b)}});Oe(t._zod,"propValues",()=>{let d=e.shape,b={};for(let m in d){let f=d[m]._zod;if(f.values){b[m]??(b[m]=new Set);for(let y of f.values)b[m].add(y)}}return b});let n=d=>{let b=new Ki(["shape","payload","ctx"]),m=r.value,f=R=>{let z=xn(R);return`shape[${z}]._zod.run({ value: input[${z}], issues: [] }, ctx)`};b.write("const input = payload.value;");let y=Object.create(null),v=0;for(let R of m.keys)y[R]=`key_${v++}`;b.write("const newResult = {}");for(let R of m.keys)if(m.optionalKeys.has(R)){let z=y[R];b.write(`const ${z} = ${f(R)};`);let V=xn(R);b.write(`
1102
+ `))}}});var Gb,ku=O(()=>{Gb={major:4,minor:0,patch:0}});function cw(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function IR(t){if(!wu.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return cw(r)}function OR(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function Wb(t,e,r){t.issues.length&&e.issues.push(...ar(r,t.issues)),e.value[r]=t.value}function ta(t,e,r){t.issues.length&&e.issues.push(...ar(r,t.issues)),e.value[r]=t.value}function Jb(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...ar(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function Yb(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>Wt(s,n,Et())))}),e}function $u(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(lo(t)&&lo(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=$u(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],i=$u(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Xb(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),kn(t))return t;let n=$u(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}function Qb(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function ew(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function tw(t,e,r){return kn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function rw(t){return t.value=Object.freeze(t.value),t}function nw(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(au(o))}}var Pe,ws,Ce,Su,Tu,Eu,Ru,Pu,Au,Iu,Ou,Cu,zu,Nu,ow,sw,iw,aw,ju,Lu,Du,Mu,Uu,Zu,qu,Fu,ra,Bu,Vu,Hu,Ku,Gu,Wu,na,oa,Ju,Yu,Xu,Qu,ed,td,rd,nd,od,sd,id,ad,cd,ld,ud,lw=O(()=>{Qi();ao();xu();yu();Xi();cr();ku();cr();Pe=I("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Gb;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=kn(s),l;for(let u of i){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,b=u._zod.check(s);if(b instanceof Promise&&a?.async===!1)throw new kr;if(l||b instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await b,s.issues.length!==d&&(c||(c=kn(s,d)))});else{if(s.issues.length===d)continue;c||(c=kn(s,d))}}return l?l.then(()=>s):s};t._zod.run=(s,i)=>{let a=t._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new kr;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=$n(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Sn(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),ws=I("$ZodString",(t,e)=>{Pe.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Eb(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),Ce=I("$ZodStringFormat",(t,e)=>{bs.init(t,e),ws.init(t,e)}),Su=I("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=pb),Ce.init(t,e)}),Tu=I("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=bu(n))}else e.pattern??(e.pattern=bu());Ce.init(t,e)}),Eu=I("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=fb),Ce.init(t,e)}),Ru=I("$ZodURL",(t,e)=>{Ce.init(t,e),t._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:_b.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),Pu=I("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=hb()),Ce.init(t,e)}),Au=I("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=ub),Ce.init(t,e)}),Iu=I("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=sb),Ce.init(t,e)}),Ou=I("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=ib),Ce.init(t,e)}),Cu=I("$ZodULID",(t,e)=>{e.pattern??(e.pattern=ab),Ce.init(t,e)}),zu=I("$ZodXID",(t,e)=>{e.pattern??(e.pattern=cb),Ce.init(t,e)}),Nu=I("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=lb),Ce.init(t,e)}),ow=I("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Tb(e)),Ce.init(t,e)}),sw=I("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=kb),Ce.init(t,e)}),iw=I("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Sb(e)),Ce.init(t,e)}),aw=I("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=db),Ce.init(t,e)}),ju=I("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=mb),Ce.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Lu=I("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=gb),Ce.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),Du=I("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=yb),Ce.init(t,e)}),Mu=I("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=bb),Ce.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});Uu=I("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=wb),Ce.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{cw(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});Zu=I("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=wu),Ce.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{IR(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),qu=I("$ZodE164",(t,e)=>{e.pattern??(e.pattern=vb),Ce.init(t,e)});Fu=I("$ZodJWT",(t,e)=>{Ce.init(t,e),t._zod.check=r=>{OR(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),ra=I("$ZodNumber",(t,e)=>{Pe.init(t,e),t._zod.pattern=t._zod.bag.pattern??Pb,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),Bu=I("$ZodNumber",(t,e)=>{jb.init(t,e),ra.init(t,e)}),Vu=I("$ZodBoolean",(t,e)=>{Pe.init(t,e),t._zod.pattern=Ab,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}}),Hu=I("$ZodNull",(t,e)=>{Pe.init(t,e),t._zod.pattern=Ib,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}}),Ku=I("$ZodUnknown",(t,e)=>{Pe.init(t,e),t._zod.parse=r=>r}),Gu=I("$ZodNever",(t,e)=>{Pe.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});Wu=I("$ZodArray",(t,e)=>{Pe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(l=>Wb(l,r,i))):Wb(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});na=I("$ZodObject",(t,e)=>{Pe.init(t,e);let r=fs(()=>{let d=Object.keys(e.shape);for(let m of d)if(!(e.shape[m]instanceof Pe))throw new Error(`Invalid element at key "${m}": expected a Zod schema`);let b=su(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(b)}});Oe(t._zod,"propValues",()=>{let d=e.shape,b={};for(let m in d){let f=d[m]._zod;if(f.values){b[m]??(b[m]=new Set);for(let y of f.values)b[m].add(y)}}return b});let n=d=>{let b=new ea(["shape","payload","ctx"]),m=r.value,f=R=>{let z=xn(R);return`shape[${z}]._zod.run({ value: input[${z}], issues: [] }, ctx)`};b.write("const input = payload.value;");let y=Object.create(null),v=0;for(let R of m.keys)y[R]=`key_${v++}`;b.write("const newResult = {}");for(let R of m.keys)if(m.optionalKeys.has(R)){let z=y[R];b.write(`const ${z} = ${f(R)};`);let H=xn(R);b.write(`
956
1103
  if (${z}.issues.length) {
957
- if (input[${V}] === undefined) {
958
- if (${V} in input) {
959
- newResult[${V}] = undefined;
1104
+ if (input[${H}] === undefined) {
1105
+ if (${H} in input) {
1106
+ newResult[${H}] = undefined;
960
1107
  }
961
1108
  } else {
962
1109
  payload.issues = payload.issues.concat(
963
1110
  ${z}.issues.map((iss) => ({
964
1111
  ...iss,
965
- path: iss.path ? [${V}, ...iss.path] : [${V}],
1112
+ path: iss.path ? [${H}, ...iss.path] : [${H}],
966
1113
  }))
967
1114
  );
968
1115
  }
969
1116
  } else if (${z}.value === undefined) {
970
- if (${V} in input) newResult[${V}] = undefined;
1117
+ if (${H} in input) newResult[${H}] = undefined;
971
1118
  } else {
972
- newResult[${V}] = ${z}.value;
1119
+ newResult[${H}] = ${z}.value;
973
1120
  }
974
1121
  `)}else{let z=y[R];b.write(`const ${z} = ${f(R)};`),b.write(`
975
1122
  if (${z}.issues.length) payload.issues = payload.issues.concat(${z}.issues.map(iss => ({
976
1123
  ...iss,
977
1124
  path: iss.path ? [${xn(R)}, ...iss.path] : [${xn(R)}]
978
- })));`),b.write(`newResult[${xn(R)}] = ${z}.value`)}b.write("payload.value = newResult;"),b.write("return payload;");let E=b.compile();return(R,z)=>E(d,R,z)},o,s=io,i=!Di.jitless,c=i&&Gl.value,l=e.catchall,u;t._zod.parse=(d,b)=>{u??(u=r.value);let m=d.value;if(!s(m))return d.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),d;let f=[];if(i&&c&&b?.async===!1&&b.jitless!==!0)o||(o=n(e.shape)),d=o(d,b);else{d.value={};let z=u.shape;for(let V of u.keys){let J=z[V],He=J._zod.run({value:m[V],issues:[]},b),Xe=J._zod.optin==="optional"&&J._zod.optout==="optional";He instanceof Promise?f.push(He.then(Rr=>Xe?Ab(Rr,d,V,m):Wi(Rr,d,V))):Xe?Ab(He,d,V,m):Wi(He,d,V)}}if(!l)return f.length?Promise.all(f).then(()=>d):d;let y=[],v=u.keySet,E=l._zod,R=E.def.type;for(let z of Object.keys(m)){if(v.has(z))continue;if(R==="never"){y.push(z);continue}let V=E.run({value:m[z],issues:[]},b);V instanceof Promise?f.push(V.then(J=>Wi(J,d,z))):Wi(V,d,z)}return y.length&&d.issues.push({code:"unrecognized_keys",keys:y,input:m,inst:t}),f.length?Promise.all(f).then(()=>d):d}});Yi=I("$ZodUnion",(t,e)=>{Pe.init(t,e),Oe(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Oe(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Oe(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Oe(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>cs(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>Ib(i,r,t,n)):Ib(s,r,t,n)}}),qu=I("$ZodDiscriminatedUnion",(t,e)=>{Yi.init(t,e);let r=t._zod.parse;Oe(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let l of c)o[a].add(l)}}return o});let n=is(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!io(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),Fu=I("$ZodIntersection",(t,e)=>{Pe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,l])=>Ob(r,c,l)):Ob(r,s,i)}});Bu=I("$ZodRecord",(t,e)=>{Pe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!ao(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let l=e.valueType._zod.run({value:o[c],issues:[]},n);l instanceof Promise?s.push(l.then(u=>{u.issues.length&&r.issues.push(...ar(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...ar(c,l.issues)),r.value[c]=l.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(l=>Wt(l,n,St())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(l=>{l.issues.length&&r.issues.push(...ar(i,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...ar(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Vu=I("$ZodEnum",(t,e)=>{Pe.init(t,e);let r=ss(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Jl.has(typeof n)).map(n=>typeof n=="string"?Dr(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),Hu=I("$ZodLiteral",(t,e)=>{Pe.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Dr(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}}),Ku=I("$ZodTransform",(t,e)=>{Pe.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new kr;return r.value=o,r}}),Wu=I("$ZodOptional",(t,e)=>{Pe.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Oe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Oe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${cs(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),Gu=I("$ZodNullable",(t,e)=>{Pe.init(t,e),Oe(t._zod,"optin",()=>e.innerType._zod.optin),Oe(t._zod,"optout",()=>e.innerType._zod.optout),Oe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${cs(r.source)}|null)$`):void 0}),Oe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Ju=I("$ZodDefault",(t,e)=>{Pe.init(t,e),t._zod.optin="optional",Oe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Cb(s,e)):Cb(o,e)}});Yu=I("$ZodPrefault",(t,e)=>{Pe.init(t,e),t._zod.optin="optional",Oe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),Xu=I("$ZodNonOptional",(t,e)=>{Pe.init(t,e),Oe(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>zb(s,t)):zb(o,t)}});Qu=I("$ZodCatch",(t,e)=>{Pe.init(t,e),t._zod.optin="optional",Oe(t._zod,"optout",()=>e.innerType._zod.optout),Oe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>Wt(i,n,St()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>Wt(s,n,St()))},input:r.value}),r.issues=[]),r)}}),ed=I("$ZodPipe",(t,e)=>{Pe.init(t,e),Oe(t._zod,"values",()=>e.in._zod.values),Oe(t._zod,"optin",()=>e.in._zod.optin),Oe(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>Nb(s,e,n)):Nb(o,e,n)}});td=I("$ZodReadonly",(t,e)=>{Pe.init(t,e),Oe(t._zod,"propValues",()=>e.innerType._zod.propValues),Oe(t._zod,"values",()=>e.innerType._zod.values),Oe(t._zod,"optin",()=>e.innerType._zod.optin),Oe(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(jb):jb(o)}});rd=I("$ZodCustom",(t,e)=>{et.init(t,e),Pe.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>Lb(s,r,n,t));Lb(o,r,n,t)}})});function Bb(){return{localeError:eR()}}var QE,eR,Vb=O(()=>{cr();QE=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},eR=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${QE(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${qi(n.values[0])}`:`Invalid option: expected one of ${Ui(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Ui(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}}});var Xi=O(()=>{});function Hb(){return new fs}var fs,Ur,od=O(()=>{fs=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};Ur=Hb()});function sd(t,e){return new t({type:"string",...Q(e)})}function id(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...Q(e)})}function Qi(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...Q(e)})}function ad(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...Q(e)})}function cd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Q(e)})}function ld(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Q(e)})}function ud(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Q(e)})}function dd(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...Q(e)})}function pd(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...Q(e)})}function fd(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...Q(e)})}function hd(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...Q(e)})}function md(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...Q(e)})}function gd(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...Q(e)})}function yd(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...Q(e)})}function bd(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...Q(e)})}function wd(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...Q(e)})}function _d(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...Q(e)})}function vd(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Q(e)})}function xd(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Q(e)})}function kd(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...Q(e)})}function $d(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...Q(e)})}function Sd(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...Q(e)})}function Td(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...Q(e)})}function Kb(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Q(e)})}function Wb(t,e){return new t({type:"string",format:"date",check:"string_format",...Q(e)})}function Gb(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...Q(e)})}function Jb(t,e){return new t({type:"string",format:"duration",check:"string_format",...Q(e)})}function Ed(t,e){return new t({type:"number",checks:[],...Q(e)})}function Rd(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...Q(e)})}function Pd(t,e){return new t({type:"boolean",...Q(e)})}function Ad(t,e){return new t({type:"null",...Q(e)})}function Id(t){return new t({type:"unknown"})}function Od(t,e){return new t({type:"never",...Q(e)})}function ea(t,e){return new pu({check:"less_than",...Q(e),value:t,inclusive:!1})}function hs(t,e){return new pu({check:"less_than",...Q(e),value:t,inclusive:!0})}function ta(t,e){return new fu({check:"greater_than",...Q(e),value:t,inclusive:!1})}function ms(t,e){return new fu({check:"greater_than",...Q(e),value:t,inclusive:!0})}function ra(t,e){return new mb({check:"multiple_of",...Q(e),value:t})}function na(t,e){return new yb({check:"max_length",...Q(e),maximum:t})}function co(t,e){return new bb({check:"min_length",...Q(e),minimum:t})}function oa(t,e){return new wb({check:"length_equals",...Q(e),length:t})}function Cd(t,e){return new _b({check:"string_format",format:"regex",...Q(e),pattern:t})}function zd(t){return new vb({check:"string_format",format:"lowercase",...Q(t)})}function Nd(t){return new xb({check:"string_format",format:"uppercase",...Q(t)})}function jd(t,e){return new kb({check:"string_format",format:"includes",...Q(e),includes:t})}function Ld(t,e){return new $b({check:"string_format",format:"starts_with",...Q(e),prefix:t})}function Md(t,e){return new Sb({check:"string_format",format:"ends_with",...Q(e),suffix:t})}function Tn(t){return new Tb({check:"overwrite",tx:t})}function Dd(t){return Tn(e=>e.normalize(t))}function Ud(){return Tn(t=>t.trim())}function Zd(){return Tn(t=>t.toLowerCase())}function qd(){return Tn(t=>t.toUpperCase())}function Yb(t,e,r){return new t({type:"array",element:e,...Q(r)})}function Fd(t,e,r){let n=Q(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Bd(t,e,r){return new t({type:"custom",check:"custom",fn:e,...Q(r)})}var Xb=O(()=>{Hi();cr()});var Qb=O(()=>{});function Vd(t,e){if(t instanceof fs){let n=new sa(e),o={};for(let a of t._idmap.entries()){let[c,l]=a;n.process(l)}let s={},i={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[c,l]=a;s[c]=n.emit(l,{...e,external:i})}if(Object.keys(o).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let r=new sa(e);return r.process(t),r.emit(t,e)}function Ge(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Ge(o.element,r);case"object":{for(let s in o.shape)if(Ge(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(Ge(s,r))return!0;return!1}case"intersection":return Ge(o.left,r)||Ge(o.right,r);case"tuple":{for(let s of o.items)if(Ge(s,r))return!0;return!!(o.rest&&Ge(o.rest,r))}case"record":return Ge(o.keyType,r)||Ge(o.valueType,r);case"map":return Ge(o.keyType,r)||Ge(o.valueType,r);case"set":return Ge(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ge(o.innerType,r);case"lazy":return Ge(o.getter(),r);case"default":return Ge(o.innerType,r);case"prefault":return Ge(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Ge(o.in,r)||Ge(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var sa,ew=O(()=>{od();cr();sa=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Ur,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path},b=e._zod.parent;if(b)a.ref=b,this.process(b,d),this.seen.get(b).isParent=!0;else{let m=a.schema;switch(o.type){case"string":{let f=m;f.type="string";let{minimum:y,maximum:v,format:E,patterns:R,contentEncoding:z}=e._zod.bag;if(typeof y=="number"&&(f.minLength=y),typeof v=="number"&&(f.maxLength=v),E&&(f.format=s[E]??E,f.format===""&&delete f.format),z&&(f.contentEncoding=z),R&&R.size>0){let V=[...R];V.length===1?f.pattern=V[0].source:V.length>1&&(a.schema.allOf=[...V.map(J=>({...this.target==="draft-7"?{type:"string"}:{},pattern:J.source}))])}break}case"number":{let f=m,{minimum:y,maximum:v,format:E,multipleOf:R,exclusiveMaximum:z,exclusiveMinimum:V}=e._zod.bag;typeof E=="string"&&E.includes("int")?f.type="integer":f.type="number",typeof V=="number"&&(f.exclusiveMinimum=V),typeof y=="number"&&(f.minimum=y,typeof V=="number"&&(V>=y?delete f.minimum:delete f.exclusiveMinimum)),typeof z=="number"&&(f.exclusiveMaximum=z),typeof v=="number"&&(f.maximum=v,typeof z=="number"&&(z<=v?delete f.maximum:delete f.exclusiveMaximum)),typeof R=="number"&&(f.multipleOf=R);break}case"boolean":{let f=m;f.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{m.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{m.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let f=m,{minimum:y,maximum:v}=e._zod.bag;typeof y=="number"&&(f.minItems=y),typeof v=="number"&&(f.maxItems=v),f.type="array",f.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let f=m;f.type="object",f.properties={};let y=o.shape;for(let R in y)f.properties[R]=this.process(y[R],{...d,path:[...d.path,"properties",R]});let v=new Set(Object.keys(y)),E=new Set([...v].filter(R=>{let z=o.shape[R]._zod;return this.io==="input"?z.optin===void 0:z.optout===void 0}));E.size>0&&(f.required=Array.from(E)),o.catchall?._zod.def.type==="never"?f.additionalProperties=!1:o.catchall?o.catchall&&(f.additionalProperties=this.process(o.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(f.additionalProperties=!1);break}case"union":{let f=m;f.anyOf=o.options.map((y,v)=>this.process(y,{...d,path:[...d.path,"anyOf",v]}));break}case"intersection":{let f=m,y=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),v=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),E=z=>"allOf"in z&&Object.keys(z).length===1,R=[...E(y)?y.allOf:[y],...E(v)?v.allOf:[v]];f.allOf=R;break}case"tuple":{let f=m;f.type="array";let y=o.items.map((R,z)=>this.process(R,{...d,path:[...d.path,"prefixItems",z]}));if(this.target==="draft-2020-12"?f.prefixItems=y:f.items=y,o.rest){let R=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?f.items=R:f.additionalItems=R}o.rest&&(f.items=this.process(o.rest,{...d,path:[...d.path,"items"]}));let{minimum:v,maximum:E}=e._zod.bag;typeof v=="number"&&(f.minItems=v),typeof E=="number"&&(f.maxItems=E);break}case"record":{let f=m;f.type="object",f.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),f.additionalProperties=this.process(o.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let f=m,y=ss(o.entries);y.every(v=>typeof v=="number")&&(f.type="number"),y.every(v=>typeof v=="string")&&(f.type="string"),f.enum=y;break}case"literal":{let f=m,y=[];for(let v of o.values)if(v===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof v=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");y.push(Number(v))}else y.push(v);if(y.length!==0)if(y.length===1){let v=y[0];f.type=v===null?"null":typeof v,f.const=v}else y.every(v=>typeof v=="number")&&(f.type="number"),y.every(v=>typeof v=="string")&&(f.type="string"),y.every(v=>typeof v=="boolean")&&(f.type="string"),y.every(v=>v===null)&&(f.type="null"),f.enum=y;break}case"file":{let f=m,y={type:"string",format:"binary",contentEncoding:"binary"},{minimum:v,maximum:E,mime:R}=e._zod.bag;v!==void 0&&(y.minLength=v),E!==void 0&&(y.maxLength=E),R?R.length===1?(y.contentMediaType=R[0],Object.assign(f,y)):f.anyOf=R.map(z=>({...y,contentMediaType:z})):Object.assign(f,y);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let f=this.process(o.innerType,d);m.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let f=m;f.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,m.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(m._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),a.ref=o.innerType;let f;try{f=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}m.default=f;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let f=m,y=e._zod.pattern;if(!y)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=y.source;break}case"pipe":{let f=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(f,d),a.ref=f;break}case"readonly":{this.process(o.innerType,d),a.ref=o.innerType,m.readOnly=!0;break}case"promise":{this.process(o.innerType,d),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"lazy":{let f=e._zod.innerType;this.process(f,d),a.ref=f;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let l=this.metadataRegistry.get(e);return l&&Object.assign(a.schema,l),this.io==="input"&&Ge(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=u=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let y=n.external.registry.get(u[0])?.id,v=n.external.uri??(R=>R);if(y)return{ref:v(y)};let E=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=E,{defId:E,ref:`${v("__shared")}#/${d}/${E}`}}if(u[1]===o)return{ref:"#"};let m=`#/${d}/`,f=u[1].schema.id??`__schema${this.counter++}`;return{defId:f,ref:m+f}},i=u=>{if(u[1].schema.$ref)return;let d=u[1],{ref:b,defId:m}=s(u);d.def={...d.schema},m&&(d.defId=m);let f=d.schema;for(let y in f)delete f[y];f.$ref=b};if(n.cycles==="throw")for(let u of this.seen.entries()){let d=u[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
1125
+ })));`),b.write(`newResult[${xn(R)}] = ${z}.value`)}b.write("payload.value = newResult;"),b.write("return payload;");let E=b.compile();return(R,z)=>E(d,R,z)},o,s=co,i=!Hi.jitless,c=i&&nu.value,l=e.catchall,u;t._zod.parse=(d,b)=>{u??(u=r.value);let m=d.value;if(!s(m))return d.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),d;let f=[];if(i&&c&&b?.async===!1&&b.jitless!==!0)o||(o=n(e.shape)),d=o(d,b);else{d.value={};let z=u.shape;for(let H of u.keys){let Y=z[H],He=Y._zod.run({value:m[H],issues:[]},b),Qe=Y._zod.optin==="optional"&&Y._zod.optout==="optional";He instanceof Promise?f.push(He.then(Rr=>Qe?Jb(Rr,d,H,m):ta(Rr,d,H))):Qe?Jb(He,d,H,m):ta(He,d,H)}}if(!l)return f.length?Promise.all(f).then(()=>d):d;let y=[],v=u.keySet,E=l._zod,R=E.def.type;for(let z of Object.keys(m)){if(v.has(z))continue;if(R==="never"){y.push(z);continue}let H=E.run({value:m[z],issues:[]},b);H instanceof Promise?f.push(H.then(Y=>ta(Y,d,z))):ta(H,d,z)}return y.length&&d.issues.push({code:"unrecognized_keys",keys:y,input:m,inst:t}),f.length?Promise.all(f).then(()=>d):d}});oa=I("$ZodUnion",(t,e)=>{Pe.init(t,e),Oe(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Oe(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Oe(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Oe(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>ms(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>Yb(i,r,t,n)):Yb(s,r,t,n)}}),Ju=I("$ZodDiscriminatedUnion",(t,e)=>{oa.init(t,e);let r=t._zod.parse;Oe(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let l of c)o[a].add(l)}}return o});let n=fs(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!co(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),Yu=I("$ZodIntersection",(t,e)=>{Pe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,l])=>Xb(r,c,l)):Xb(r,s,i)}});Xu=I("$ZodRecord",(t,e)=>{Pe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!lo(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let l=e.valueType._zod.run({value:o[c],issues:[]},n);l instanceof Promise?s.push(l.then(u=>{u.issues.length&&r.issues.push(...ar(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...ar(c,l.issues)),r.value[c]=l.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(l=>Wt(l,n,Et())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(l=>{l.issues.length&&r.issues.push(...ar(i,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...ar(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Qu=I("$ZodEnum",(t,e)=>{Pe.init(t,e);let r=ps(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>ou.has(typeof n)).map(n=>typeof n=="string"?Zr(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),ed=I("$ZodLiteral",(t,e)=>{Pe.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Zr(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}}),td=I("$ZodTransform",(t,e)=>{Pe.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new kr;return r.value=o,r}}),rd=I("$ZodOptional",(t,e)=>{Pe.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Oe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Oe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${ms(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),nd=I("$ZodNullable",(t,e)=>{Pe.init(t,e),Oe(t._zod,"optin",()=>e.innerType._zod.optin),Oe(t._zod,"optout",()=>e.innerType._zod.optout),Oe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${ms(r.source)}|null)$`):void 0}),Oe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),od=I("$ZodDefault",(t,e)=>{Pe.init(t,e),t._zod.optin="optional",Oe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Qb(s,e)):Qb(o,e)}});sd=I("$ZodPrefault",(t,e)=>{Pe.init(t,e),t._zod.optin="optional",Oe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),id=I("$ZodNonOptional",(t,e)=>{Pe.init(t,e),Oe(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>ew(s,t)):ew(o,t)}});ad=I("$ZodCatch",(t,e)=>{Pe.init(t,e),t._zod.optin="optional",Oe(t._zod,"optout",()=>e.innerType._zod.optout),Oe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>Wt(i,n,Et()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>Wt(s,n,Et()))},input:r.value}),r.issues=[]),r)}}),cd=I("$ZodPipe",(t,e)=>{Pe.init(t,e),Oe(t._zod,"values",()=>e.in._zod.values),Oe(t._zod,"optin",()=>e.in._zod.optin),Oe(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>tw(s,e,n)):tw(o,e,n)}});ld=I("$ZodReadonly",(t,e)=>{Pe.init(t,e),Oe(t._zod,"propValues",()=>e.innerType._zod.propValues),Oe(t._zod,"values",()=>e.innerType._zod.values),Oe(t._zod,"optin",()=>e.innerType._zod.optin),Oe(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(rw):rw(o)}});ud=I("$ZodCustom",(t,e)=>{tt.init(t,e),Pe.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>nw(s,r,n,t));nw(o,r,n,t)}})});function uw(){return{localeError:zR()}}var CR,zR,dw=O(()=>{cr();CR=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},zR=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${CR(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Wi(n.values[0])}`:`Invalid option: expected one of ${Ki(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Ki(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}}});var sa=O(()=>{});function pw(){return new _s}var _s,qr,pd=O(()=>{_s=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};qr=pw()});function fd(t,e){return new t({type:"string",...te(e)})}function hd(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...te(e)})}function ia(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...te(e)})}function md(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...te(e)})}function gd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...te(e)})}function yd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...te(e)})}function bd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...te(e)})}function wd(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...te(e)})}function _d(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...te(e)})}function vd(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...te(e)})}function xd(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...te(e)})}function kd(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...te(e)})}function $d(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...te(e)})}function Sd(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...te(e)})}function Td(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...te(e)})}function Ed(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...te(e)})}function Rd(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...te(e)})}function Pd(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...te(e)})}function Ad(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...te(e)})}function Id(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...te(e)})}function Od(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...te(e)})}function Cd(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...te(e)})}function zd(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...te(e)})}function fw(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...te(e)})}function hw(t,e){return new t({type:"string",format:"date",check:"string_format",...te(e)})}function mw(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...te(e)})}function gw(t,e){return new t({type:"string",format:"duration",check:"string_format",...te(e)})}function Nd(t,e){return new t({type:"number",checks:[],...te(e)})}function jd(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...te(e)})}function Ld(t,e){return new t({type:"boolean",...te(e)})}function Dd(t,e){return new t({type:"null",...te(e)})}function Md(t){return new t({type:"unknown"})}function Ud(t,e){return new t({type:"never",...te(e)})}function aa(t,e){return new _u({check:"less_than",...te(e),value:t,inclusive:!1})}function vs(t,e){return new _u({check:"less_than",...te(e),value:t,inclusive:!0})}function ca(t,e){return new vu({check:"greater_than",...te(e),value:t,inclusive:!1})}function xs(t,e){return new vu({check:"greater_than",...te(e),value:t,inclusive:!0})}function la(t,e){return new Nb({check:"multiple_of",...te(e),value:t})}function ua(t,e){return new Lb({check:"max_length",...te(e),maximum:t})}function uo(t,e){return new Db({check:"min_length",...te(e),minimum:t})}function da(t,e){return new Mb({check:"length_equals",...te(e),length:t})}function Zd(t,e){return new Ub({check:"string_format",format:"regex",...te(e),pattern:t})}function qd(t){return new Zb({check:"string_format",format:"lowercase",...te(t)})}function Fd(t){return new qb({check:"string_format",format:"uppercase",...te(t)})}function Bd(t,e){return new Fb({check:"string_format",format:"includes",...te(e),includes:t})}function Vd(t,e){return new Bb({check:"string_format",format:"starts_with",...te(e),prefix:t})}function Hd(t,e){return new Vb({check:"string_format",format:"ends_with",...te(e),suffix:t})}function Tn(t){return new Hb({check:"overwrite",tx:t})}function Kd(t){return Tn(e=>e.normalize(t))}function Gd(){return Tn(t=>t.trim())}function Wd(){return Tn(t=>t.toLowerCase())}function Jd(){return Tn(t=>t.toUpperCase())}function yw(t,e,r){return new t({type:"array",element:e,...te(r)})}function Yd(t,e,r){let n=te(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Xd(t,e,r){return new t({type:"custom",check:"custom",fn:e,...te(r)})}var bw=O(()=>{Qi();cr()});var ww=O(()=>{});function Qd(t,e){if(t instanceof _s){let n=new pa(e),o={};for(let a of t._idmap.entries()){let[c,l]=a;n.process(l)}let s={},i={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[c,l]=a;s[c]=n.emit(l,{...e,external:i})}if(Object.keys(o).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let r=new pa(e);return r.process(t),r.emit(t,e)}function We(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return We(o.element,r);case"object":{for(let s in o.shape)if(We(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(We(s,r))return!0;return!1}case"intersection":return We(o.left,r)||We(o.right,r);case"tuple":{for(let s of o.items)if(We(s,r))return!0;return!!(o.rest&&We(o.rest,r))}case"record":return We(o.keyType,r)||We(o.valueType,r);case"map":return We(o.keyType,r)||We(o.valueType,r);case"set":return We(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return We(o.innerType,r);case"lazy":return We(o.getter(),r);case"default":return We(o.innerType,r);case"prefault":return We(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return We(o.in,r)||We(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var pa,_w=O(()=>{pd();cr();pa=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??qr,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path},b=e._zod.parent;if(b)a.ref=b,this.process(b,d),this.seen.get(b).isParent=!0;else{let m=a.schema;switch(o.type){case"string":{let f=m;f.type="string";let{minimum:y,maximum:v,format:E,patterns:R,contentEncoding:z}=e._zod.bag;if(typeof y=="number"&&(f.minLength=y),typeof v=="number"&&(f.maxLength=v),E&&(f.format=s[E]??E,f.format===""&&delete f.format),z&&(f.contentEncoding=z),R&&R.size>0){let H=[...R];H.length===1?f.pattern=H[0].source:H.length>1&&(a.schema.allOf=[...H.map(Y=>({...this.target==="draft-7"?{type:"string"}:{},pattern:Y.source}))])}break}case"number":{let f=m,{minimum:y,maximum:v,format:E,multipleOf:R,exclusiveMaximum:z,exclusiveMinimum:H}=e._zod.bag;typeof E=="string"&&E.includes("int")?f.type="integer":f.type="number",typeof H=="number"&&(f.exclusiveMinimum=H),typeof y=="number"&&(f.minimum=y,typeof H=="number"&&(H>=y?delete f.minimum:delete f.exclusiveMinimum)),typeof z=="number"&&(f.exclusiveMaximum=z),typeof v=="number"&&(f.maximum=v,typeof z=="number"&&(z<=v?delete f.maximum:delete f.exclusiveMaximum)),typeof R=="number"&&(f.multipleOf=R);break}case"boolean":{let f=m;f.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{m.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{m.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let f=m,{minimum:y,maximum:v}=e._zod.bag;typeof y=="number"&&(f.minItems=y),typeof v=="number"&&(f.maxItems=v),f.type="array",f.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let f=m;f.type="object",f.properties={};let y=o.shape;for(let R in y)f.properties[R]=this.process(y[R],{...d,path:[...d.path,"properties",R]});let v=new Set(Object.keys(y)),E=new Set([...v].filter(R=>{let z=o.shape[R]._zod;return this.io==="input"?z.optin===void 0:z.optout===void 0}));E.size>0&&(f.required=Array.from(E)),o.catchall?._zod.def.type==="never"?f.additionalProperties=!1:o.catchall?o.catchall&&(f.additionalProperties=this.process(o.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(f.additionalProperties=!1);break}case"union":{let f=m;f.anyOf=o.options.map((y,v)=>this.process(y,{...d,path:[...d.path,"anyOf",v]}));break}case"intersection":{let f=m,y=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),v=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),E=z=>"allOf"in z&&Object.keys(z).length===1,R=[...E(y)?y.allOf:[y],...E(v)?v.allOf:[v]];f.allOf=R;break}case"tuple":{let f=m;f.type="array";let y=o.items.map((R,z)=>this.process(R,{...d,path:[...d.path,"prefixItems",z]}));if(this.target==="draft-2020-12"?f.prefixItems=y:f.items=y,o.rest){let R=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?f.items=R:f.additionalItems=R}o.rest&&(f.items=this.process(o.rest,{...d,path:[...d.path,"items"]}));let{minimum:v,maximum:E}=e._zod.bag;typeof v=="number"&&(f.minItems=v),typeof E=="number"&&(f.maxItems=E);break}case"record":{let f=m;f.type="object",f.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),f.additionalProperties=this.process(o.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let f=m,y=ps(o.entries);y.every(v=>typeof v=="number")&&(f.type="number"),y.every(v=>typeof v=="string")&&(f.type="string"),f.enum=y;break}case"literal":{let f=m,y=[];for(let v of o.values)if(v===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof v=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");y.push(Number(v))}else y.push(v);if(y.length!==0)if(y.length===1){let v=y[0];f.type=v===null?"null":typeof v,f.const=v}else y.every(v=>typeof v=="number")&&(f.type="number"),y.every(v=>typeof v=="string")&&(f.type="string"),y.every(v=>typeof v=="boolean")&&(f.type="string"),y.every(v=>v===null)&&(f.type="null"),f.enum=y;break}case"file":{let f=m,y={type:"string",format:"binary",contentEncoding:"binary"},{minimum:v,maximum:E,mime:R}=e._zod.bag;v!==void 0&&(y.minLength=v),E!==void 0&&(y.maxLength=E),R?R.length===1?(y.contentMediaType=R[0],Object.assign(f,y)):f.anyOf=R.map(z=>({...y,contentMediaType:z})):Object.assign(f,y);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let f=this.process(o.innerType,d);m.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let f=m;f.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,m.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(m._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),a.ref=o.innerType;let f;try{f=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}m.default=f;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let f=m,y=e._zod.pattern;if(!y)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=y.source;break}case"pipe":{let f=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(f,d),a.ref=f;break}case"readonly":{this.process(o.innerType,d),a.ref=o.innerType,m.readOnly=!0;break}case"promise":{this.process(o.innerType,d),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"lazy":{let f=e._zod.innerType;this.process(f,d),a.ref=f;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let l=this.metadataRegistry.get(e);return l&&Object.assign(a.schema,l),this.io==="input"&&We(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=u=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let y=n.external.registry.get(u[0])?.id,v=n.external.uri??(R=>R);if(y)return{ref:v(y)};let E=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=E,{defId:E,ref:`${v("__shared")}#/${d}/${E}`}}if(u[1]===o)return{ref:"#"};let m=`#/${d}/`,f=u[1].schema.id??`__schema${this.counter++}`;return{defId:f,ref:m+f}},i=u=>{if(u[1].schema.$ref)return;let d=u[1],{ref:b,defId:m}=s(u);d.def={...d.schema},m&&(d.defId=m);let f=d.schema;for(let y in f)delete f[y];f.$ref=b};if(n.cycles==="throw")for(let u of this.seen.entries()){let d=u[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
979
1126
 
980
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let u of this.seen.entries()){let d=u[1];if(e===u[0]){i(u);continue}if(n.external){let m=n.external.registry.get(u[0])?.id;if(e!==u[0]&&m){i(u);continue}}if(this.metadataRegistry.get(u[0])?.id){i(u);continue}if(d.cycle){i(u);continue}if(d.count>1&&n.reused==="ref"){i(u);continue}}let a=(u,d)=>{let b=this.seen.get(u),m=b.def??b.schema,f={...m};if(b.ref===null)return;let y=b.ref;if(b.ref=null,y){a(y,d);let v=this.seen.get(y).schema;v.$ref&&d.target==="draft-7"?(m.allOf=m.allOf??[],m.allOf.push(v)):(Object.assign(m,v),Object.assign(m,f))}b.isParent||this.override({zodSchema:u,jsonSchema:m,path:b.path??[]})};for(let u of[...this.seen.entries()].reverse())a(u[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let u=n.external.registry.get(e)?.id;if(!u)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(u)}Object.assign(c,o.def);let l=n.external?.defs??{};for(let u of this.seen.entries()){let d=u[1];d.def&&d.defId&&(l[d.defId]=d.def)}n.external||Object.keys(l).length>0&&(this.target==="draft-2020-12"?c.$defs=l:c.definitions=l);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}});var tw=O(()=>{});var ut=O(()=>{so();lu();ru();Fb();Hi();mu();cr();Vi();Xi();od();hu();Qb();Xb();ew();tw()});var Hd=O(()=>{ut()});function Kd(t,e){let r={type:"object",get shape(){return we.assignProp(this,"shape",{...t}),this.shape},...we.normalizeParams(e)};return new jR(r)}var NR,jR,rw=O(()=>{ut();ut();Hd();NR=I("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");Pe.init(t,e),t.def=e,t.parse=(r,n)=>ou(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>$n(t,r,n),t.parseAsync=async(r,n)=>iu(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Sn(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Tt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),jR=I("ZodMiniObject",(t,e)=>{Ji.init(t,e),NR.init(t,e),we.defineLazy(t,"shape",()=>e.shape)})});var nw=O(()=>{});var ow=O(()=>{});var sw=O(()=>{});var iw=O(()=>{ut();Hd();rw();nw();ut();Xi();ow();sw()});var aw=O(()=>{iw()});var Wd=O(()=>{aw()});function lr(t){return!!t._zod}function Rn(t){let e=Object.values(t);if(e.length===0)return Kd({});let r=e.every(lr),n=e.every(o=>!lr(o));if(r)return Kd(t);if(n)return Qc(t);throw new Error("Mixed Zod versions detected in object shape.")}function Zr(t,e){return lr(t)?$n(t,e):t.safeParse(e)}async function ia(t,e){return lr(t)?await Sn(t,e):await t.safeParseAsync(e)}function qr(t){if(!t)return;let e;if(lr(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function lo(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Rn(t)}}if(lr(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function DR(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function aa(t){if(t&&typeof t=="object"){if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0)return t.issues.map(e=>e.path?.length?`${e.message} at ${DR(e.path)}`:e.message).join(`
981
- `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function lw(t){return t.description}function uw(t){if(lr(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function uo(t){if(lr(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var gs=O(()=>{ns();Wd()});var Gd=O(()=>{ut()});var ys={};Mo(ys,{ZodISODate:()=>pw,ZodISODateTime:()=>dw,ZodISODuration:()=>hw,ZodISOTime:()=>fw,date:()=>Yd,datetime:()=>Jd,duration:()=>Qd,time:()=>Xd});function Jd(t){return Kb(dw,t)}function Yd(t){return Wb(pw,t)}function Xd(t){return Gb(fw,t)}function Qd(t){return Jb(hw,t)}var dw,pw,fw,hw,ep=O(()=>{ut();tp();dw=I("ZodISODateTime",(t,e)=>{Mb.init(t,e),De.init(t,e)});pw=I("ZodISODate",(t,e)=>{Db.init(t,e),De.init(t,e)});fw=I("ZodISOTime",(t,e)=>{Ub.init(t,e),De.init(t,e)});hw=I("ZodISODuration",(t,e)=>{Zb.init(t,e),De.init(t,e)})});var mw,xZ,bs,rp=O(()=>{ut();ut();mw=(t,e)=>{Fi.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>tu(t,r)},flatten:{value:r=>eu(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},xZ=I("ZodError",mw),bs=I("ZodError",mw,{Parent:Error})});var gw,yw,bw,ww,np=O(()=>{ut();rp();gw=nu(bs),yw=su(bs),bw=au(bs),ww=cu(bs)});function P(t){return sd(KR,t)}function Re(t){return Ed($w,t)}function vw(t){return Rd(dP,t)}function Ye(t){return Pd(pP,t)}function Sw(t){return Ad(fP,t)}function Ue(){return Id(hP)}function gP(t){return Od(mP,t)}function _e(t,e){return Yb(yP,t,e)}function B(t,e){let r={type:"object",get shape(){return we.assignProp(this,"shape",{...t}),this.shape},...we.normalizeParams(e)};return new Tw(r)}function dt(t,e){return new Tw({type:"object",get shape(){return we.assignProp(this,"shape",{...t}),this.shape},catchall:Ue(),...we.normalizeParams(e)})}function Ne(t,e){return new Ew({type:"union",options:t,...we.normalizeParams(e)})}function ip(t,e,r){return new bP({type:"union",options:e,discriminator:t,...we.normalizeParams(r)})}function la(t,e){return new wP({type:"intersection",left:t,right:e})}function ze(t,e,r){return new _P({type:"record",keyType:t,valueType:e,...we.normalizeParams(r)})}function _t(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new op({type:"enum",entries:r,...we.normalizeParams(e)})}function W(t,e){return new vP({type:"literal",values:Array.isArray(t)?t:[t],...we.normalizeParams(e)})}function Rw(t){return new xP({type:"transform",transform:t})}function Ze(t){return new Pw({type:"optional",innerType:t})}function xw(t){return new kP({type:"nullable",innerType:t})}function SP(t,e){return new $P({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function EP(t,e){return new TP({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function RP(t,e){return new Aw({type:"nonoptional",innerType:t,...we.normalizeParams(e)})}function AP(t,e){return new PP({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function sp(t,e){return new IP({type:"pipe",in:t,out:e})}function CP(t){return new OP({type:"readonly",innerType:t})}function zP(t){let e=new et({check:"custom"});return e._zod.check=t,e}function Ow(t,e){return Fd(Iw,t??(()=>!0),e)}function NP(t,e={}){return Bd(Iw,t,e)}function jP(t){let e=zP(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(we.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(we.issue(o))}},t(r.value,r)));return e}function ap(t,e){return sp(Rw(t),e)}var Fe,kw,KR,De,WR,_w,ca,GR,JR,YR,XR,QR,eP,tP,rP,nP,oP,sP,iP,aP,cP,lP,uP,$w,dP,pP,fP,hP,mP,yP,Tw,Ew,bP,wP,_P,op,vP,xP,Pw,kP,$P,TP,Aw,PP,IP,OP,Iw,tp=O(()=>{ut();ut();Gd();ep();np();Fe=I("ZodType",(t,e)=>(Pe.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Tt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>gw(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>bw(t,r,n),t.parseAsync=async(r,n)=>yw(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>ww(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(NP(r,n)),t.superRefine=r=>t.check(jP(r)),t.overwrite=r=>t.check(Tn(r)),t.optional=()=>Ze(t),t.nullable=()=>xw(t),t.nullish=()=>Ze(xw(t)),t.nonoptional=r=>RP(t,r),t.array=()=>_e(t),t.or=r=>Ne([t,r]),t.and=r=>la(t,r),t.transform=r=>sp(t,Rw(r)),t.default=r=>SP(t,r),t.prefault=r=>EP(t,r),t.catch=r=>AP(t,r),t.pipe=r=>sp(t,r),t.readonly=()=>CP(t),t.describe=r=>{let n=t.clone();return Ur.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Ur.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Ur.get(t);let n=t.clone();return Ur.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),kw=I("_ZodString",(t,e)=>{ps.init(t,e),Fe.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Cd(...n)),t.includes=(...n)=>t.check(jd(...n)),t.startsWith=(...n)=>t.check(Ld(...n)),t.endsWith=(...n)=>t.check(Md(...n)),t.min=(...n)=>t.check(co(...n)),t.max=(...n)=>t.check(na(...n)),t.length=(...n)=>t.check(oa(...n)),t.nonempty=(...n)=>t.check(co(1,...n)),t.lowercase=n=>t.check(zd(n)),t.uppercase=n=>t.check(Nd(n)),t.trim=()=>t.check(Ud()),t.normalize=(...n)=>t.check(Dd(...n)),t.toLowerCase=()=>t.check(Zd()),t.toUpperCase=()=>t.check(qd())}),KR=I("ZodString",(t,e)=>{ps.init(t,e),kw.init(t,e),t.email=r=>t.check(id(WR,r)),t.url=r=>t.check(dd(GR,r)),t.jwt=r=>t.check(Td(uP,r)),t.emoji=r=>t.check(pd(JR,r)),t.guid=r=>t.check(Qi(_w,r)),t.uuid=r=>t.check(ad(ca,r)),t.uuidv4=r=>t.check(cd(ca,r)),t.uuidv6=r=>t.check(ld(ca,r)),t.uuidv7=r=>t.check(ud(ca,r)),t.nanoid=r=>t.check(fd(YR,r)),t.guid=r=>t.check(Qi(_w,r)),t.cuid=r=>t.check(hd(XR,r)),t.cuid2=r=>t.check(md(QR,r)),t.ulid=r=>t.check(gd(eP,r)),t.base64=r=>t.check(kd(aP,r)),t.base64url=r=>t.check($d(cP,r)),t.xid=r=>t.check(yd(tP,r)),t.ksuid=r=>t.check(bd(rP,r)),t.ipv4=r=>t.check(wd(nP,r)),t.ipv6=r=>t.check(_d(oP,r)),t.cidrv4=r=>t.check(vd(sP,r)),t.cidrv6=r=>t.check(xd(iP,r)),t.e164=r=>t.check(Sd(lP,r)),t.datetime=r=>t.check(Jd(r)),t.date=r=>t.check(Yd(r)),t.time=r=>t.check(Xd(r)),t.duration=r=>t.check(Qd(r))});De=I("ZodStringFormat",(t,e)=>{Ce.init(t,e),kw.init(t,e)}),WR=I("ZodEmail",(t,e)=>{wu.init(t,e),De.init(t,e)}),_w=I("ZodGUID",(t,e)=>{yu.init(t,e),De.init(t,e)}),ca=I("ZodUUID",(t,e)=>{bu.init(t,e),De.init(t,e)}),GR=I("ZodURL",(t,e)=>{_u.init(t,e),De.init(t,e)}),JR=I("ZodEmoji",(t,e)=>{vu.init(t,e),De.init(t,e)}),YR=I("ZodNanoID",(t,e)=>{xu.init(t,e),De.init(t,e)}),XR=I("ZodCUID",(t,e)=>{ku.init(t,e),De.init(t,e)}),QR=I("ZodCUID2",(t,e)=>{$u.init(t,e),De.init(t,e)}),eP=I("ZodULID",(t,e)=>{Su.init(t,e),De.init(t,e)}),tP=I("ZodXID",(t,e)=>{Tu.init(t,e),De.init(t,e)}),rP=I("ZodKSUID",(t,e)=>{Eu.init(t,e),De.init(t,e)}),nP=I("ZodIPv4",(t,e)=>{Ru.init(t,e),De.init(t,e)}),oP=I("ZodIPv6",(t,e)=>{Pu.init(t,e),De.init(t,e)}),sP=I("ZodCIDRv4",(t,e)=>{Au.init(t,e),De.init(t,e)}),iP=I("ZodCIDRv6",(t,e)=>{Iu.init(t,e),De.init(t,e)}),aP=I("ZodBase64",(t,e)=>{Ou.init(t,e),De.init(t,e)}),cP=I("ZodBase64URL",(t,e)=>{Cu.init(t,e),De.init(t,e)}),lP=I("ZodE164",(t,e)=>{zu.init(t,e),De.init(t,e)}),uP=I("ZodJWT",(t,e)=>{Nu.init(t,e),De.init(t,e)}),$w=I("ZodNumber",(t,e)=>{Gi.init(t,e),Fe.init(t,e),t.gt=(n,o)=>t.check(ta(n,o)),t.gte=(n,o)=>t.check(ms(n,o)),t.min=(n,o)=>t.check(ms(n,o)),t.lt=(n,o)=>t.check(ea(n,o)),t.lte=(n,o)=>t.check(hs(n,o)),t.max=(n,o)=>t.check(hs(n,o)),t.int=n=>t.check(vw(n)),t.safe=n=>t.check(vw(n)),t.positive=n=>t.check(ta(0,n)),t.nonnegative=n=>t.check(ms(0,n)),t.negative=n=>t.check(ea(0,n)),t.nonpositive=n=>t.check(hs(0,n)),t.multipleOf=(n,o)=>t.check(ra(n,o)),t.step=(n,o)=>t.check(ra(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});dP=I("ZodNumberFormat",(t,e)=>{ju.init(t,e),$w.init(t,e)});pP=I("ZodBoolean",(t,e)=>{Lu.init(t,e),Fe.init(t,e)});fP=I("ZodNull",(t,e)=>{Mu.init(t,e),Fe.init(t,e)});hP=I("ZodUnknown",(t,e)=>{Du.init(t,e),Fe.init(t,e)});mP=I("ZodNever",(t,e)=>{Uu.init(t,e),Fe.init(t,e)});yP=I("ZodArray",(t,e)=>{Zu.init(t,e),Fe.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(co(r,n)),t.nonempty=r=>t.check(co(1,r)),t.max=(r,n)=>t.check(na(r,n)),t.length=(r,n)=>t.check(oa(r,n)),t.unwrap=()=>t.element});Tw=I("ZodObject",(t,e)=>{Ji.init(t,e),Fe.init(t,e),we.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>_t(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Ue()}),t.loose=()=>t.clone({...t._zod.def,catchall:Ue()}),t.strict=()=>t.clone({...t._zod.def,catchall:gP()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>we.extend(t,r),t.merge=r=>we.merge(t,r),t.pick=r=>we.pick(t,r),t.omit=r=>we.omit(t,r),t.partial=(...r)=>we.partial(Pw,t,r[0]),t.required=(...r)=>we.required(Aw,t,r[0])});Ew=I("ZodUnion",(t,e)=>{Yi.init(t,e),Fe.init(t,e),t.options=e.options});bP=I("ZodDiscriminatedUnion",(t,e)=>{Ew.init(t,e),qu.init(t,e)});wP=I("ZodIntersection",(t,e)=>{Fu.init(t,e),Fe.init(t,e)});_P=I("ZodRecord",(t,e)=>{Bu.init(t,e),Fe.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});op=I("ZodEnum",(t,e)=>{Vu.init(t,e),Fe.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new op({...e,checks:[],...we.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new op({...e,checks:[],...we.normalizeParams(o),entries:s})}});vP=I("ZodLiteral",(t,e)=>{Hu.init(t,e),Fe.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});xP=I("ZodTransform",(t,e)=>{Ku.init(t,e),Fe.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(we.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(we.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});Pw=I("ZodOptional",(t,e)=>{Wu.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});kP=I("ZodNullable",(t,e)=>{Gu.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});$P=I("ZodDefault",(t,e)=>{Ju.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});TP=I("ZodPrefault",(t,e)=>{Yu.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});Aw=I("ZodNonOptional",(t,e)=>{Xu.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});PP=I("ZodCatch",(t,e)=>{Qu.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});IP=I("ZodPipe",(t,e)=>{ed.init(t,e),Fe.init(t,e),t.in=e.in,t.out=e.out});OP=I("ZodReadonly",(t,e)=>{td.init(t,e),Fe.init(t,e)});Iw=I("ZodCustom",(t,e)=>{rd.init(t,e),Fe.init(t,e)})});var Cw=O(()=>{});var zw=O(()=>{});var Nw=O(()=>{ut();tp();Gd();rp();np();Cw();ut();Vb();Xi();ep();zw();St(Bb())});var jw=O(()=>{Nw()});var Lw=O(()=>{jw()});function e_(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function t_(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var lp,Mw,Fr,da,Je,Dw,Uw,MZ,DP,UP,up,Et,ws,Zw,tt,Lt,Mt,rt,pa,qw,dp,Fw,Bw,pp,_s,Y,fp,Vw,Hw,DZ,fa,ZP,ha,qP,vs,po,Kw,FP,BP,VP,HP,KP,WP,hp,GP,JP,mp,ma,YP,XP,ga,QP,xs,ks,eA,$s,fo,tA,Ss,ya,ba,wa,UZ,_a,va,xa,Ww,Gw,Jw,gp,Yw,Ts,ho,Xw,rA,ka,nA,$a,oA,yp,sA,Sa,iA,aA,cA,lA,uA,dA,pA,fA,hA,mA,Ta,gA,yA,Ea,bp,wp,_p,bA,wA,_A,vp,vA,xA,kA,$A,SA,Qw,Ra,TA,Pa,ZZ,EA,mo,RA,qZ,Es,PA,xp,AA,IA,OA,CA,zA,NA,jA,ua,LA,MA,DA,Rs,kp,UA,ZA,qA,FA,BA,VA,HA,KA,WA,GA,JA,YA,XA,QA,eI,tI,rI,nI,go,oI,sI,iI,Aa,aI,cI,lI,$p,uI,FZ,BZ,VZ,HZ,KZ,WZ,K,cp,yo=O(()=>{Lw();lp="2025-11-25",Mw=[lp,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Fr="io.modelcontextprotocol/related-task",da="2.0",Je=Ow(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Dw=Ne([P(),Re().int()]),Uw=P(),MZ=dt({ttl:Re().optional(),pollInterval:Re().optional()}),DP=B({ttl:Re().optional()}),UP=B({taskId:P()}),up=dt({progressToken:Dw.optional(),[Fr]:UP.optional()}),Et=B({_meta:up.optional()}),ws=Et.extend({task:DP.optional()}),Zw=t=>ws.safeParse(t).success,tt=B({method:P(),params:Et.loose().optional()}),Lt=B({_meta:up.optional()}),Mt=B({method:P(),params:Lt.loose().optional()}),rt=dt({_meta:up.optional()}),pa=Ne([P(),Re().int()]),qw=B({jsonrpc:W(da),id:pa,...tt.shape}).strict(),dp=t=>qw.safeParse(t).success,Fw=B({jsonrpc:W(da),...Mt.shape}).strict(),Bw=t=>Fw.safeParse(t).success,pp=B({jsonrpc:W(da),id:pa,result:rt}).strict(),_s=t=>pp.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Y||(Y={}));fp=B({jsonrpc:W(da),id:pa.optional(),error:B({code:Re().int(),message:P(),data:Ue().optional()})}).strict(),Vw=t=>fp.safeParse(t).success,Hw=Ne([qw,Fw,pp,fp]),DZ=Ne([pp,fp]),fa=rt.strict(),ZP=Lt.extend({requestId:pa.optional(),reason:P().optional()}),ha=Mt.extend({method:W("notifications/cancelled"),params:ZP}),qP=B({src:P(),mimeType:P().optional(),sizes:_e(P()).optional(),theme:_t(["light","dark"]).optional()}),vs=B({icons:_e(qP).optional()}),po=B({name:P(),title:P().optional()}),Kw=po.extend({...po.shape,...vs.shape,version:P(),websiteUrl:P().optional(),description:P().optional()}),FP=la(B({applyDefaults:Ye().optional()}),ze(P(),Ue())),BP=ap(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,la(B({form:FP.optional(),url:Je.optional()}),ze(P(),Ue()).optional())),VP=dt({list:Je.optional(),cancel:Je.optional(),requests:dt({sampling:dt({createMessage:Je.optional()}).optional(),elicitation:dt({create:Je.optional()}).optional()}).optional()}),HP=dt({list:Je.optional(),cancel:Je.optional(),requests:dt({tools:dt({call:Je.optional()}).optional()}).optional()}),KP=B({experimental:ze(P(),Je).optional(),sampling:B({context:Je.optional(),tools:Je.optional()}).optional(),elicitation:BP.optional(),roots:B({listChanged:Ye().optional()}).optional(),tasks:VP.optional(),extensions:ze(P(),Je).optional()}),WP=Et.extend({protocolVersion:P(),capabilities:KP,clientInfo:Kw}),hp=tt.extend({method:W("initialize"),params:WP}),GP=B({experimental:ze(P(),Je).optional(),logging:Je.optional(),completions:Je.optional(),prompts:B({listChanged:Ye().optional()}).optional(),resources:B({subscribe:Ye().optional(),listChanged:Ye().optional()}).optional(),tools:B({listChanged:Ye().optional()}).optional(),tasks:HP.optional(),extensions:ze(P(),Je).optional()}),JP=rt.extend({protocolVersion:P(),capabilities:GP,serverInfo:Kw,instructions:P().optional()}),mp=Mt.extend({method:W("notifications/initialized"),params:Lt.optional()}),ma=tt.extend({method:W("ping"),params:Et.optional()}),YP=B({progress:Re(),total:Ze(Re()),message:Ze(P())}),XP=B({...Lt.shape,...YP.shape,progressToken:Dw}),ga=Mt.extend({method:W("notifications/progress"),params:XP}),QP=Et.extend({cursor:Uw.optional()}),xs=tt.extend({params:QP.optional()}),ks=rt.extend({nextCursor:Uw.optional()}),eA=_t(["working","input_required","completed","failed","cancelled"]),$s=B({taskId:P(),status:eA,ttl:Ne([Re(),Sw()]),createdAt:P(),lastUpdatedAt:P(),pollInterval:Ze(Re()),statusMessage:Ze(P())}),fo=rt.extend({task:$s}),tA=Lt.merge($s),Ss=Mt.extend({method:W("notifications/tasks/status"),params:tA}),ya=tt.extend({method:W("tasks/get"),params:Et.extend({taskId:P()})}),ba=rt.merge($s),wa=tt.extend({method:W("tasks/result"),params:Et.extend({taskId:P()})}),UZ=rt.loose(),_a=xs.extend({method:W("tasks/list")}),va=ks.extend({tasks:_e($s)}),xa=tt.extend({method:W("tasks/cancel"),params:Et.extend({taskId:P()})}),Ww=rt.merge($s),Gw=B({uri:P(),mimeType:Ze(P()),_meta:ze(P(),Ue()).optional()}),Jw=Gw.extend({text:P()}),gp=P().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Yw=Gw.extend({blob:gp}),Ts=_t(["user","assistant"]),ho=B({audience:_e(Ts).optional(),priority:Re().min(0).max(1).optional(),lastModified:ys.datetime({offset:!0}).optional()}),Xw=B({...po.shape,...vs.shape,uri:P(),description:Ze(P()),mimeType:Ze(P()),size:Ze(Re()),annotations:ho.optional(),_meta:Ze(dt({}))}),rA=B({...po.shape,...vs.shape,uriTemplate:P(),description:Ze(P()),mimeType:Ze(P()),annotations:ho.optional(),_meta:Ze(dt({}))}),ka=xs.extend({method:W("resources/list")}),nA=ks.extend({resources:_e(Xw)}),$a=xs.extend({method:W("resources/templates/list")}),oA=ks.extend({resourceTemplates:_e(rA)}),yp=Et.extend({uri:P()}),sA=yp,Sa=tt.extend({method:W("resources/read"),params:sA}),iA=rt.extend({contents:_e(Ne([Jw,Yw]))}),aA=Mt.extend({method:W("notifications/resources/list_changed"),params:Lt.optional()}),cA=yp,lA=tt.extend({method:W("resources/subscribe"),params:cA}),uA=yp,dA=tt.extend({method:W("resources/unsubscribe"),params:uA}),pA=Lt.extend({uri:P()}),fA=Mt.extend({method:W("notifications/resources/updated"),params:pA}),hA=B({name:P(),description:Ze(P()),required:Ze(Ye())}),mA=B({...po.shape,...vs.shape,description:Ze(P()),arguments:Ze(_e(hA)),_meta:Ze(dt({}))}),Ta=xs.extend({method:W("prompts/list")}),gA=ks.extend({prompts:_e(mA)}),yA=Et.extend({name:P(),arguments:ze(P(),P()).optional()}),Ea=tt.extend({method:W("prompts/get"),params:yA}),bp=B({type:W("text"),text:P(),annotations:ho.optional(),_meta:ze(P(),Ue()).optional()}),wp=B({type:W("image"),data:gp,mimeType:P(),annotations:ho.optional(),_meta:ze(P(),Ue()).optional()}),_p=B({type:W("audio"),data:gp,mimeType:P(),annotations:ho.optional(),_meta:ze(P(),Ue()).optional()}),bA=B({type:W("tool_use"),name:P(),id:P(),input:ze(P(),Ue()),_meta:ze(P(),Ue()).optional()}),wA=B({type:W("resource"),resource:Ne([Jw,Yw]),annotations:ho.optional(),_meta:ze(P(),Ue()).optional()}),_A=Xw.extend({type:W("resource_link")}),vp=Ne([bp,wp,_p,_A,wA]),vA=B({role:Ts,content:vp}),xA=rt.extend({description:P().optional(),messages:_e(vA)}),kA=Mt.extend({method:W("notifications/prompts/list_changed"),params:Lt.optional()}),$A=B({title:P().optional(),readOnlyHint:Ye().optional(),destructiveHint:Ye().optional(),idempotentHint:Ye().optional(),openWorldHint:Ye().optional()}),SA=B({taskSupport:_t(["required","optional","forbidden"]).optional()}),Qw=B({...po.shape,...vs.shape,description:P().optional(),inputSchema:B({type:W("object"),properties:ze(P(),Je).optional(),required:_e(P()).optional()}).catchall(Ue()),outputSchema:B({type:W("object"),properties:ze(P(),Je).optional(),required:_e(P()).optional()}).catchall(Ue()).optional(),annotations:$A.optional(),execution:SA.optional(),_meta:ze(P(),Ue()).optional()}),Ra=xs.extend({method:W("tools/list")}),TA=ks.extend({tools:_e(Qw)}),Pa=rt.extend({content:_e(vp).default([]),structuredContent:ze(P(),Ue()).optional(),isError:Ye().optional()}),ZZ=Pa.or(rt.extend({toolResult:Ue()})),EA=ws.extend({name:P(),arguments:ze(P(),Ue()).optional()}),mo=tt.extend({method:W("tools/call"),params:EA}),RA=Mt.extend({method:W("notifications/tools/list_changed"),params:Lt.optional()}),qZ=B({autoRefresh:Ye().default(!0),debounceMs:Re().int().nonnegative().default(300)}),Es=_t(["debug","info","notice","warning","error","critical","alert","emergency"]),PA=Et.extend({level:Es}),xp=tt.extend({method:W("logging/setLevel"),params:PA}),AA=Lt.extend({level:Es,logger:P().optional(),data:Ue()}),IA=Mt.extend({method:W("notifications/message"),params:AA}),OA=B({name:P().optional()}),CA=B({hints:_e(OA).optional(),costPriority:Re().min(0).max(1).optional(),speedPriority:Re().min(0).max(1).optional(),intelligencePriority:Re().min(0).max(1).optional()}),zA=B({mode:_t(["auto","required","none"]).optional()}),NA=B({type:W("tool_result"),toolUseId:P().describe("The unique identifier for the corresponding tool call."),content:_e(vp).default([]),structuredContent:B({}).loose().optional(),isError:Ye().optional(),_meta:ze(P(),Ue()).optional()}),jA=ip("type",[bp,wp,_p]),ua=ip("type",[bp,wp,_p,bA,NA]),LA=B({role:Ts,content:Ne([ua,_e(ua)]),_meta:ze(P(),Ue()).optional()}),MA=ws.extend({messages:_e(LA),modelPreferences:CA.optional(),systemPrompt:P().optional(),includeContext:_t(["none","thisServer","allServers"]).optional(),temperature:Re().optional(),maxTokens:Re().int(),stopSequences:_e(P()).optional(),metadata:Je.optional(),tools:_e(Qw).optional(),toolChoice:zA.optional()}),DA=tt.extend({method:W("sampling/createMessage"),params:MA}),Rs=rt.extend({model:P(),stopReason:Ze(_t(["endTurn","stopSequence","maxTokens"]).or(P())),role:Ts,content:jA}),kp=rt.extend({model:P(),stopReason:Ze(_t(["endTurn","stopSequence","maxTokens","toolUse"]).or(P())),role:Ts,content:Ne([ua,_e(ua)])}),UA=B({type:W("boolean"),title:P().optional(),description:P().optional(),default:Ye().optional()}),ZA=B({type:W("string"),title:P().optional(),description:P().optional(),minLength:Re().optional(),maxLength:Re().optional(),format:_t(["email","uri","date","date-time"]).optional(),default:P().optional()}),qA=B({type:_t(["number","integer"]),title:P().optional(),description:P().optional(),minimum:Re().optional(),maximum:Re().optional(),default:Re().optional()}),FA=B({type:W("string"),title:P().optional(),description:P().optional(),enum:_e(P()),default:P().optional()}),BA=B({type:W("string"),title:P().optional(),description:P().optional(),oneOf:_e(B({const:P(),title:P()})),default:P().optional()}),VA=B({type:W("string"),title:P().optional(),description:P().optional(),enum:_e(P()),enumNames:_e(P()).optional(),default:P().optional()}),HA=Ne([FA,BA]),KA=B({type:W("array"),title:P().optional(),description:P().optional(),minItems:Re().optional(),maxItems:Re().optional(),items:B({type:W("string"),enum:_e(P())}),default:_e(P()).optional()}),WA=B({type:W("array"),title:P().optional(),description:P().optional(),minItems:Re().optional(),maxItems:Re().optional(),items:B({anyOf:_e(B({const:P(),title:P()}))}),default:_e(P()).optional()}),GA=Ne([KA,WA]),JA=Ne([VA,HA,GA]),YA=Ne([JA,UA,ZA,qA]),XA=ws.extend({mode:W("form").optional(),message:P(),requestedSchema:B({type:W("object"),properties:ze(P(),YA),required:_e(P()).optional()})}),QA=ws.extend({mode:W("url"),message:P(),elicitationId:P(),url:P().url()}),eI=Ne([XA,QA]),tI=tt.extend({method:W("elicitation/create"),params:eI}),rI=Lt.extend({elicitationId:P()}),nI=Mt.extend({method:W("notifications/elicitation/complete"),params:rI}),go=rt.extend({action:_t(["accept","decline","cancel"]),content:ap(t=>t===null?void 0:t,ze(P(),Ne([P(),Re(),Ye(),_e(P())])).optional())}),oI=B({type:W("ref/resource"),uri:P()}),sI=B({type:W("ref/prompt"),name:P()}),iI=Et.extend({ref:Ne([sI,oI]),argument:B({name:P(),value:P()}),context:B({arguments:ze(P(),P()).optional()}).optional()}),Aa=tt.extend({method:W("completion/complete"),params:iI});aI=rt.extend({completion:dt({values:_e(P()).max(100),total:Ze(Re().int()),hasMore:Ze(Ye())})}),cI=B({uri:P().startsWith("file://"),name:P().optional(),_meta:ze(P(),Ue()).optional()}),lI=tt.extend({method:W("roots/list"),params:Et.optional()}),$p=rt.extend({roots:_e(cI)}),uI=Mt.extend({method:W("notifications/roots/list_changed"),params:Lt.optional()}),FZ=Ne([ma,hp,Aa,xp,Ea,Ta,ka,$a,Sa,lA,dA,mo,Ra,ya,wa,_a,xa]),BZ=Ne([ha,ga,mp,uI,Ss]),VZ=Ne([fa,Rs,kp,go,$p,ba,va,fo]),HZ=Ne([ma,DA,tI,lI,ya,wa,_a,xa]),KZ=Ne([ha,ga,IA,fA,aA,RA,kA,Ss,nI]),WZ=Ne([fa,JP,aI,xA,gA,nA,oA,iA,Pa,TA,ba,va,fo]),K=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===Y.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new cp(o.elicitations,r)}return new t(e,r,n)}},cp=class extends K{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(Y.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Br(t){return t==="completed"||t==="failed"||t==="cancelled"}var r_=O(()=>{});var o_,n_,s_,Ia=O(()=>{o_=Symbol("Let zodToJsonSchema decide on which parser to use"),n_={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},s_=t=>typeof t=="string"?{...n_,name:t}:{...n_,...t}});var i_,Sp=O(()=>{Ia();i_=t=>{let e=s_(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function Tp(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ve(t,e,r,n,o){t[e]=r,Tp(t,e,n,o)}var Vr=O(()=>{});var Oa,Ca=O(()=>{Oa=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")}});function qe(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Oa(e,t.currentPath):e.join("/")}}var Dt=O(()=>{Ca()});function a_(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==M.ZodAny&&(r.items=te(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ve(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ve(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ve(r,"minItems",t.exactLength.value,t.exactLength.message,e),ve(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var Ep=O(()=>{ns();Vr();We()});function c_(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?ve(r,"minimum",n.value,n.message,e):ve(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ve(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ve(r,"maximum",n.value,n.message,e):ve(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ve(r,"maximum",n.value,n.message,e));break;case"multipleOf":ve(r,"multipleOf",n.value,n.message,e);break}return r}var Rp=O(()=>{Vr()});function l_(){return{type:"boolean"}}var Pp=O(()=>{});function za(t,e){return te(t.type._def,e)}var Na=O(()=>{We()});var u_,Ap=O(()=>{We();u_=(t,e)=>te(t.innerType._def,e)});function Ip(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Ip(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return dI(t,e)}}var dI,Op=O(()=>{Vr();dI=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":ve(r,"minimum",n.value,n.message,e);break;case"max":ve(r,"maximum",n.value,n.message,e);break}return r}});function d_(t,e){return{...te(t.innerType._def,e),default:t.defaultValue()}}var Cp=O(()=>{We()});function p_(t,e){return e.effectStrategy==="input"?te(t.schema._def,e):qe(e)}var zp=O(()=>{We();Dt()});function f_(t){return{type:"string",enum:Array.from(t.values)}}var Np=O(()=>{});function h_(t,e){let r=[te(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),te(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(pI(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}var pI,jp=O(()=>{We();pI=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function m_(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var Lp=O(()=>{});function ja(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ve(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ve(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Jt(r,"email",n.message,e);break;case"format:idn-email":Jt(r,"idn-email",n.message,e);break;case"pattern:zod":pt(r,Gt.email,n.message,e);break}break;case"url":Jt(r,"uri",n.message,e);break;case"uuid":Jt(r,"uuid",n.message,e);break;case"regex":pt(r,n.regex,n.message,e);break;case"cuid":pt(r,Gt.cuid,n.message,e);break;case"cuid2":pt(r,Gt.cuid2,n.message,e);break;case"startsWith":pt(r,RegExp(`^${Dp(n.value,e)}`),n.message,e);break;case"endsWith":pt(r,RegExp(`${Dp(n.value,e)}$`),n.message,e);break;case"datetime":Jt(r,"date-time",n.message,e);break;case"date":Jt(r,"date",n.message,e);break;case"time":Jt(r,"time",n.message,e);break;case"duration":Jt(r,"duration",n.message,e);break;case"length":ve(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ve(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{pt(r,RegExp(Dp(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Jt(r,"ipv4",n.message,e),n.version!=="v4"&&Jt(r,"ipv6",n.message,e);break}case"base64url":pt(r,Gt.base64url,n.message,e);break;case"jwt":pt(r,Gt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&pt(r,Gt.ipv4Cidr,n.message,e),n.version!=="v4"&&pt(r,Gt.ipv6Cidr,n.message,e);break}case"emoji":pt(r,Gt.emoji(),n.message,e);break;case"ulid":{pt(r,Gt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Jt(r,"binary",n.message,e);break}case"contentEncoding:base64":{ve(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{pt(r,Gt.base64,n.message,e);break}}break}case"nanoid":pt(r,Gt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Dp(t,e){return e.patternStrategy==="escape"?hI(t):t}function hI(t){let e="";for(let r=0;r<t.length;r++)fI.has(t[r])||(e+="\\"),e+=t[r];return e}function Jt(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ve(t,"format",e,r,n)}function pt(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:g_(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ve(t,"pattern",g_(e,n),r,n)}function g_(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
1127
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let u of this.seen.entries()){let d=u[1];if(e===u[0]){i(u);continue}if(n.external){let m=n.external.registry.get(u[0])?.id;if(e!==u[0]&&m){i(u);continue}}if(this.metadataRegistry.get(u[0])?.id){i(u);continue}if(d.cycle){i(u);continue}if(d.count>1&&n.reused==="ref"){i(u);continue}}let a=(u,d)=>{let b=this.seen.get(u),m=b.def??b.schema,f={...m};if(b.ref===null)return;let y=b.ref;if(b.ref=null,y){a(y,d);let v=this.seen.get(y).schema;v.$ref&&d.target==="draft-7"?(m.allOf=m.allOf??[],m.allOf.push(v)):(Object.assign(m,v),Object.assign(m,f))}b.isParent||this.override({zodSchema:u,jsonSchema:m,path:b.path??[]})};for(let u of[...this.seen.entries()].reverse())a(u[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let u=n.external.registry.get(e)?.id;if(!u)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(u)}Object.assign(c,o.def);let l=n.external?.defs??{};for(let u of this.seen.entries()){let d=u[1];d.def&&d.defId&&(l[d.defId]=d.def)}n.external||Object.keys(l).length>0&&(this.target==="draft-2020-12"?c.$defs=l:c.definitions=l);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}});var vw=O(()=>{});var dt=O(()=>{ao();yu();uu();lw();Qi();ku();cr();Xi();sa();pd();xu();ww();bw();_w();vw()});var ep=O(()=>{dt()});function tp(t,e){let r={type:"object",get shape(){return _e.assignProp(this,"shape",{...t}),this.shape},..._e.normalizeParams(e)};return new gP(r)}var mP,gP,xw=O(()=>{dt();dt();ep();mP=I("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");Pe.init(t,e),t.def=e,t.parse=(r,n)=>pu(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>$n(t,r,n),t.parseAsync=async(r,n)=>hu(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Sn(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Rt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),gP=I("ZodMiniObject",(t,e)=>{na.init(t,e),mP.init(t,e),_e.defineLazy(t,"shape",()=>e.shape)})});var kw=O(()=>{});var $w=O(()=>{});var Sw=O(()=>{});var Tw=O(()=>{dt();ep();xw();kw();dt();sa();$w();Sw()});var Ew=O(()=>{Tw()});var rp=O(()=>{Ew()});function lr(t){return!!t._zod}function Rn(t){let e=Object.values(t);if(e.length===0)return tp({});let r=e.every(lr),n=e.every(o=>!lr(o));if(r)return tp(t);if(n)return il(t);throw new Error("Mixed Zod versions detected in object shape.")}function Fr(t,e){return lr(t)?$n(t,e):t.safeParse(e)}async function fa(t,e){return lr(t)?await Sn(t,e):await t.safeParseAsync(e)}function Br(t){if(!t)return;let e;if(lr(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function po(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Rn(t)}}if(lr(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function wP(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function ha(t){if(t&&typeof t=="object"){if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0)return t.issues.map(e=>e.path?.length?`${e.message} at ${wP(e.path)}`:e.message).join(`
1128
+ `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function Pw(t){return t.description}function Aw(t){if(lr(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function fo(t){if(lr(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var ks=O(()=>{us();rp()});var np=O(()=>{dt()});var $s={};qo($s,{ZodISODate:()=>Ow,ZodISODateTime:()=>Iw,ZodISODuration:()=>zw,ZodISOTime:()=>Cw,date:()=>sp,datetime:()=>op,duration:()=>ap,time:()=>ip});function op(t){return fw(Iw,t)}function sp(t){return hw(Ow,t)}function ip(t){return mw(Cw,t)}function ap(t){return gw(zw,t)}var Iw,Ow,Cw,zw,cp=O(()=>{dt();lp();Iw=I("ZodISODateTime",(t,e)=>{ow.init(t,e),Me.init(t,e)});Ow=I("ZodISODate",(t,e)=>{sw.init(t,e),Me.init(t,e)});Cw=I("ZodISOTime",(t,e)=>{iw.init(t,e),Me.init(t,e)});zw=I("ZodISODuration",(t,e)=>{aw.init(t,e),Me.init(t,e)})});var Nw,gq,Ss,up=O(()=>{dt();dt();Nw=(t,e)=>{Ji.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>lu(t,r)},flatten:{value:r=>cu(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},gq=I("ZodError",Nw),Ss=I("ZodError",Nw,{Parent:Error})});var jw,Lw,Dw,Mw,dp=O(()=>{dt();up();jw=du(Ss),Lw=fu(Ss),Dw=mu(Ss),Mw=gu(Ss)});function A(t){return fd(EP,t)}function Re(t){return Nd(Bw,t)}function Zw(t){return jd(VP,t)}function Xe(t){return Ld(HP,t)}function Vw(t){return Dd(KP,t)}function Ue(){return Md(GP)}function JP(t){return Ud(WP,t)}function ve(t,e){return yw(YP,t,e)}function B(t,e){let r={type:"object",get shape(){return _e.assignProp(this,"shape",{...t}),this.shape},..._e.normalizeParams(e)};return new Hw(r)}function pt(t,e){return new Hw({type:"object",get shape(){return _e.assignProp(this,"shape",{...t}),this.shape},catchall:Ue(),..._e.normalizeParams(e)})}function Ne(t,e){return new Kw({type:"union",options:t,..._e.normalizeParams(e)})}function hp(t,e,r){return new XP({type:"union",options:e,discriminator:t,..._e.normalizeParams(r)})}function ga(t,e){return new QP({type:"intersection",left:t,right:e})}function ze(t,e,r){return new eA({type:"record",keyType:t,valueType:e,..._e.normalizeParams(r)})}function _t(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new pp({type:"enum",entries:r,..._e.normalizeParams(e)})}function W(t,e){return new tA({type:"literal",values:Array.isArray(t)?t:[t],..._e.normalizeParams(e)})}function Gw(t){return new rA({type:"transform",transform:t})}function Ze(t){return new Ww({type:"optional",innerType:t})}function qw(t){return new nA({type:"nullable",innerType:t})}function sA(t,e){return new oA({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function aA(t,e){return new iA({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function cA(t,e){return new Jw({type:"nonoptional",innerType:t,..._e.normalizeParams(e)})}function uA(t,e){return new lA({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function fp(t,e){return new dA({type:"pipe",in:t,out:e})}function fA(t){return new pA({type:"readonly",innerType:t})}function hA(t){let e=new tt({check:"custom"});return e._zod.check=t,e}function Xw(t,e){return Yd(Yw,t??(()=>!0),e)}function mA(t,e={}){return Xd(Yw,t,e)}function gA(t){let e=hA(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(_e.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(_e.issue(o))}},t(r.value,r)));return e}function mp(t,e){return fp(Gw(t),e)}var Fe,Fw,EP,Me,RP,Uw,ma,PP,AP,IP,OP,CP,zP,NP,jP,LP,DP,MP,UP,ZP,qP,FP,BP,Bw,VP,HP,KP,GP,WP,YP,Hw,Kw,XP,QP,eA,pp,tA,rA,Ww,nA,oA,iA,Jw,lA,dA,pA,Yw,lp=O(()=>{dt();dt();np();cp();dp();Fe=I("ZodType",(t,e)=>(Pe.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Rt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>jw(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Dw(t,r,n),t.parseAsync=async(r,n)=>Lw(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Mw(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(mA(r,n)),t.superRefine=r=>t.check(gA(r)),t.overwrite=r=>t.check(Tn(r)),t.optional=()=>Ze(t),t.nullable=()=>qw(t),t.nullish=()=>Ze(qw(t)),t.nonoptional=r=>cA(t,r),t.array=()=>ve(t),t.or=r=>Ne([t,r]),t.and=r=>ga(t,r),t.transform=r=>fp(t,Gw(r)),t.default=r=>sA(t,r),t.prefault=r=>aA(t,r),t.catch=r=>uA(t,r),t.pipe=r=>fp(t,r),t.readonly=()=>fA(t),t.describe=r=>{let n=t.clone();return qr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return qr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return qr.get(t);let n=t.clone();return qr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Fw=I("_ZodString",(t,e)=>{ws.init(t,e),Fe.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Zd(...n)),t.includes=(...n)=>t.check(Bd(...n)),t.startsWith=(...n)=>t.check(Vd(...n)),t.endsWith=(...n)=>t.check(Hd(...n)),t.min=(...n)=>t.check(uo(...n)),t.max=(...n)=>t.check(ua(...n)),t.length=(...n)=>t.check(da(...n)),t.nonempty=(...n)=>t.check(uo(1,...n)),t.lowercase=n=>t.check(qd(n)),t.uppercase=n=>t.check(Fd(n)),t.trim=()=>t.check(Gd()),t.normalize=(...n)=>t.check(Kd(...n)),t.toLowerCase=()=>t.check(Wd()),t.toUpperCase=()=>t.check(Jd())}),EP=I("ZodString",(t,e)=>{ws.init(t,e),Fw.init(t,e),t.email=r=>t.check(hd(RP,r)),t.url=r=>t.check(wd(PP,r)),t.jwt=r=>t.check(zd(BP,r)),t.emoji=r=>t.check(_d(AP,r)),t.guid=r=>t.check(ia(Uw,r)),t.uuid=r=>t.check(md(ma,r)),t.uuidv4=r=>t.check(gd(ma,r)),t.uuidv6=r=>t.check(yd(ma,r)),t.uuidv7=r=>t.check(bd(ma,r)),t.nanoid=r=>t.check(vd(IP,r)),t.guid=r=>t.check(ia(Uw,r)),t.cuid=r=>t.check(xd(OP,r)),t.cuid2=r=>t.check(kd(CP,r)),t.ulid=r=>t.check($d(zP,r)),t.base64=r=>t.check(Id(ZP,r)),t.base64url=r=>t.check(Od(qP,r)),t.xid=r=>t.check(Sd(NP,r)),t.ksuid=r=>t.check(Td(jP,r)),t.ipv4=r=>t.check(Ed(LP,r)),t.ipv6=r=>t.check(Rd(DP,r)),t.cidrv4=r=>t.check(Pd(MP,r)),t.cidrv6=r=>t.check(Ad(UP,r)),t.e164=r=>t.check(Cd(FP,r)),t.datetime=r=>t.check(op(r)),t.date=r=>t.check(sp(r)),t.time=r=>t.check(ip(r)),t.duration=r=>t.check(ap(r))});Me=I("ZodStringFormat",(t,e)=>{Ce.init(t,e),Fw.init(t,e)}),RP=I("ZodEmail",(t,e)=>{Eu.init(t,e),Me.init(t,e)}),Uw=I("ZodGUID",(t,e)=>{Su.init(t,e),Me.init(t,e)}),ma=I("ZodUUID",(t,e)=>{Tu.init(t,e),Me.init(t,e)}),PP=I("ZodURL",(t,e)=>{Ru.init(t,e),Me.init(t,e)}),AP=I("ZodEmoji",(t,e)=>{Pu.init(t,e),Me.init(t,e)}),IP=I("ZodNanoID",(t,e)=>{Au.init(t,e),Me.init(t,e)}),OP=I("ZodCUID",(t,e)=>{Iu.init(t,e),Me.init(t,e)}),CP=I("ZodCUID2",(t,e)=>{Ou.init(t,e),Me.init(t,e)}),zP=I("ZodULID",(t,e)=>{Cu.init(t,e),Me.init(t,e)}),NP=I("ZodXID",(t,e)=>{zu.init(t,e),Me.init(t,e)}),jP=I("ZodKSUID",(t,e)=>{Nu.init(t,e),Me.init(t,e)}),LP=I("ZodIPv4",(t,e)=>{ju.init(t,e),Me.init(t,e)}),DP=I("ZodIPv6",(t,e)=>{Lu.init(t,e),Me.init(t,e)}),MP=I("ZodCIDRv4",(t,e)=>{Du.init(t,e),Me.init(t,e)}),UP=I("ZodCIDRv6",(t,e)=>{Mu.init(t,e),Me.init(t,e)}),ZP=I("ZodBase64",(t,e)=>{Uu.init(t,e),Me.init(t,e)}),qP=I("ZodBase64URL",(t,e)=>{Zu.init(t,e),Me.init(t,e)}),FP=I("ZodE164",(t,e)=>{qu.init(t,e),Me.init(t,e)}),BP=I("ZodJWT",(t,e)=>{Fu.init(t,e),Me.init(t,e)}),Bw=I("ZodNumber",(t,e)=>{ra.init(t,e),Fe.init(t,e),t.gt=(n,o)=>t.check(ca(n,o)),t.gte=(n,o)=>t.check(xs(n,o)),t.min=(n,o)=>t.check(xs(n,o)),t.lt=(n,o)=>t.check(aa(n,o)),t.lte=(n,o)=>t.check(vs(n,o)),t.max=(n,o)=>t.check(vs(n,o)),t.int=n=>t.check(Zw(n)),t.safe=n=>t.check(Zw(n)),t.positive=n=>t.check(ca(0,n)),t.nonnegative=n=>t.check(xs(0,n)),t.negative=n=>t.check(aa(0,n)),t.nonpositive=n=>t.check(vs(0,n)),t.multipleOf=(n,o)=>t.check(la(n,o)),t.step=(n,o)=>t.check(la(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});VP=I("ZodNumberFormat",(t,e)=>{Bu.init(t,e),Bw.init(t,e)});HP=I("ZodBoolean",(t,e)=>{Vu.init(t,e),Fe.init(t,e)});KP=I("ZodNull",(t,e)=>{Hu.init(t,e),Fe.init(t,e)});GP=I("ZodUnknown",(t,e)=>{Ku.init(t,e),Fe.init(t,e)});WP=I("ZodNever",(t,e)=>{Gu.init(t,e),Fe.init(t,e)});YP=I("ZodArray",(t,e)=>{Wu.init(t,e),Fe.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(uo(r,n)),t.nonempty=r=>t.check(uo(1,r)),t.max=(r,n)=>t.check(ua(r,n)),t.length=(r,n)=>t.check(da(r,n)),t.unwrap=()=>t.element});Hw=I("ZodObject",(t,e)=>{na.init(t,e),Fe.init(t,e),_e.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>_t(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Ue()}),t.loose=()=>t.clone({...t._zod.def,catchall:Ue()}),t.strict=()=>t.clone({...t._zod.def,catchall:JP()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>_e.extend(t,r),t.merge=r=>_e.merge(t,r),t.pick=r=>_e.pick(t,r),t.omit=r=>_e.omit(t,r),t.partial=(...r)=>_e.partial(Ww,t,r[0]),t.required=(...r)=>_e.required(Jw,t,r[0])});Kw=I("ZodUnion",(t,e)=>{oa.init(t,e),Fe.init(t,e),t.options=e.options});XP=I("ZodDiscriminatedUnion",(t,e)=>{Kw.init(t,e),Ju.init(t,e)});QP=I("ZodIntersection",(t,e)=>{Yu.init(t,e),Fe.init(t,e)});eA=I("ZodRecord",(t,e)=>{Xu.init(t,e),Fe.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});pp=I("ZodEnum",(t,e)=>{Qu.init(t,e),Fe.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new pp({...e,checks:[],..._e.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new pp({...e,checks:[],..._e.normalizeParams(o),entries:s})}});tA=I("ZodLiteral",(t,e)=>{ed.init(t,e),Fe.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});rA=I("ZodTransform",(t,e)=>{td.init(t,e),Fe.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(_e.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(_e.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});Ww=I("ZodOptional",(t,e)=>{rd.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});nA=I("ZodNullable",(t,e)=>{nd.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});oA=I("ZodDefault",(t,e)=>{od.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});iA=I("ZodPrefault",(t,e)=>{sd.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});Jw=I("ZodNonOptional",(t,e)=>{id.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});lA=I("ZodCatch",(t,e)=>{ad.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});dA=I("ZodPipe",(t,e)=>{cd.init(t,e),Fe.init(t,e),t.in=e.in,t.out=e.out});pA=I("ZodReadonly",(t,e)=>{ld.init(t,e),Fe.init(t,e)});Yw=I("ZodCustom",(t,e)=>{ud.init(t,e),Fe.init(t,e)})});var Qw=O(()=>{});var e_=O(()=>{});var t_=O(()=>{dt();lp();np();up();dp();Qw();dt();dw();sa();cp();e_();Et(uw())});var r_=O(()=>{t_()});var n_=O(()=>{r_()});function __(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function v_(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var yp,o_,Vr,ba,Je,s_,i_,Oq,wA,_A,bp,Pt,Ts,a_,rt,Mt,Ut,nt,wa,c_,wp,l_,u_,_p,Es,X,vp,d_,p_,Cq,_a,vA,va,xA,Rs,ho,f_,kA,$A,SA,TA,EA,RA,xp,PA,AA,kp,xa,IA,OA,ka,CA,Ps,As,zA,Is,mo,NA,Os,$a,Sa,Ta,zq,Ea,Ra,Pa,h_,m_,g_,$p,y_,Cs,go,b_,jA,Aa,LA,Ia,DA,Sp,MA,Oa,UA,ZA,qA,FA,BA,VA,HA,KA,GA,WA,Ca,JA,YA,za,Tp,Ep,Rp,XA,QA,eI,Pp,tI,rI,nI,oI,sI,w_,Na,iI,ja,Nq,aI,yo,cI,jq,zs,lI,Ap,uI,dI,pI,fI,hI,mI,gI,ya,yI,bI,wI,Ns,Ip,_I,vI,xI,kI,$I,SI,TI,EI,RI,PI,AI,II,OI,CI,zI,NI,jI,LI,bo,DI,MI,UI,La,ZI,qI,FI,Op,BI,Lq,Dq,Mq,Uq,Zq,qq,G,gp,wo=O(()=>{n_();yp="2025-11-25",o_=[yp,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Vr="io.modelcontextprotocol/related-task",ba="2.0",Je=Xw(t=>t!==null&&(typeof t=="object"||typeof t=="function")),s_=Ne([A(),Re().int()]),i_=A(),Oq=pt({ttl:Re().optional(),pollInterval:Re().optional()}),wA=B({ttl:Re().optional()}),_A=B({taskId:A()}),bp=pt({progressToken:s_.optional(),[Vr]:_A.optional()}),Pt=B({_meta:bp.optional()}),Ts=Pt.extend({task:wA.optional()}),a_=t=>Ts.safeParse(t).success,rt=B({method:A(),params:Pt.loose().optional()}),Mt=B({_meta:bp.optional()}),Ut=B({method:A(),params:Mt.loose().optional()}),nt=pt({_meta:bp.optional()}),wa=Ne([A(),Re().int()]),c_=B({jsonrpc:W(ba),id:wa,...rt.shape}).strict(),wp=t=>c_.safeParse(t).success,l_=B({jsonrpc:W(ba),...Ut.shape}).strict(),u_=t=>l_.safeParse(t).success,_p=B({jsonrpc:W(ba),id:wa,result:nt}).strict(),Es=t=>_p.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(X||(X={}));vp=B({jsonrpc:W(ba),id:wa.optional(),error:B({code:Re().int(),message:A(),data:Ue().optional()})}).strict(),d_=t=>vp.safeParse(t).success,p_=Ne([c_,l_,_p,vp]),Cq=Ne([_p,vp]),_a=nt.strict(),vA=Mt.extend({requestId:wa.optional(),reason:A().optional()}),va=Ut.extend({method:W("notifications/cancelled"),params:vA}),xA=B({src:A(),mimeType:A().optional(),sizes:ve(A()).optional(),theme:_t(["light","dark"]).optional()}),Rs=B({icons:ve(xA).optional()}),ho=B({name:A(),title:A().optional()}),f_=ho.extend({...ho.shape,...Rs.shape,version:A(),websiteUrl:A().optional(),description:A().optional()}),kA=ga(B({applyDefaults:Xe().optional()}),ze(A(),Ue())),$A=mp(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,ga(B({form:kA.optional(),url:Je.optional()}),ze(A(),Ue()).optional())),SA=pt({list:Je.optional(),cancel:Je.optional(),requests:pt({sampling:pt({createMessage:Je.optional()}).optional(),elicitation:pt({create:Je.optional()}).optional()}).optional()}),TA=pt({list:Je.optional(),cancel:Je.optional(),requests:pt({tools:pt({call:Je.optional()}).optional()}).optional()}),EA=B({experimental:ze(A(),Je).optional(),sampling:B({context:Je.optional(),tools:Je.optional()}).optional(),elicitation:$A.optional(),roots:B({listChanged:Xe().optional()}).optional(),tasks:SA.optional(),extensions:ze(A(),Je).optional()}),RA=Pt.extend({protocolVersion:A(),capabilities:EA,clientInfo:f_}),xp=rt.extend({method:W("initialize"),params:RA}),PA=B({experimental:ze(A(),Je).optional(),logging:Je.optional(),completions:Je.optional(),prompts:B({listChanged:Xe().optional()}).optional(),resources:B({subscribe:Xe().optional(),listChanged:Xe().optional()}).optional(),tools:B({listChanged:Xe().optional()}).optional(),tasks:TA.optional(),extensions:ze(A(),Je).optional()}),AA=nt.extend({protocolVersion:A(),capabilities:PA,serverInfo:f_,instructions:A().optional()}),kp=Ut.extend({method:W("notifications/initialized"),params:Mt.optional()}),xa=rt.extend({method:W("ping"),params:Pt.optional()}),IA=B({progress:Re(),total:Ze(Re()),message:Ze(A())}),OA=B({...Mt.shape,...IA.shape,progressToken:s_}),ka=Ut.extend({method:W("notifications/progress"),params:OA}),CA=Pt.extend({cursor:i_.optional()}),Ps=rt.extend({params:CA.optional()}),As=nt.extend({nextCursor:i_.optional()}),zA=_t(["working","input_required","completed","failed","cancelled"]),Is=B({taskId:A(),status:zA,ttl:Ne([Re(),Vw()]),createdAt:A(),lastUpdatedAt:A(),pollInterval:Ze(Re()),statusMessage:Ze(A())}),mo=nt.extend({task:Is}),NA=Mt.merge(Is),Os=Ut.extend({method:W("notifications/tasks/status"),params:NA}),$a=rt.extend({method:W("tasks/get"),params:Pt.extend({taskId:A()})}),Sa=nt.merge(Is),Ta=rt.extend({method:W("tasks/result"),params:Pt.extend({taskId:A()})}),zq=nt.loose(),Ea=Ps.extend({method:W("tasks/list")}),Ra=As.extend({tasks:ve(Is)}),Pa=rt.extend({method:W("tasks/cancel"),params:Pt.extend({taskId:A()})}),h_=nt.merge(Is),m_=B({uri:A(),mimeType:Ze(A()),_meta:ze(A(),Ue()).optional()}),g_=m_.extend({text:A()}),$p=A().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),y_=m_.extend({blob:$p}),Cs=_t(["user","assistant"]),go=B({audience:ve(Cs).optional(),priority:Re().min(0).max(1).optional(),lastModified:$s.datetime({offset:!0}).optional()}),b_=B({...ho.shape,...Rs.shape,uri:A(),description:Ze(A()),mimeType:Ze(A()),size:Ze(Re()),annotations:go.optional(),_meta:Ze(pt({}))}),jA=B({...ho.shape,...Rs.shape,uriTemplate:A(),description:Ze(A()),mimeType:Ze(A()),annotations:go.optional(),_meta:Ze(pt({}))}),Aa=Ps.extend({method:W("resources/list")}),LA=As.extend({resources:ve(b_)}),Ia=Ps.extend({method:W("resources/templates/list")}),DA=As.extend({resourceTemplates:ve(jA)}),Sp=Pt.extend({uri:A()}),MA=Sp,Oa=rt.extend({method:W("resources/read"),params:MA}),UA=nt.extend({contents:ve(Ne([g_,y_]))}),ZA=Ut.extend({method:W("notifications/resources/list_changed"),params:Mt.optional()}),qA=Sp,FA=rt.extend({method:W("resources/subscribe"),params:qA}),BA=Sp,VA=rt.extend({method:W("resources/unsubscribe"),params:BA}),HA=Mt.extend({uri:A()}),KA=Ut.extend({method:W("notifications/resources/updated"),params:HA}),GA=B({name:A(),description:Ze(A()),required:Ze(Xe())}),WA=B({...ho.shape,...Rs.shape,description:Ze(A()),arguments:Ze(ve(GA)),_meta:Ze(pt({}))}),Ca=Ps.extend({method:W("prompts/list")}),JA=As.extend({prompts:ve(WA)}),YA=Pt.extend({name:A(),arguments:ze(A(),A()).optional()}),za=rt.extend({method:W("prompts/get"),params:YA}),Tp=B({type:W("text"),text:A(),annotations:go.optional(),_meta:ze(A(),Ue()).optional()}),Ep=B({type:W("image"),data:$p,mimeType:A(),annotations:go.optional(),_meta:ze(A(),Ue()).optional()}),Rp=B({type:W("audio"),data:$p,mimeType:A(),annotations:go.optional(),_meta:ze(A(),Ue()).optional()}),XA=B({type:W("tool_use"),name:A(),id:A(),input:ze(A(),Ue()),_meta:ze(A(),Ue()).optional()}),QA=B({type:W("resource"),resource:Ne([g_,y_]),annotations:go.optional(),_meta:ze(A(),Ue()).optional()}),eI=b_.extend({type:W("resource_link")}),Pp=Ne([Tp,Ep,Rp,eI,QA]),tI=B({role:Cs,content:Pp}),rI=nt.extend({description:A().optional(),messages:ve(tI)}),nI=Ut.extend({method:W("notifications/prompts/list_changed"),params:Mt.optional()}),oI=B({title:A().optional(),readOnlyHint:Xe().optional(),destructiveHint:Xe().optional(),idempotentHint:Xe().optional(),openWorldHint:Xe().optional()}),sI=B({taskSupport:_t(["required","optional","forbidden"]).optional()}),w_=B({...ho.shape,...Rs.shape,description:A().optional(),inputSchema:B({type:W("object"),properties:ze(A(),Je).optional(),required:ve(A()).optional()}).catchall(Ue()),outputSchema:B({type:W("object"),properties:ze(A(),Je).optional(),required:ve(A()).optional()}).catchall(Ue()).optional(),annotations:oI.optional(),execution:sI.optional(),_meta:ze(A(),Ue()).optional()}),Na=Ps.extend({method:W("tools/list")}),iI=As.extend({tools:ve(w_)}),ja=nt.extend({content:ve(Pp).default([]),structuredContent:ze(A(),Ue()).optional(),isError:Xe().optional()}),Nq=ja.or(nt.extend({toolResult:Ue()})),aI=Ts.extend({name:A(),arguments:ze(A(),Ue()).optional()}),yo=rt.extend({method:W("tools/call"),params:aI}),cI=Ut.extend({method:W("notifications/tools/list_changed"),params:Mt.optional()}),jq=B({autoRefresh:Xe().default(!0),debounceMs:Re().int().nonnegative().default(300)}),zs=_t(["debug","info","notice","warning","error","critical","alert","emergency"]),lI=Pt.extend({level:zs}),Ap=rt.extend({method:W("logging/setLevel"),params:lI}),uI=Mt.extend({level:zs,logger:A().optional(),data:Ue()}),dI=Ut.extend({method:W("notifications/message"),params:uI}),pI=B({name:A().optional()}),fI=B({hints:ve(pI).optional(),costPriority:Re().min(0).max(1).optional(),speedPriority:Re().min(0).max(1).optional(),intelligencePriority:Re().min(0).max(1).optional()}),hI=B({mode:_t(["auto","required","none"]).optional()}),mI=B({type:W("tool_result"),toolUseId:A().describe("The unique identifier for the corresponding tool call."),content:ve(Pp).default([]),structuredContent:B({}).loose().optional(),isError:Xe().optional(),_meta:ze(A(),Ue()).optional()}),gI=hp("type",[Tp,Ep,Rp]),ya=hp("type",[Tp,Ep,Rp,XA,mI]),yI=B({role:Cs,content:Ne([ya,ve(ya)]),_meta:ze(A(),Ue()).optional()}),bI=Ts.extend({messages:ve(yI),modelPreferences:fI.optional(),systemPrompt:A().optional(),includeContext:_t(["none","thisServer","allServers"]).optional(),temperature:Re().optional(),maxTokens:Re().int(),stopSequences:ve(A()).optional(),metadata:Je.optional(),tools:ve(w_).optional(),toolChoice:hI.optional()}),wI=rt.extend({method:W("sampling/createMessage"),params:bI}),Ns=nt.extend({model:A(),stopReason:Ze(_t(["endTurn","stopSequence","maxTokens"]).or(A())),role:Cs,content:gI}),Ip=nt.extend({model:A(),stopReason:Ze(_t(["endTurn","stopSequence","maxTokens","toolUse"]).or(A())),role:Cs,content:Ne([ya,ve(ya)])}),_I=B({type:W("boolean"),title:A().optional(),description:A().optional(),default:Xe().optional()}),vI=B({type:W("string"),title:A().optional(),description:A().optional(),minLength:Re().optional(),maxLength:Re().optional(),format:_t(["email","uri","date","date-time"]).optional(),default:A().optional()}),xI=B({type:_t(["number","integer"]),title:A().optional(),description:A().optional(),minimum:Re().optional(),maximum:Re().optional(),default:Re().optional()}),kI=B({type:W("string"),title:A().optional(),description:A().optional(),enum:ve(A()),default:A().optional()}),$I=B({type:W("string"),title:A().optional(),description:A().optional(),oneOf:ve(B({const:A(),title:A()})),default:A().optional()}),SI=B({type:W("string"),title:A().optional(),description:A().optional(),enum:ve(A()),enumNames:ve(A()).optional(),default:A().optional()}),TI=Ne([kI,$I]),EI=B({type:W("array"),title:A().optional(),description:A().optional(),minItems:Re().optional(),maxItems:Re().optional(),items:B({type:W("string"),enum:ve(A())}),default:ve(A()).optional()}),RI=B({type:W("array"),title:A().optional(),description:A().optional(),minItems:Re().optional(),maxItems:Re().optional(),items:B({anyOf:ve(B({const:A(),title:A()}))}),default:ve(A()).optional()}),PI=Ne([EI,RI]),AI=Ne([SI,TI,PI]),II=Ne([AI,_I,vI,xI]),OI=Ts.extend({mode:W("form").optional(),message:A(),requestedSchema:B({type:W("object"),properties:ze(A(),II),required:ve(A()).optional()})}),CI=Ts.extend({mode:W("url"),message:A(),elicitationId:A(),url:A().url()}),zI=Ne([OI,CI]),NI=rt.extend({method:W("elicitation/create"),params:zI}),jI=Mt.extend({elicitationId:A()}),LI=Ut.extend({method:W("notifications/elicitation/complete"),params:jI}),bo=nt.extend({action:_t(["accept","decline","cancel"]),content:mp(t=>t===null?void 0:t,ze(A(),Ne([A(),Re(),Xe(),ve(A())])).optional())}),DI=B({type:W("ref/resource"),uri:A()}),MI=B({type:W("ref/prompt"),name:A()}),UI=Pt.extend({ref:Ne([MI,DI]),argument:B({name:A(),value:A()}),context:B({arguments:ze(A(),A()).optional()}).optional()}),La=rt.extend({method:W("completion/complete"),params:UI});ZI=nt.extend({completion:pt({values:ve(A()).max(100),total:Ze(Re().int()),hasMore:Ze(Xe())})}),qI=B({uri:A().startsWith("file://"),name:A().optional(),_meta:ze(A(),Ue()).optional()}),FI=rt.extend({method:W("roots/list"),params:Pt.optional()}),Op=nt.extend({roots:ve(qI)}),BI=Ut.extend({method:W("notifications/roots/list_changed"),params:Mt.optional()}),Lq=Ne([xa,xp,La,Ap,za,Ca,Aa,Ia,Oa,FA,VA,yo,Na,$a,Ta,Ea,Pa]),Dq=Ne([va,ka,kp,BI,Os]),Mq=Ne([_a,Ns,Ip,bo,Op,Sa,Ra,mo]),Uq=Ne([xa,wI,NI,FI,$a,Ta,Ea,Pa]),Zq=Ne([va,ka,dI,KA,ZA,cI,nI,Os,LI]),qq=Ne([_a,AA,ZI,rI,JA,LA,DA,UA,ja,iI,Sa,Ra,mo]),G=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===X.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new gp(o.elicitations,r)}return new t(e,r,n)}},gp=class extends G{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(X.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Hr(t){return t==="completed"||t==="failed"||t==="cancelled"}var x_=O(()=>{});var $_,k_,S_,Da=O(()=>{$_=Symbol("Let zodToJsonSchema decide on which parser to use"),k_={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},S_=t=>typeof t=="string"?{...k_,name:t}:{...k_,...t}});var T_,Cp=O(()=>{Da();T_=t=>{let e=S_(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function zp(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function xe(t,e,r,n,o){t[e]=r,zp(t,e,n,o)}var Kr=O(()=>{});var Ma,Ua=O(()=>{Ma=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")}});function qe(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Ma(e,t.currentPath):e.join("/")}}var Zt=O(()=>{Ua()});function E_(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==D.ZodAny&&(r.items=re(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&xe(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&xe(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(xe(r,"minItems",t.exactLength.value,t.exactLength.message,e),xe(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var Np=O(()=>{us();Kr();Ge()});function R_(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?xe(r,"minimum",n.value,n.message,e):xe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),xe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?xe(r,"maximum",n.value,n.message,e):xe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),xe(r,"maximum",n.value,n.message,e));break;case"multipleOf":xe(r,"multipleOf",n.value,n.message,e);break}return r}var jp=O(()=>{Kr()});function P_(){return{type:"boolean"}}var Lp=O(()=>{});function Za(t,e){return re(t.type._def,e)}var qa=O(()=>{Ge()});var A_,Dp=O(()=>{Ge();A_=(t,e)=>re(t.innerType._def,e)});function Mp(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Mp(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return VI(t,e)}}var VI,Up=O(()=>{Kr();VI=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":xe(r,"minimum",n.value,n.message,e);break;case"max":xe(r,"maximum",n.value,n.message,e);break}return r}});function I_(t,e){return{...re(t.innerType._def,e),default:t.defaultValue()}}var Zp=O(()=>{Ge()});function O_(t,e){return e.effectStrategy==="input"?re(t.schema._def,e):qe(e)}var qp=O(()=>{Ge();Zt()});function C_(t){return{type:"string",enum:Array.from(t.values)}}var Fp=O(()=>{});function z_(t,e){let r=[re(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),re(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(HI(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}var HI,Bp=O(()=>{Ge();HI=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function N_(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var Vp=O(()=>{});function Fa(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":xe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":xe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Yt(r,"email",n.message,e);break;case"format:idn-email":Yt(r,"idn-email",n.message,e);break;case"pattern:zod":ft(r,Jt.email,n.message,e);break}break;case"url":Yt(r,"uri",n.message,e);break;case"uuid":Yt(r,"uuid",n.message,e);break;case"regex":ft(r,n.regex,n.message,e);break;case"cuid":ft(r,Jt.cuid,n.message,e);break;case"cuid2":ft(r,Jt.cuid2,n.message,e);break;case"startsWith":ft(r,RegExp(`^${Kp(n.value,e)}`),n.message,e);break;case"endsWith":ft(r,RegExp(`${Kp(n.value,e)}$`),n.message,e);break;case"datetime":Yt(r,"date-time",n.message,e);break;case"date":Yt(r,"date",n.message,e);break;case"time":Yt(r,"time",n.message,e);break;case"duration":Yt(r,"duration",n.message,e);break;case"length":xe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),xe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{ft(r,RegExp(Kp(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Yt(r,"ipv4",n.message,e),n.version!=="v4"&&Yt(r,"ipv6",n.message,e);break}case"base64url":ft(r,Jt.base64url,n.message,e);break;case"jwt":ft(r,Jt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&ft(r,Jt.ipv4Cidr,n.message,e),n.version!=="v4"&&ft(r,Jt.ipv6Cidr,n.message,e);break}case"emoji":ft(r,Jt.emoji(),n.message,e);break;case"ulid":{ft(r,Jt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Yt(r,"binary",n.message,e);break}case"contentEncoding:base64":{xe(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{ft(r,Jt.base64,n.message,e);break}}break}case"nanoid":ft(r,Jt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Kp(t,e){return e.patternStrategy==="escape"?GI(t):t}function GI(t){let e="";for(let r=0;r<t.length;r++)KI.has(t[r])||(e+="\\"),e+=t[r];return e}function Yt(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):xe(t,"format",e,r,n)}function ft(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:j_(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):xe(t,"pattern",j_(e,n),r,n)}function j_(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
982
1129
  ]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
983
1130
  ]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
984
1131
  `:`[${n[c]}\r
985
- ]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var Mp,Gt,fI,La=O(()=>{Vr();Gt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Mp===void 0&&(Mp=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Mp),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};fI=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function Ma(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===M.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:te(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??qe(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:te(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===M.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=ja(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===M.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===M.ZodBranded&&t.keyType._def.type._def.typeName===M.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=za(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var Da=O(()=>{ns();We();La();Na();Dt()});function y_(t,e){if(e.mapStrategy==="record")return Ma(t,e);let r=te(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||qe(e),n=te(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||qe(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var Up=O(()=>{We();Da();Dt()});function b_(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}var Zp=O(()=>{});function w_(t){return t.target==="openAi"?void 0:{not:qe({...t,currentPath:[...t.currentPath,"not"]})}}var qp=O(()=>{Dt()});function __(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Fp=O(()=>{});function x_(t,e){if(e.target==="openApi3")return v_(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Ps&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Ps[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return v_(t,e)}var Ps,v_,Ua=O(()=>{We();Ps={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};v_=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>te(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function k_(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Ps[t.innerType._def.typeName],nullable:!0}:{type:[Ps[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=te(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=te(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var Bp=O(()=>{We();Ua()});function $_(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",Tp(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ve(r,"minimum",n.value,n.message,e):ve(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ve(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ve(r,"maximum",n.value,n.message,e):ve(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ve(r,"maximum",n.value,n.message,e));break;case"multipleOf":ve(r,"multipleOf",n.value,n.message,e);break}return r}var Vp=O(()=>{Vr()});function S_(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let l=gI(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=te(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});u!==void 0&&(n.properties[a]=u,l||o.push(a))}o.length&&(n.required=o);let i=mI(t,e);return i!==void 0&&(n.additionalProperties=i),n}function mI(t,e){if(t.catchall._def.typeName!=="ZodNever")return te(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function gI(t){try{return t.isOptional()}catch{return!0}}var Hp=O(()=>{We()});var T_,Kp=O(()=>{We();Dt();T_=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return te(t.innerType._def,e);let r=te(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:qe(e)},r]}:qe(e)}});var E_,Wp=O(()=>{We();E_=(t,e)=>{if(e.pipeStrategy==="input")return te(t.in._def,e);if(e.pipeStrategy==="output")return te(t.out._def,e);let r=te(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=te(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function R_(t,e){return te(t.type._def,e)}var Gp=O(()=>{We()});function P_(t,e){let n={type:"array",uniqueItems:!0,items:te(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ve(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ve(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var Jp=O(()=>{Vr();We()});function A_(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>te(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:te(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>te(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var Yp=O(()=>{We()});function I_(t){return{not:qe(t)}}var Xp=O(()=>{Dt()});function O_(t){return qe(t)}var Qp=O(()=>{Dt()});var C_,ef=O(()=>{We();C_=(t,e)=>te(t.innerType._def,e)});var z_,tf=O(()=>{ns();Dt();Ep();Rp();Pp();Na();Ap();Op();Cp();zp();Np();jp();Lp();Up();Zp();qp();Fp();Bp();Vp();Hp();Kp();Wp();Gp();Da();Jp();La();Yp();Xp();Ua();Qp();ef();z_=(t,e,r)=>{switch(e){case M.ZodString:return ja(t,r);case M.ZodNumber:return $_(t,r);case M.ZodObject:return S_(t,r);case M.ZodBigInt:return c_(t,r);case M.ZodBoolean:return l_();case M.ZodDate:return Ip(t,r);case M.ZodUndefined:return I_(r);case M.ZodNull:return __(r);case M.ZodArray:return a_(t,r);case M.ZodUnion:case M.ZodDiscriminatedUnion:return x_(t,r);case M.ZodIntersection:return h_(t,r);case M.ZodTuple:return A_(t,r);case M.ZodRecord:return Ma(t,r);case M.ZodLiteral:return m_(t,r);case M.ZodEnum:return f_(t);case M.ZodNativeEnum:return b_(t);case M.ZodNullable:return k_(t,r);case M.ZodOptional:return T_(t,r);case M.ZodMap:return y_(t,r);case M.ZodSet:return P_(t,r);case M.ZodLazy:return()=>t.getter()._def;case M.ZodPromise:return R_(t,r);case M.ZodNaN:case M.ZodNever:return w_(r);case M.ZodEffects:return p_(t,r);case M.ZodAny:return qe(r);case M.ZodUnknown:return O_(r);case M.ZodDefault:return d_(t,r);case M.ZodBranded:return za(t,r);case M.ZodReadonly:return C_(t,r);case M.ZodCatch:return u_(t,r);case M.ZodPipeline:return E_(t,r);case M.ZodFunction:case M.ZodVoid:case M.ZodSymbol:return;default:return(n=>{})(e)}}});function te(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==o_)return a}if(n&&!r){let a=yI(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=z_(t,t.typeName,e),i=typeof s=="function"?te(s(),e):s;if(i&&bI(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var yI,bI,We=O(()=>{Ia();tf();Ca();Dt();yI=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Oa(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),qe(e)):e.$refStrategy==="seen"?qe(e):void 0}},bI=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var N_=O(()=>{});var rf,nf=O(()=>{We();Sp();Dt();rf=(t,e)=>{let r=i_(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:te(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??qe(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=te(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??qe(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var j_=O(()=>{Ia();Sp();Vr();Ca();We();N_();Dt();Ep();Rp();Pp();Na();Ap();Op();Cp();zp();Np();jp();Lp();Up();Zp();qp();Fp();Bp();Vp();Hp();Kp();Wp();Gp();ef();Da();Jp();La();Yp();Xp();Ua();Qp();tf();nf();nf()});function wI(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function of(t,e){return lr(t)?Vd(t,{target:wI(e?.target),io:e?.pipeStrategy??"input"}):rf(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function sf(t){let r=qr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=uo(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function af(t,e){let r=Zr(t,e);if(!r.success)throw r.error;return r.data}var cf=O(()=>{Wd();gs();j_()});function L_(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function M_(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];L_(i)&&L_(s)?r[o]={...i,...s}:r[o]=s}return r}var _I,Za,D_=O(()=>{gs();yo();r_();cf();_I=6e4,Za=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(ha,r=>{this._oncancel(r)}),this.setNotificationHandler(ga,r=>{this._onprogress(r)}),this.setRequestHandler(ma,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ya,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new K(Y.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(wa,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),a.type==="response")u(c);else{let d=c,b=new K(d.error.code,d.error.message,d.error.data);u(b)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${l}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new K(Y.InvalidParams,`Task not found: ${s}`);if(!Br(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Br(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Fr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(_a,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new K(Y.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(xa,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new K(Y.InvalidParams,`Task not found: ${r.params.taskId}`);if(Br(o.status))throw new K(Y.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new K(Y.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof K?o:new K(Y.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),K.fromError(Y.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),_s(s)||Vw(s)?this._onresponse(s):dp(s)?this._onrequest(s,i):Bw(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=K.fromError(Y.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[Fr]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:Y.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(u).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=Zw(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,l={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(u,d)},sendRequest:async(u,d,b)=>{if(i.signal.aborted)throw new K(Y.ConnectionClosed,"Request was cancelled");let m={...b,relatedRequestId:e.id};s&&!m.relatedTask&&(m.relatedTask={taskId:s});let f=m.relatedTask?.taskId??s;return f&&c&&await c.updateTaskStatus(f,"input_required"),await this.request(u,d,m)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async u=>{if(i.signal.aborted)return;let d={result:u,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async u=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:Y.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),_s(e))n(e);else{let i=new K(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(_s(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),_s(e))o(e);else{let i=K.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof K?i:new K(Y.InternalError,String(i))}}return}let s;try{let i=await this.request(e,fo,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new K(Y.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Br(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new K(Y.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new K(Y.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof K?i:new K(Y.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let d=R=>{u(R)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(R){d(R);return}n?.signal?.throwIfAborted();let b=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:b};n?.onprogress&&(this._progressHandlers.set(b,n.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:b}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Fr]:c}});let f=R=>{this._responseHandlers.delete(b),this._progressHandlers.delete(b),this._cleanupTimeout(b),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:b,reason:String(R)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(V=>this._onerror(new Error(`Failed to send cancellation: ${V}`)));let z=R instanceof K?R:new K(Y.RequestTimeout,String(R));u(z)};this._responseHandlers.set(b,R=>{if(!n?.signal?.aborted){if(R instanceof Error)return u(R);try{let z=Zr(r,R.result);z.success?l(z.data):u(z.error)}catch(z){u(z)}}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});let y=n?.timeout??_I,v=()=>f(K.fromError(Y.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(b,y,n?.maxTotalTimeout,v,n?.resetTimeoutOnProgress??!1);let E=c?.taskId;if(E){let R=z=>{let V=this._responseHandlers.get(b);V?V(z):this._onerror(new Error(`Response handler missing for side-channeled request ${b}`))};this._requestResolvers.set(b,R),this._enqueueTaskMessage(E,{type:"request",message:m,timestamp:Date.now()}).catch(z=>{this._cleanupTimeout(b),u(z)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(R=>{this._cleanupTimeout(b),u(R)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},ba,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},va,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Ww,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Fr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Fr]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Fr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=sf(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=af(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=sf(e);this._notificationHandlers.set(n,o=>{let s=af(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&dp(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new K(Y.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new K(Y.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new K(Y.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new K(Y.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=Ss.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Br(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new K(Y.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Br(a.status))throw new K(Y.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let l=Ss.parse({method:"notifications/tasks/status",params:c});await this.notification(l),Br(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var Os=Z(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.regexpCode=Ee.getEsmExportName=Ee.getProperty=Ee.safeStringify=Ee.stringify=Ee.strConcat=Ee.addCodeArg=Ee.str=Ee._=Ee.nil=Ee._Code=Ee.Name=Ee.IDENTIFIER=Ee._CodeOrName=void 0;var As=class{};Ee._CodeOrName=As;Ee.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Pn=class extends As{constructor(e){if(super(),!Ee.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};Ee.Name=Pn;var Ut=class extends As{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(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Pn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Ee._Code=Ut;Ee.nil=new Ut("");function U_(t,...e){let r=[t[0]],n=0;for(;n<e.length;)uf(r,e[n]),r.push(t[++n]);return new Ut(r)}Ee._=U_;var lf=new Ut("+");function Z_(t,...e){let r=[Is(t[0])],n=0;for(;n<e.length;)r.push(lf),uf(r,e[n]),r.push(lf,Is(t[++n]));return vI(r),new Ut(r)}Ee.str=Z_;function uf(t,e){e instanceof Ut?t.push(...e._items):e instanceof Pn?t.push(e):t.push($I(e))}Ee.addCodeArg=uf;function vI(t){let e=1;for(;e<t.length-1;){if(t[e]===lf){let r=xI(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function xI(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Pn||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Pn))return`"${t}${e.slice(1)}`}function kI(t,e){return e.emptyStr()?t:t.emptyStr()?e:Z_`${t}${e}`}Ee.strConcat=kI;function $I(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Is(Array.isArray(t)?t.join(","):t)}function SI(t){return new Ut(Is(t))}Ee.stringify=SI;function Is(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Ee.safeStringify=Is;function TI(t){return typeof t=="string"&&Ee.IDENTIFIER.test(t)?new Ut(`.${t}`):U_`[${t}]`}Ee.getProperty=TI;function EI(t){if(typeof t=="string"&&Ee.IDENTIFIER.test(t))return new Ut(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Ee.getEsmExportName=EI;function RI(t){return new Ut(t.toString())}Ee.regexpCode=RI});var ff=Z(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.ValueScope=xt.ValueScopeName=xt.Scope=xt.varKinds=xt.UsedValueState=void 0;var vt=Os(),df=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},qa;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(qa||(xt.UsedValueState=qa={}));xt.varKinds={const:new vt.Name("const"),let:new vt.Name("let"),var:new vt.Name("var")};var Fa=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof vt.Name?e:this.name(e)}name(e){return new vt.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};xt.Scope=Fa;var Ba=class extends vt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,vt._)`.${new vt.Name(r)}[${n}]`}};xt.ValueScopeName=Ba;var PI=(0,vt._)`\n`,pf=class extends Fa{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?PI:vt.nil}}get(){return this._scope}name(e){return new Ba(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let u=a.get(i);if(u)return u}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),l=c.length;return c[l]=r.ref,o.setValue(r,{property:s,itemIndex:l}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,vt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=vt.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,qa.Started);let u=r(l);if(u){let d=this.opts.es5?xt.varKinds.var:xt.varKinds.const;s=(0,vt._)`${s}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))s=(0,vt._)`${s}${u}${this.opts._n}`;else throw new df(l);c.set(l,qa.Completed)})}return s}};xt.ValueScope=pf});var ue=Z(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.or=de.and=de.not=de.CodeGen=de.operators=de.varKinds=de.ValueScopeName=de.ValueScope=de.Scope=de.Name=de.regexpCode=de.stringify=de.getProperty=de.nil=de.strConcat=de.str=de._=void 0;var xe=Os(),Yt=ff(),Hr=Os();Object.defineProperty(de,"_",{enumerable:!0,get:function(){return Hr._}});Object.defineProperty(de,"str",{enumerable:!0,get:function(){return Hr.str}});Object.defineProperty(de,"strConcat",{enumerable:!0,get:function(){return Hr.strConcat}});Object.defineProperty(de,"nil",{enumerable:!0,get:function(){return Hr.nil}});Object.defineProperty(de,"getProperty",{enumerable:!0,get:function(){return Hr.getProperty}});Object.defineProperty(de,"stringify",{enumerable:!0,get:function(){return Hr.stringify}});Object.defineProperty(de,"regexpCode",{enumerable:!0,get:function(){return Hr.regexpCode}});Object.defineProperty(de,"Name",{enumerable:!0,get:function(){return Hr.Name}});var Wa=ff();Object.defineProperty(de,"Scope",{enumerable:!0,get:function(){return Wa.Scope}});Object.defineProperty(de,"ValueScope",{enumerable:!0,get:function(){return Wa.ValueScope}});Object.defineProperty(de,"ValueScopeName",{enumerable:!0,get:function(){return Wa.ValueScopeName}});Object.defineProperty(de,"varKinds",{enumerable:!0,get:function(){return Wa.varKinds}});de.operators={GT:new xe._Code(">"),GTE:new xe._Code(">="),LT:new xe._Code("<"),LTE:new xe._Code("<="),EQ:new xe._Code("==="),NEQ:new xe._Code("!=="),NOT:new xe._Code("!"),OR:new xe._Code("||"),AND:new xe._Code("&&"),ADD:new xe._Code("+")};var $r=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},hf=class extends $r{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Yt.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=wo(this.rhs,e,r)),this}get names(){return this.rhs instanceof xe._CodeOrName?this.rhs.names:{}}},Va=class extends $r{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof xe.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=wo(this.rhs,e,r),this}get names(){let e=this.lhs instanceof xe.Name?{}:{...this.lhs.names};return Ka(e,this.rhs)}},mf=class extends Va{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},gf=class extends $r{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},yf=class extends $r{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},bf=class extends $r{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},wf=class extends $r{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=wo(this.code,e,r),this}get names(){return this.code instanceof xe._CodeOrName?this.code.names:{}}},Cs=class extends $r{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(AI(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>On(e,r.names),{})}},Sr=class extends Cs{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},_f=class extends Cs{},bo=class extends Sr{};bo.kind="else";var An=class t extends Sr{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new bo(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(q_(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=wo(this.condition,e,r),this}get names(){let e=super.names;return Ka(e,this.condition),this.else&&On(e,this.else.names),e}};An.kind="if";var In=class extends Sr{};In.kind="for";var vf=class extends In{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=wo(this.iteration,e,r),this}get names(){return On(super.names,this.iteration.names)}},xf=class extends In{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?Yt.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=Ka(super.names,this.from);return Ka(e,this.to)}},Ha=class extends In{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=wo(this.iterable,e,r),this}get names(){return On(super.names,this.iterable.names)}},zs=class extends Sr{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};zs.kind="func";var Ns=class extends Cs{render(e){return"return "+super.render(e)}};Ns.kind="return";var kf=class extends Sr{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&On(e,this.catch.names),this.finally&&On(e,this.finally.names),e}},js=class extends Sr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};js.kind="catch";var Ls=class extends Sr{render(e){return"finally"+super.render(e)}};Ls.kind="finally";var $f=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
986
- `:""},this._extScope=e,this._scope=new Yt.Scope({parent:e}),this._nodes=[new _f]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new hf(e,s,n)),s}const(e,r,n){return this._def(Yt.varKinds.const,e,r,n)}let(e,r,n){return this._def(Yt.varKinds.let,e,r,n)}var(e,r,n){return this._def(Yt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Va(e,r,n))}add(e,r){return this._leafNode(new mf(e,de.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==xe.nil&&this._leafNode(new wf(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,xe.addCodeArg)(r,o));return r.push("}"),new xe._Code(r)}if(e,r,n){if(this._blockNode(new An(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new An(e))}else(){return this._elseNode(new bo)}endIf(){return this._endBlockNode(An,bo)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new vf(e),r)}forRange(e,r,n,o,s=this.opts.es5?Yt.varKinds.var:Yt.varKinds.let){let i=this._scope.toName(e);return this._for(new xf(s,i,r,n),()=>o(i))}forOf(e,r,n,o=Yt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof xe.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,xe._)`${i}.length`,a=>{this.var(s,(0,xe._)`${i}[${a}]`),n(s)})}return this._for(new Ha("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?Yt.varKinds.var:Yt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,xe._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Ha("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(In)}label(e){return this._leafNode(new gf(e))}break(e){return this._leafNode(new yf(e))}return(e){let r=new Ns;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Ns)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new kf;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new js(s),r(s)}return n&&(this._currNode=o.finally=new Ls,this.code(n)),this._endBlockNode(js,Ls)}throw(e){return this._leafNode(new bf(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=xe.nil,n,o){return this._blockNode(new zs(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(zs)}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,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof An))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};de.CodeGen=$f;function On(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Ka(t,e){return e instanceof xe._CodeOrName?On(t,e.names):t}function wo(t,e,r){if(t instanceof xe.Name)return n(t);if(!o(t))return t;return new xe._Code(t._items.reduce((s,i)=>(i instanceof xe.Name&&(i=n(i)),i instanceof xe._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof xe._Code&&s._items.some(i=>i instanceof xe.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function AI(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function q_(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,xe._)`!${Sf(t)}`}de.not=q_;var II=F_(de.operators.AND);function OI(...t){return t.reduce(II)}de.and=OI;var CI=F_(de.operators.OR);function zI(...t){return t.reduce(CI)}de.or=zI;function F_(t){return(e,r)=>e===xe.nil?r:r===xe.nil?e:(0,xe._)`${Sf(e)} ${t} ${Sf(r)}`}function Sf(t){return t instanceof xe.Name?t:(0,xe._)`(${t})`}});var $e=Z(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.checkStrictMode=he.getErrorPath=he.Type=he.useFunc=he.setEvaluated=he.evaluatedPropsToName=he.mergeEvaluated=he.eachItem=he.unescapeJsonPointer=he.escapeJsonPointer=he.escapeFragment=he.unescapeFragment=he.schemaRefOrVal=he.schemaHasRulesButRef=he.schemaHasRules=he.checkUnknownRules=he.alwaysValidSchema=he.toHash=void 0;var Ie=ue(),NI=Os();function jI(t){let e={};for(let r of t)e[r]=!0;return e}he.toHash=jI;function LI(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(H_(t,e),!K_(e,t.self.RULES.all))}he.alwaysValidSchema=LI;function H_(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||J_(t,`unknown keyword: "${s}"`)}he.checkUnknownRules=H_;function K_(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}he.schemaHasRules=K_;function MI(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}he.schemaHasRulesButRef=MI;function DI({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Ie._)`${r}`}return(0,Ie._)`${t}${e}${(0,Ie.getProperty)(n)}`}he.schemaRefOrVal=DI;function UI(t){return W_(decodeURIComponent(t))}he.unescapeFragment=UI;function ZI(t){return encodeURIComponent(Ef(t))}he.escapeFragment=ZI;function Ef(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}he.escapeJsonPointer=Ef;function W_(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}he.unescapeJsonPointer=W_;function qI(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}he.eachItem=qI;function B_({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof Ie.Name?(s instanceof Ie.Name?t(o,s,i):e(o,s,i),i):s instanceof Ie.Name?(e(o,i,s),s):r(s,i);return a===Ie.Name&&!(c instanceof Ie.Name)?n(o,c):c}}he.mergeEvaluated={props:B_({mergeNames:(t,e,r)=>t.if((0,Ie._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Ie._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Ie._)`${r} || {}`).code((0,Ie._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Ie._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Ie._)`${r} || {}`),Rf(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:G_}),items:B_({mergeNames:(t,e,r)=>t.if((0,Ie._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Ie._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Ie._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Ie._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function G_(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Ie._)`{}`);return e!==void 0&&Rf(t,r,e),r}he.evaluatedPropsToName=G_;function Rf(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Ie._)`${e}${(0,Ie.getProperty)(n)}`,!0))}he.setEvaluated=Rf;var V_={};function FI(t,e){return t.scopeValue("func",{ref:e,code:V_[e.code]||(V_[e.code]=new NI._Code(e.code))})}he.useFunc=FI;var Tf;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Tf||(he.Type=Tf={}));function BI(t,e,r){if(t instanceof Ie.Name){let n=e===Tf.Num;return r?n?(0,Ie._)`"[" + ${t} + "]"`:(0,Ie._)`"['" + ${t} + "']"`:n?(0,Ie._)`"/" + ${t}`:(0,Ie._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Ie.getProperty)(t).toString():"/"+Ef(t)}he.getErrorPath=BI;function J_(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}he.checkStrictMode=J_});var Tr=Z(Pf=>{"use strict";Object.defineProperty(Pf,"__esModule",{value:!0});var it=ue(),VI={data:new it.Name("data"),valCxt:new it.Name("valCxt"),instancePath:new it.Name("instancePath"),parentData:new it.Name("parentData"),parentDataProperty:new it.Name("parentDataProperty"),rootData:new it.Name("rootData"),dynamicAnchors:new it.Name("dynamicAnchors"),vErrors:new it.Name("vErrors"),errors:new it.Name("errors"),this:new it.Name("this"),self:new it.Name("self"),scope:new it.Name("scope"),json:new it.Name("json"),jsonPos:new it.Name("jsonPos"),jsonLen:new it.Name("jsonLen"),jsonPart:new it.Name("jsonPart")};Pf.default=VI});var Ms=Z(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.extendErrors=at.resetErrorsCount=at.reportExtraError=at.reportError=at.keyword$DataError=at.keywordError=void 0;var Se=ue(),Ga=$e(),ft=Tr();at.keywordError={message:({keyword:t})=>(0,Se.str)`must pass "${t}" keyword validation`};at.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,Se.str)`"${t}" keyword must be ${e} ($data)`:(0,Se.str)`"${t}" keyword is invalid ($data)`};function HI(t,e=at.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Q_(t,e,r);n??(i||a)?Y_(s,c):X_(o,(0,Se._)`[${c}]`)}at.reportError=HI;function KI(t,e=at.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Q_(t,e,r);Y_(o,a),s||i||X_(n,ft.default.vErrors)}at.reportExtraError=KI;function WI(t,e){t.assign(ft.default.errors,e),t.if((0,Se._)`${ft.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,Se._)`${ft.default.vErrors}.length`,e),()=>t.assign(ft.default.vErrors,null)))}at.resetErrorsCount=WI;function GI({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,ft.default.errors,a=>{t.const(i,(0,Se._)`${ft.default.vErrors}[${a}]`),t.if((0,Se._)`${i}.instancePath === undefined`,()=>t.assign((0,Se._)`${i}.instancePath`,(0,Se.strConcat)(ft.default.instancePath,s.errorPath))),t.assign((0,Se._)`${i}.schemaPath`,(0,Se.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,Se._)`${i}.schema`,r),t.assign((0,Se._)`${i}.data`,n))})}at.extendErrors=GI;function Y_(t,e){let r=t.const("err",e);t.if((0,Se._)`${ft.default.vErrors} === null`,()=>t.assign(ft.default.vErrors,(0,Se._)`[${r}]`),(0,Se._)`${ft.default.vErrors}.push(${r})`),t.code((0,Se._)`${ft.default.errors}++`)}function X_(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,Se._)`new ${t.ValidationError}(${e})`):(r.assign((0,Se._)`${n}.errors`,e),r.return(!1))}var Cn={keyword:new Se.Name("keyword"),schemaPath:new Se.Name("schemaPath"),params:new Se.Name("params"),propertyName:new Se.Name("propertyName"),message:new Se.Name("message"),schema:new Se.Name("schema"),parentSchema:new Se.Name("parentSchema")};function Q_(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,Se._)`{}`:JI(t,e,r)}function JI(t,e,r={}){let{gen:n,it:o}=t,s=[YI(o,r),XI(t,r)];return QI(t,e,s),n.object(...s)}function YI({errorPath:t},{instancePath:e}){let r=e?(0,Se.str)`${t}${(0,Ga.getErrorPath)(e,Ga.Type.Str)}`:t;return[ft.default.instancePath,(0,Se.strConcat)(ft.default.instancePath,r)]}function XI({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,Se.str)`${e}/${t}`;return r&&(o=(0,Se.str)`${o}${(0,Ga.getErrorPath)(r,Ga.Type.Str)}`),[Cn.schemaPath,o]}function QI(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;n.push([Cn.keyword,o],[Cn.params,typeof e=="function"?e(t):e||(0,Se._)`{}`]),c.messages&&n.push([Cn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Cn.schema,i],[Cn.parentSchema,(0,Se._)`${u}${d}`],[ft.default.data,s]),l&&n.push([Cn.propertyName,l])}});var tv=Z(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});_o.boolOrEmptySchema=_o.topBoolOrEmptySchema=void 0;var eO=Ms(),tO=ue(),rO=Tr(),nO={message:"boolean schema is false"};function oO(t){let{gen:e,schema:r,validateName:n}=t;r===!1?ev(t,!1):typeof r=="object"&&r.$async===!0?e.return(rO.default.data):(e.assign((0,tO._)`${n}.errors`,null),e.return(!0))}_o.topBoolOrEmptySchema=oO;function sO(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),ev(t)):r.var(e,!0)}_o.boolOrEmptySchema=sO;function ev(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,eO.reportError)(o,nO,void 0,e)}});var Af=Z(vo=>{"use strict";Object.defineProperty(vo,"__esModule",{value:!0});vo.getRules=vo.isJSONType=void 0;var iO=["string","number","integer","boolean","null","object","array"],aO=new Set(iO);function cO(t){return typeof t=="string"&&aO.has(t)}vo.isJSONType=cO;function lO(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}vo.getRules=lO});var If=Z(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.shouldUseRule=Kr.shouldUseGroup=Kr.schemaHasRulesForType=void 0;function uO({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&rv(t,n)}Kr.schemaHasRulesForType=uO;function rv(t,e){return e.rules.some(r=>nv(t,r))}Kr.shouldUseGroup=rv;function nv(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}Kr.shouldUseRule=nv});var Ds=Z(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.reportTypeError=ct.checkDataTypes=ct.checkDataType=ct.coerceAndCheckDataType=ct.getJSONTypes=ct.getSchemaTypes=ct.DataType=void 0;var dO=Af(),pO=If(),fO=Ms(),ae=ue(),ov=$e(),xo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(xo||(ct.DataType=xo={}));function hO(t){let e=sv(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}ct.getSchemaTypes=hO;function sv(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(dO.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ct.getJSONTypes=sv;function mO(t,e){let{gen:r,data:n,opts:o}=t,s=gO(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,pO.schemaHasRulesForType)(t,e[0]));if(i){let a=Cf(e,n,o.strictNumbers,xo.Wrong);r.if(a,()=>{s.length?yO(t,e,s):zf(t)})}return i}ct.coerceAndCheckDataType=mO;var iv=new Set(["string","number","integer","boolean","null"]);function gO(t,e){return e?t.filter(r=>iv.has(r)||e==="array"&&r==="array"):[]}function yO(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,ae._)`typeof ${o}`),a=n.let("coerced",(0,ae._)`undefined`);s.coerceTypes==="array"&&n.if((0,ae._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,ae._)`${o}[0]`).assign(i,(0,ae._)`typeof ${o}`).if(Cf(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,ae._)`${a} !== undefined`);for(let l of r)(iv.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),zf(t),n.endIf(),n.if((0,ae._)`${a} !== undefined`,()=>{n.assign(o,a),bO(t,a)});function c(l){switch(l){case"string":n.elseIf((0,ae._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,ae._)`"" + ${o}`).elseIf((0,ae._)`${o} === null`).assign(a,(0,ae._)`""`);return;case"number":n.elseIf((0,ae._)`${i} == "boolean" || ${o} === null
987
- || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,ae._)`+${o}`);return;case"integer":n.elseIf((0,ae._)`${i} === "boolean" || ${o} === null
988
- || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,ae._)`+${o}`);return;case"boolean":n.elseIf((0,ae._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,ae._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,ae._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,ae._)`${i} === "string" || ${i} === "number"
989
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,ae._)`[${o}]`)}}}function bO({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,ae._)`${e} !== undefined`,()=>t.assign((0,ae._)`${e}[${r}]`,n))}function Of(t,e,r,n=xo.Correct){let o=n===xo.Correct?ae.operators.EQ:ae.operators.NEQ,s;switch(t){case"null":return(0,ae._)`${e} ${o} null`;case"array":s=(0,ae._)`Array.isArray(${e})`;break;case"object":s=(0,ae._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,ae._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,ae._)`typeof ${e} ${o} ${t}`}return n===xo.Correct?s:(0,ae.not)(s);function i(a=ae.nil){return(0,ae.and)((0,ae._)`typeof ${e} == "number"`,a,r?(0,ae._)`isFinite(${e})`:ae.nil)}}ct.checkDataType=Of;function Cf(t,e,r,n){if(t.length===1)return Of(t[0],e,r,n);let o,s=(0,ov.toHash)(t);if(s.array&&s.object){let i=(0,ae._)`typeof ${e} != "object"`;o=s.null?i:(0,ae._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=ae.nil;s.number&&delete s.integer;for(let i in s)o=(0,ae.and)(o,Of(i,e,r,n));return o}ct.checkDataTypes=Cf;var wO={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ae._)`{type: ${t}}`:(0,ae._)`{type: ${e}}`};function zf(t){let e=_O(t);(0,fO.reportError)(e,wO)}ct.reportTypeError=zf;function _O(t){let{gen:e,data:r,schema:n}=t,o=(0,ov.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var cv=Z(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});Ja.assignDefaults=void 0;var ko=ue(),vO=$e();function xO(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)av(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>av(t,s,o.default))}Ja.assignDefaults=xO;function av(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,ko._)`${s}${(0,ko.getProperty)(e)}`;if(o){(0,vO.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,ko._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,ko._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,ko._)`${a} = ${(0,ko.stringify)(r)}`)}});var Zt=Z(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.validateUnion=Ae.validateArray=Ae.usePattern=Ae.callValidateCode=Ae.schemaProperties=Ae.allSchemaProperties=Ae.noPropertyInData=Ae.propertyInData=Ae.isOwnProperty=Ae.hasPropFunc=Ae.reportMissingProp=Ae.checkMissingProp=Ae.checkReportMissingProp=void 0;var je=ue(),Nf=$e(),Wr=Tr(),kO=$e();function $O(t,e){let{gen:r,data:n,it:o}=t;r.if(Lf(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,je._)`${e}`},!0),t.error()})}Ae.checkReportMissingProp=$O;function SO({gen:t,data:e,it:{opts:r}},n,o){return(0,je.or)(...n.map(s=>(0,je.and)(Lf(t,e,s,r.ownProperties),(0,je._)`${o} = ${s}`)))}Ae.checkMissingProp=SO;function TO(t,e){t.setParams({missingProperty:e},!0),t.error()}Ae.reportMissingProp=TO;function lv(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,je._)`Object.prototype.hasOwnProperty`})}Ae.hasPropFunc=lv;function jf(t,e,r){return(0,je._)`${lv(t)}.call(${e}, ${r})`}Ae.isOwnProperty=jf;function EO(t,e,r,n){let o=(0,je._)`${e}${(0,je.getProperty)(r)} !== undefined`;return n?(0,je._)`${o} && ${jf(t,e,r)}`:o}Ae.propertyInData=EO;function Lf(t,e,r,n){let o=(0,je._)`${e}${(0,je.getProperty)(r)} === undefined`;return n?(0,je.or)(o,(0,je.not)(jf(t,e,r))):o}Ae.noPropertyInData=Lf;function uv(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Ae.allSchemaProperties=uv;function RO(t,e){return uv(e).filter(r=>!(0,Nf.alwaysValidSchema)(t,e[r]))}Ae.schemaProperties=RO;function PO({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,l){let u=l?(0,je._)`${t}, ${e}, ${n}${o}`:e,d=[[Wr.default.instancePath,(0,je.strConcat)(Wr.default.instancePath,s)],[Wr.default.parentData,i.parentData],[Wr.default.parentDataProperty,i.parentDataProperty],[Wr.default.rootData,Wr.default.rootData]];i.opts.dynamicRef&&d.push([Wr.default.dynamicAnchors,Wr.default.dynamicAnchors]);let b=(0,je._)`${u}, ${r.object(...d)}`;return c!==je.nil?(0,je._)`${a}.call(${c}, ${b})`:(0,je._)`${a}(${b})`}Ae.callValidateCode=PO;var AO=(0,je._)`new RegExp`;function IO({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,je._)`${o.code==="new RegExp"?AO:(0,kO.useFunc)(t,o)}(${r}, ${n})`})}Ae.usePattern=IO;function OO(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,je._)`${r}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:n,dataProp:l,dataPropType:Nf.Type.Num},s),e.if((0,je.not)(s),a)})}}Ae.validateArray=OO;function CO(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Nf.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,l)=>{let u=t.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);e.assign(i,(0,je._)`${i} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,je.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Ae.validateUnion=CO});var fv=Z(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.validateKeywordUsage=ur.validSchemaType=ur.funcKeywordCode=ur.macroKeywordCode=void 0;var ht=ue(),zn=Tr(),zO=Zt(),NO=Ms();function jO(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=pv(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=r.name("valid");t.subschema({schema:a,schemaPath:ht.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}ur.macroKeywordCode=jO;function LO(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;DO(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,u=pv(n,o,l),d=n.let("valid");t.block$data(d,b),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function b(){if(e.errors===!1)y(),e.modifying&&dv(t),v(()=>t.error());else{let E=e.async?m():f();e.modifying&&dv(t),v(()=>MO(t,E))}}function m(){let E=n.let("ruleErrs",null);return n.try(()=>y((0,ht._)`await `),R=>n.assign(d,!1).if((0,ht._)`${R} instanceof ${c.ValidationError}`,()=>n.assign(E,(0,ht._)`${R}.errors`),()=>n.throw(R))),E}function f(){let E=(0,ht._)`${u}.errors`;return n.assign(E,null),y(ht.nil),E}function y(E=e.async?(0,ht._)`await `:ht.nil){let R=c.opts.passContext?zn.default.this:zn.default.self,z=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,ht._)`${E}${(0,zO.callValidateCode)(t,u,R,z)}`,e.modifying)}function v(E){var R;n.if((0,ht.not)((R=e.valid)!==null&&R!==void 0?R:d),E)}}ur.funcKeywordCode=LO;function dv(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,ht._)`${n.parentData}[${n.parentDataProperty}]`))}function MO(t,e){let{gen:r}=t;r.if((0,ht._)`Array.isArray(${e})`,()=>{r.assign(zn.default.vErrors,(0,ht._)`${zn.default.vErrors} === null ? ${e} : ${zn.default.vErrors}.concat(${e})`).assign(zn.default.errors,(0,ht._)`${zn.default.vErrors}.length`),(0,NO.extendErrors)(t)},()=>t.error())}function DO({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function pv(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,ht.stringify)(r)})}function UO(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}ur.validSchemaType=UO;function ZO({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}ur.validateKeywordUsage=ZO});var mv=Z(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.extendSubschemaMode=Gr.extendSubschemaData=Gr.getSubschema=void 0;var dr=ue(),hv=$e();function qO(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,dr._)`${t.schemaPath}${(0,dr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,dr._)`${t.schemaPath}${(0,dr.getProperty)(e)}${(0,dr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,hv.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Gr.getSubschema=qO;function FO(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:l,dataPathArr:u,opts:d}=e,b=a.let("data",(0,dr._)`${e.data}${(0,dr.getProperty)(r)}`,!0);c(b),t.errorPath=(0,dr.str)`${l}${(0,hv.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,dr._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(o!==void 0){let l=o instanceof dr.Name?o:a.let("data",o,!0);c(l),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(l){t.data=l,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,l]}}Gr.extendSubschemaData=FO;function BO(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}Gr.extendSubschemaMode=BO});var Mf=Z((uB,gv)=>{"use strict";gv.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var bv=Z((dB,yv)=>{"use strict";var Jr=yv.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};Ya(e,n,o,t,"",t)};Jr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Jr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Jr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Jr.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 Ya(t,e,r,n,o,s,i,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,l);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in Jr.arrayKeywords)for(var b=0;b<d.length;b++)Ya(t,e,r,d[b],o+"/"+u+"/"+b,s,o,u,n,b)}else if(u in Jr.propsKeywords){if(d&&typeof d=="object")for(var m in d)Ya(t,e,r,d[m],o+"/"+u+"/"+VO(m),s,o,u,n,m)}else(u in Jr.keywords||t.allKeys&&!(u in Jr.skipKeywords))&&Ya(t,e,r,d,o+"/"+u,s,o,u,n)}r(n,o,s,i,a,c,l)}}function VO(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Us=Z(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.getSchemaRefs=kt.resolveUrl=kt.normalizeId=kt._getFullPath=kt.getFullPath=kt.inlineRef=void 0;var HO=$e(),KO=Mf(),WO=bv(),GO=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function JO(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Df(t):e?wv(t)<=e:!1}kt.inlineRef=JO;var YO=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Df(t){for(let e in t){if(YO.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Df)||typeof r=="object"&&Df(r))return!0}return!1}function wv(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!GO.has(r)&&(typeof t[r]=="object"&&(0,HO.eachItem)(t[r],n=>e+=wv(n)),e===1/0))return 1/0}return e}function _v(t,e="",r){r!==!1&&(e=$o(e));let n=t.parse(e);return vv(t,n)}kt.getFullPath=_v;function vv(t,e){return t.serialize(e).split("#")[0]+"#"}kt._getFullPath=vv;var XO=/#\/?$/;function $o(t){return t?t.replace(XO,""):""}kt.normalizeId=$o;function QO(t,e,r){return r=$o(r),t.resolve(e,r)}kt.resolveUrl=QO;var eC=/^[a-z_][-a-z0-9._]*$/i;function tC(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=$o(t[r]||e),s={"":o},i=_v(n,o,!1),a={},c=new Set;return WO(t,{allKeys:!0},(d,b,m,f)=>{if(f===void 0)return;let y=i+b,v=s[f];typeof d[r]=="string"&&(v=E.call(this,d[r])),R.call(this,d.$anchor),R.call(this,d.$dynamicAnchor),s[b]=v;function E(z){let V=this.opts.uriResolver.resolve;if(z=$o(v?V(v,z):z),c.has(z))throw u(z);c.add(z);let J=this.refs[z];return typeof J=="string"&&(J=this.refs[J]),typeof J=="object"?l(d,J.schema,z):z!==$o(y)&&(z[0]==="#"?(l(d,a[z],z),a[z]=d):this.refs[z]=y),z}function R(z){if(typeof z=="string"){if(!eC.test(z))throw new Error(`invalid anchor "${z}"`);E.call(this,`#${z}`)}}}),a;function l(d,b,m){if(b!==void 0&&!KO(d,b))throw u(m)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}kt.getSchemaRefs=tC});var Fs=Z(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.getData=Yr.KeywordCxt=Yr.validateFunctionCode=void 0;var Tv=tv(),xv=Ds(),Zf=If(),Xa=Ds(),rC=cv(),qs=fv(),Uf=mv(),G=ue(),re=Tr(),nC=Us(),Er=$e(),Zs=Ms();function oC(t){if(Pv(t)&&(Av(t),Rv(t))){aC(t);return}Ev(t,()=>(0,Tv.topBoolOrEmptySchema)(t))}Yr.validateFunctionCode=oC;function Ev({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,G._)`${re.default.data}, ${re.default.valCxt}`,n.$async,()=>{t.code((0,G._)`"use strict"; ${kv(r,o)}`),iC(t,o),t.code(s)}):t.func(e,(0,G._)`${re.default.data}, ${sC(o)}`,n.$async,()=>t.code(kv(r,o)).code(s))}function sC(t){return(0,G._)`{${re.default.instancePath}="", ${re.default.parentData}, ${re.default.parentDataProperty}, ${re.default.rootData}=${re.default.data}${t.dynamicRef?(0,G._)`, ${re.default.dynamicAnchors}={}`:G.nil}}={}`}function iC(t,e){t.if(re.default.valCxt,()=>{t.var(re.default.instancePath,(0,G._)`${re.default.valCxt}.${re.default.instancePath}`),t.var(re.default.parentData,(0,G._)`${re.default.valCxt}.${re.default.parentData}`),t.var(re.default.parentDataProperty,(0,G._)`${re.default.valCxt}.${re.default.parentDataProperty}`),t.var(re.default.rootData,(0,G._)`${re.default.valCxt}.${re.default.rootData}`),e.dynamicRef&&t.var(re.default.dynamicAnchors,(0,G._)`${re.default.valCxt}.${re.default.dynamicAnchors}`)},()=>{t.var(re.default.instancePath,(0,G._)`""`),t.var(re.default.parentData,(0,G._)`undefined`),t.var(re.default.parentDataProperty,(0,G._)`undefined`),t.var(re.default.rootData,re.default.data),e.dynamicRef&&t.var(re.default.dynamicAnchors,(0,G._)`{}`)})}function aC(t){let{schema:e,opts:r,gen:n}=t;Ev(t,()=>{r.$comment&&e.$comment&&Ov(t),pC(t),n.let(re.default.vErrors,null),n.let(re.default.errors,0),r.unevaluated&&cC(t),Iv(t),mC(t)})}function cC(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,G._)`${r}.evaluated`),e.if((0,G._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,G._)`${t.evaluated}.props`,(0,G._)`undefined`)),e.if((0,G._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,G._)`${t.evaluated}.items`,(0,G._)`undefined`))}function kv(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,G._)`/*# sourceURL=${r} */`:G.nil}function lC(t,e){if(Pv(t)&&(Av(t),Rv(t))){uC(t,e);return}(0,Tv.boolOrEmptySchema)(t,e)}function Rv({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function Pv(t){return typeof t.schema!="boolean"}function uC(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Ov(t),fC(t),hC(t);let s=n.const("_errs",re.default.errors);Iv(t,s),n.var(e,(0,G._)`${s} === ${re.default.errors}`)}function Av(t){(0,Er.checkUnknownRules)(t),dC(t)}function Iv(t,e){if(t.opts.jtd)return $v(t,[],!1,e);let r=(0,xv.getSchemaTypes)(t.schema),n=(0,xv.coerceAndCheckDataType)(t,r);$v(t,r,!n,e)}function dC(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Er.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function pC(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Er.checkStrictMode)(t,"default is ignored in the schema root")}function fC(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,nC.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function hC(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Ov({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,G._)`${re.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,G.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,G._)`${re.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function mC(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,G._)`${re.default.errors} === 0`,()=>e.return(re.default.data),()=>e.throw((0,G._)`new ${o}(${re.default.vErrors})`)):(e.assign((0,G._)`${n}.errors`,re.default.vErrors),s.unevaluated&&gC(t),e.return((0,G._)`${re.default.errors} === 0`))}function gC({gen:t,evaluated:e,props:r,items:n}){r instanceof G.Name&&t.assign((0,G._)`${e}.props`,r),n instanceof G.Name&&t.assign((0,G._)`${e}.items`,n)}function $v(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:l}=t,{RULES:u}=l;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,Er.schemaHasRulesButRef)(s,u))){o.block(()=>zv(t,"$ref",u.all.$ref.definition));return}c.jtd||yC(t,e),o.block(()=>{for(let b of u.rules)d(b);d(u.post)});function d(b){(0,Zf.shouldUseGroup)(s,b)&&(b.type?(o.if((0,Xa.checkDataType)(b.type,i,c.strictNumbers)),Sv(t,b),e.length===1&&e[0]===b.type&&r&&(o.else(),(0,Xa.reportTypeError)(t)),o.endIf()):Sv(t,b),a||o.if((0,G._)`${re.default.errors} === ${n||0}`))}}function Sv(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,rC.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Zf.shouldUseRule)(n,s)&&zv(t,s.keyword,s.definition,e.type)})}function yC(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(bC(t,e),t.opts.allowUnionTypes||wC(t,e),_C(t,t.dataTypes))}function bC(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Cv(t.dataTypes,r)||qf(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),xC(t,e)}}function wC(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&qf(t,"use allowUnionTypes to allow union type keyword")}function _C(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Zf.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>vC(e,i))&&qf(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function vC(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Cv(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function xC(t,e){let r=[];for(let n of t.dataTypes)Cv(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function qf(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Er.checkStrictMode)(t,e,t.opts.strictTypes)}var Qa=class{constructor(e,r,n){if((0,qs.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Er.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",Nv(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,qs.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",re.default.errors))}result(e,r,n){this.failResult((0,G.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,G.not)(e),void 0,r)}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:r}=this;this.fail((0,G._)`${r} !== undefined && (${(0,G.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?Zs.reportExtraError:Zs.reportError)(this,this.def.error,r)}$dataError(){(0,Zs.reportError)(this,this.def.$dataError||Zs.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Zs.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=G.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=G.nil,r=G.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,G.or)((0,G._)`${o} === undefined`,r)),e!==G.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==G.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,G.or)(i(),a());function i(){if(n.length){if(!(r instanceof G.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,G._)`${(0,Xa.checkDataTypes)(c,r,s.opts.strictNumbers,Xa.DataType.Wrong)}`}return G.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,G._)`!${c}(${r})`}return G.nil}}subschema(e,r){let n=(0,Uf.getSubschema)(this.it,e);(0,Uf.extendSubschemaData)(n,this.it,e),(0,Uf.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return lC(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Er.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Er.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,G.Name)),!0}};Yr.KeywordCxt=Qa;function zv(t,e,r,n){let o=new Qa(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,qs.funcKeywordCode)(o,r):"macro"in r?(0,qs.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,qs.funcKeywordCode)(o,r)}var kC=/^\/(?:[^~]|~0|~1)*$/,$C=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Nv(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return re.default.rootData;if(t[0]==="/"){if(!kC.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=re.default.rootData}else{let l=$C.exec(t);if(!l)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+l[1];if(o=l[2],o==="#"){if(u>=e)throw new Error(c("property/index",u));return n[e-u]}if(u>e)throw new Error(c("data",u));if(s=r[e-u],!o)return s}let i=s,a=o.split("/");for(let l of a)l&&(s=(0,G._)`${s}${(0,G.getProperty)((0,Er.unescapeJsonPointer)(l))}`,i=(0,G._)`${i} && ${s}`);return i;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}Yr.getData=Nv});var ec=Z(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});var Ff=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Bf.default=Ff});var Bs=Z(Kf=>{"use strict";Object.defineProperty(Kf,"__esModule",{value:!0});var Vf=Us(),Hf=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Vf.resolveUrl)(e,r,n),this.missingSchema=(0,Vf.normalizeId)((0,Vf.getFullPath)(e,this.missingRef))}};Kf.default=Hf});var rc=Z(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.resolveSchema=qt.getCompilingSchema=qt.resolveRef=qt.compileSchema=qt.SchemaEnv=void 0;var Xt=ue(),SC=ec(),Nn=Tr(),Qt=Us(),jv=$e(),TC=Fs(),So=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,Qt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};qt.SchemaEnv=So;function Gf(t){let e=Lv.call(this,t);if(e)return e;let r=(0,Qt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Xt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:SC.default,code:(0,Xt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:Nn.default.data,parentData:Nn.default.parentData,parentDataProperty:Nn.default.parentDataProperty,dataNames:[Nn.default.data],dataPathArr:[Xt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Xt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Xt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Xt._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,TC.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let d=i.toString();u=`${i.scopeRefs(Nn.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let m=new Function(`${Nn.default.self}`,`${Nn.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:m}),m.errors=null,m.schema=t.schema,m.schemaEnv=t,t.$async&&(m.$async=!0),this.opts.code.source===!0&&(m.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:f,items:y}=l;m.evaluated={props:f instanceof Xt.Name?void 0:f,items:y instanceof Xt.Name?void 0:y,dynamicProps:f instanceof Xt.Name,dynamicItems:y instanceof Xt.Name},m.source&&(m.source.evaluated=(0,Xt.stringify)(m.evaluated))}return t.validate=m,t}catch(d){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(t)}}qt.compileSchema=Gf;function EC(t,e,r){var n;r=(0,Qt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=AC.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new So({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=RC.call(this,s)}qt.resolveRef=EC;function RC(t){return(0,Qt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Gf.call(this,t)}function Lv(t){for(let e of this._compilations)if(PC(e,t))return e}qt.getCompilingSchema=Lv;function PC(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function AC(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||tc.call(this,t,e)}function tc(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Qt._getFullPath)(this.opts.uriResolver,r),o=(0,Qt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Wf.call(this,r,t);let s=(0,Qt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=tc.call(this,t,i);return typeof a?.schema!="object"?void 0:Wf.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Gf.call(this,i),s===(0,Qt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,Qt.resolveUrl)(this.opts.uriResolver,o,l)),new So({schema:a,schemaId:c,root:t,baseId:o})}return Wf.call(this,r,i)}}qt.resolveSchema=tc;var IC=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Wf(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,jv.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!IC.has(a)&&l&&(e=(0,Qt.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,jv.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Qt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=tc.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new So({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Mv=Z((yB,OC)=>{OC.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}});var Xf=Z((bB,Bv)=>{"use strict";var CC=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Uv=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),Jf=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Zv=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),zC=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Yf(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var NC=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Dv(t){return t.length=0,!0}function jC(t,e,r){if(t.length){let n=Yf(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function LC(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=jC;for(let c=0;c<t.length;c++){let l=t[c];if(!(l==="["||l==="]"))if(l===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(l==="%"){if(!a(o,n,r))break;a=Dv}else{o.push(l);continue}}return o.length&&(a===Dv?r.zone=o.join(""):i?n.push(o.join("")):n.push(Yf(o))),r.address=n.join(""),r}function qv(t){if(MC(t,":")<2)return{host:t,isIPV6:!1};let e=LC(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function MC(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function DC(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}var UC={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},ZC=/[@/?#:]/g,qC=/[@/?#]/g;function Fv(t,e){let r=e?qC:ZC;return r.lastIndex=0,t.replace(r,n=>UC[n])}function FC(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(Jf(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Zv(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function BC(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(Jf(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Zv(s)?e+=s:e+="%"+o,r+=2;continue}}zC(t[r])?e+=t[r]:e+=escape(t[r])}return e}function VC(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(Jf(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function HC(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!Uv(r)){let n=qv(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Fv(r,!1)}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}Bv.exports={nonSimpleDomain:NC,recomposeAuthority:HC,reescapeHostDelimiters:Fv,normalizePercentEncoding:FC,normalizePathEncoding:BC,escapePreservingEscapes:VC,removeDotSegments:DC,isIPv4:Uv,isUUID:CC,normalizeIPv6:qv,stringArrayToHexStripped:Yf}});var Gv=Z((wB,Wv)=>{"use strict";var{isUUID:KC}=Xf(),WC=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,GC=["http","https","ws","wss","urn","urn:uuid"];function JC(t){return GC.indexOf(t)!==-1}function Qf(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function Vv(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Hv(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function YC(t){return t.secure=Qf(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function XC(t){if((t.port===(Qf(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function QC(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(WC);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=eh(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function ez(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=eh(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function tz(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!KC(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function rz(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Kv={scheme:"http",domainHost:!0,parse:Vv,serialize:Hv},nz={scheme:"https",domainHost:Kv.domainHost,parse:Vv,serialize:Hv},nc={scheme:"ws",domainHost:!0,parse:YC,serialize:XC},oz={scheme:"wss",domainHost:nc.domainHost,parse:nc.parse,serialize:nc.serialize},sz={scheme:"urn",parse:QC,serialize:ez,skipNormalize:!0},iz={scheme:"urn:uuid",parse:tz,serialize:rz,skipNormalize:!0},oc={http:Kv,https:nz,ws:nc,wss:oz,urn:sz,"urn:uuid":iz};Object.setPrototypeOf(oc,null);function eh(t){return t&&(oc[t]||oc[t.toLowerCase()])||void 0}Wv.exports={wsIsSecure:Qf,SCHEMES:oc,isValidSchemeName:JC,getSchemeHandler:eh}});var ex=Z((_B,ac)=>{"use strict";var{normalizeIPv6:az,removeDotSegments:Vs,recomposeAuthority:cz,normalizePercentEncoding:lz,normalizePathEncoding:uz,escapePreservingEscapes:dz,reescapeHostDelimiters:pz,isIPv4:fz,nonSimpleDomain:hz}=Xf(),{SCHEMES:mz,getSchemeHandler:Yv}=Gv();function gz(t,e){return typeof t=="string"?t=kz(t,e):typeof t=="object"&&(t=ic(jn(t,e),e)),t}function yz(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=sc(t,n),{parsed:i,malformedAuthorityOrPort:a}=sc(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let c=Xv(o,i,n,!0);return n.skipEscape=!0,jn(c,n)}function Xv(t,e,r,n){let o={};return n||(t=ic(jn(t,r),r),e=ic(jn(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Vs(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Vs(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Vs(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=Vs(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function bz(t,e,r){let n=Jv(t,r),o=Jv(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function jn(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=Yv(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=lz(r.path):(r.path=dz(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=cz(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=Vs(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var wz=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,_z=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,vz=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function xz(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function sc(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let i=t.match(_z);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(vz);if(a!==null){let l=a[1],u=l.replace(/[\t\n\r]/g,"");u.length>=2&&(u.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):l.length!==u.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let c=t.match(wz);if(c){n.scheme=c[1],n.userinfo=c[3],n.host=c[4],n.port=parseInt(c[5],10),n.path=c[6]||"",n.query=c[7],n.fragment=c[8],isNaN(n.port)&&(n.port=c[5]);let l=xz(n,c);if(l!==void 0&&(n.error=n.error||l,o=!0),n.host)if(fz(n.host)===!1){let b=az(n.host);n.host=b.host.toLowerCase(),s=b.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let u=Yv(r.scheme||n.scheme);if(!r.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(r.domainHost||u&&u.domainHost)&&s===!1&&hz(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(d){n.error=n.error||"Host's domain name can not be converted to ASCII: "+d}if((!u||u&&!u.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=pz(unescape(n.host),s))),n.path&&(n.path=uz(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}u&&u.parse&&u.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function ic(t,e){return sc(t,e).parsed}function kz(t,e){return Qv(t,e).normalized}function Qv(t,e){let{parsed:r,malformedAuthorityOrPort:n}=sc(t,e);return{normalized:n?t:jn(r,e),malformedAuthorityOrPort:n}}function Jv(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Qv(t,e);return n?void 0:r}if(typeof t=="object")return jn(t,e)}var th={SCHEMES:mz,normalize:gz,resolve:yz,resolveComponent:Xv,equal:bz,serialize:jn,parse:ic};ac.exports=th;ac.exports.default=th;ac.exports.fastUri=th});var rx=Z(rh=>{"use strict";Object.defineProperty(rh,"__esModule",{value:!0});var tx=ex();tx.code='require("ajv/dist/runtime/uri").default';rh.default=tx});var ux=Z(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.CodeGen=nt.Name=nt.nil=nt.stringify=nt.str=nt._=nt.KeywordCxt=void 0;var $z=Fs();Object.defineProperty(nt,"KeywordCxt",{enumerable:!0,get:function(){return $z.KeywordCxt}});var To=ue();Object.defineProperty(nt,"_",{enumerable:!0,get:function(){return To._}});Object.defineProperty(nt,"str",{enumerable:!0,get:function(){return To.str}});Object.defineProperty(nt,"stringify",{enumerable:!0,get:function(){return To.stringify}});Object.defineProperty(nt,"nil",{enumerable:!0,get:function(){return To.nil}});Object.defineProperty(nt,"Name",{enumerable:!0,get:function(){return To.Name}});Object.defineProperty(nt,"CodeGen",{enumerable:!0,get:function(){return To.CodeGen}});var Sz=ec(),ax=Bs(),Tz=Af(),Hs=rc(),Ez=ue(),Ks=Us(),cc=Ds(),oh=$e(),nx=Mv(),Rz=rx(),cx=(t,e)=>new RegExp(t,e);cx.code="new RegExp";var Pz=["removeAdditional","useDefaults","coerceTypes"],Az=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Iz={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."},Oz={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},ox=200;function Cz(t){var e,r,n,o,s,i,a,c,l,u,d,b,m,f,y,v,E,R,z,V,J,He,Xe,Rr,rr;let tn=t.strict,mr=(e=t.code)===null||e===void 0?void 0:e.optimize,Un=mr===!0||mr===void 0?1:mr||0,Zn=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:cx,ai=(o=t.uriResolver)!==null&&o!==void 0?o:Rz.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:tn)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:tn)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:tn)!==null&&u!==void 0?u:"log",strictTuples:(b=(d=t.strictTuples)!==null&&d!==void 0?d:tn)!==null&&b!==void 0?b:"log",strictRequired:(f=(m=t.strictRequired)!==null&&m!==void 0?m:tn)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:Un,regExp:Zn}:{optimize:Un,regExp:Zn},loopRequired:(y=t.loopRequired)!==null&&y!==void 0?y:ox,loopEnum:(v=t.loopEnum)!==null&&v!==void 0?v:ox,meta:(E=t.meta)!==null&&E!==void 0?E:!0,messages:(R=t.messages)!==null&&R!==void 0?R:!0,inlineRefs:(z=t.inlineRefs)!==null&&z!==void 0?z:!0,schemaId:(V=t.schemaId)!==null&&V!==void 0?V:"$id",addUsedSchema:(J=t.addUsedSchema)!==null&&J!==void 0?J:!0,validateSchema:(He=t.validateSchema)!==null&&He!==void 0?He:!0,validateFormats:(Xe=t.validateFormats)!==null&&Xe!==void 0?Xe:!0,unicodeRegExp:(Rr=t.unicodeRegExp)!==null&&Rr!==void 0?Rr:!0,int32range:(rr=t.int32range)!==null&&rr!==void 0?rr:!0,uriResolver:ai}}var Ws=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...Cz(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new Ez.ValueScope({scope:{},prefixes:Az,es5:r,lines:n}),this.logger=Dz(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Tz.getRules)(),sx.call(this,Iz,e,"NOT SUPPORTED"),sx.call(this,Oz,e,"DEPRECATED","warn"),this._metaOpts=Lz.call(this),e.formats&&Nz.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&jz.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),zz.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=nx;n==="id"&&(o={...nx},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(u,d){await s.call(this,u.$schema);let b=this._addSchema(u,d);return b.validate||i.call(this,b)}async function s(u){u&&!this.getSchema(u)&&await o.call(this,{$ref:u},!0)}async function i(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof ax.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,u)}}function a({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function c(u){let d=await l.call(this,u);this.refs[u]||await s.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,r)}async function l(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Ks.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new 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 o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=ix.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Hs.SchemaEnv({schema:{},schemaId:n});if(r=Hs.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}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 r=ix.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,Ks.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Zz.call(this,n,r),!r)return(0,oh.eachItem)(n,s=>nh.call(this,s)),this;Fz.call(this,r);let o={...r,type:(0,cc.getJSONTypes)(r.type),schemaType:(0,cc.getJSONTypes)(r.schemaType)};return(0,oh.eachItem)(n,o.type.length===0?s=>nh.call(this,s,o):s=>o.type.forEach(i=>nh.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=i[a];l&&u&&(i[a]=lx(u))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,Ks.normalizeId)(i||n);let l=Ks.getSchemaRefs.call(this,e,n);return c=new Hs.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:l}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Hs.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{Hs.compileSchema.call(this,e)}finally{this.opts=r}}};Ws.ValidationError=Sz.default;Ws.MissingRefError=ax.default;nt.default=Ws;function sx(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function ix(t){return t=(0,Ks.normalizeId)(t),this.schemas[t]||this.refs[t]}function zz(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function Nz(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function jz(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function Lz(){let t={...this.opts};for(let e of Pz)delete t[e];return t}var Mz={log(){},warn(){},error(){}};function Dz(t){if(t===!1)return Mz;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var Uz=/^[a-z_$][a-z0-9_$:-]*$/i;function Zz(t,e){let{RULES:r}=this;if((0,oh.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!Uz.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function nh(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,cc.getJSONTypes)(e.type),schemaType:(0,cc.getJSONTypes)(e.schemaType)}};e.before?qz.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function qz(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function Fz(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=lx(e)),t.validateSchema=this.compile(e,!0))}var Bz={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function lx(t){return{anyOf:[t,Bz]}}});var dx=Z(sh=>{"use strict";Object.defineProperty(sh,"__esModule",{value:!0});var Vz={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};sh.default=Vz});var mx=Z(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.callRef=Ln.getValidate=void 0;var Hz=Bs(),px=Zt(),$t=ue(),Eo=Tr(),fx=rc(),lc=$e(),Kz={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:l}=s;if((r==="#"||r==="#/")&&o===l.baseId)return d();let u=fx.resolveRef.call(c,l,o,r);if(u===void 0)throw new Hz.default(n.opts.uriResolver,o,r);if(u instanceof fx.SchemaEnv)return b(u);return m(u);function d(){if(s===l)return uc(t,i,s,s.$async);let f=e.scopeValue("root",{ref:l});return uc(t,(0,$t._)`${f}.validate`,l,l.$async)}function b(f){let y=hx(t,f);uc(t,y,f,f.$async)}function m(f){let y=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,$t.stringify)(f)}:{ref:f}),v=e.name("valid"),E=t.subschema({schema:f,dataTypes:[],schemaPath:$t.nil,topSchemaRef:y,errSchemaPath:r},v);t.mergeEvaluated(E),t.ok(v)}}};function hx(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,$t._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Ln.getValidate=hx;function uc(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?Eo.default.this:$t.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let f=o.let("valid");o.try(()=>{o.code((0,$t._)`await ${(0,px.callValidateCode)(t,e,l)}`),m(e),i||o.assign(f,!0)},y=>{o.if((0,$t._)`!(${y} instanceof ${s.ValidationError})`,()=>o.throw(y)),b(y),i||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,px.callValidateCode)(t,e,l),()=>m(e),()=>b(e))}function b(f){let y=(0,$t._)`${f}.errors`;o.assign(Eo.default.vErrors,(0,$t._)`${Eo.default.vErrors} === null ? ${y} : ${Eo.default.vErrors}.concat(${y})`),o.assign(Eo.default.errors,(0,$t._)`${Eo.default.vErrors}.length`)}function m(f){var y;if(!s.opts.unevaluated)return;let v=(y=r?.validate)===null||y===void 0?void 0:y.evaluated;if(s.props!==!0)if(v&&!v.dynamicProps)v.props!==void 0&&(s.props=lc.mergeEvaluated.props(o,v.props,s.props));else{let E=o.var("props",(0,$t._)`${f}.evaluated.props`);s.props=lc.mergeEvaluated.props(o,E,s.props,$t.Name)}if(s.items!==!0)if(v&&!v.dynamicItems)v.items!==void 0&&(s.items=lc.mergeEvaluated.items(o,v.items,s.items));else{let E=o.var("items",(0,$t._)`${f}.evaluated.items`);s.items=lc.mergeEvaluated.items(o,E,s.items,$t.Name)}}}Ln.callRef=uc;Ln.default=Kz});var gx=Z(ih=>{"use strict";Object.defineProperty(ih,"__esModule",{value:!0});var Wz=dx(),Gz=mx(),Jz=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Wz.default,Gz.default];ih.default=Jz});var yx=Z(ah=>{"use strict";Object.defineProperty(ah,"__esModule",{value:!0});var dc=ue(),Xr=dc.operators,pc={maximum:{okStr:"<=",ok:Xr.LTE,fail:Xr.GT},minimum:{okStr:">=",ok:Xr.GTE,fail:Xr.LT},exclusiveMaximum:{okStr:"<",ok:Xr.LT,fail:Xr.GTE},exclusiveMinimum:{okStr:">",ok:Xr.GT,fail:Xr.LTE}},Yz={message:({keyword:t,schemaCode:e})=>(0,dc.str)`must be ${pc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,dc._)`{comparison: ${pc[t].okStr}, limit: ${e}}`},Xz={keyword:Object.keys(pc),type:"number",schemaType:"number",$data:!0,error:Yz,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,dc._)`${r} ${pc[e].fail} ${n} || isNaN(${r})`)}};ah.default=Xz});var bx=Z(ch=>{"use strict";Object.defineProperty(ch,"__esModule",{value:!0});var Gs=ue(),Qz={message:({schemaCode:t})=>(0,Gs.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Gs._)`{multipleOf: ${t}}`},eN={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Qz,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Gs._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Gs._)`${i} !== parseInt(${i})`;t.fail$data((0,Gs._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};ch.default=eN});var _x=Z(lh=>{"use strict";Object.defineProperty(lh,"__esModule",{value:!0});function wx(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}lh.default=wx;wx.code='require("ajv/dist/runtime/ucs2length").default'});var vx=Z(uh=>{"use strict";Object.defineProperty(uh,"__esModule",{value:!0});var Mn=ue(),tN=$e(),rN=_x(),nN={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Mn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Mn._)`{limit: ${t}}`},oN={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:nN,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Mn.operators.GT:Mn.operators.LT,i=o.opts.unicode===!1?(0,Mn._)`${r}.length`:(0,Mn._)`${(0,tN.useFunc)(t.gen,rN.default)}(${r})`;t.fail$data((0,Mn._)`${i} ${s} ${n}`)}};uh.default=oN});var xx=Z(dh=>{"use strict";Object.defineProperty(dh,"__esModule",{value:!0});var sN=Zt(),iN=$e(),Ro=ue(),aN={message:({schemaCode:t})=>(0,Ro.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Ro._)`{pattern: ${t}}`},cN={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:aN,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,l=c.code==="new RegExp"?(0,Ro._)`new RegExp`:(0,iN.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,Ro._)`${l}(${s}, ${a}).test(${r})`),()=>e.assign(u,!1)),t.fail$data((0,Ro._)`!${u}`)}else{let c=(0,sN.usePattern)(t,o);t.fail$data((0,Ro._)`!${c}.test(${r})`)}}};dh.default=cN});var kx=Z(ph=>{"use strict";Object.defineProperty(ph,"__esModule",{value:!0});var Js=ue(),lN={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Js.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Js._)`{limit: ${t}}`},uN={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:lN,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Js.operators.GT:Js.operators.LT;t.fail$data((0,Js._)`Object.keys(${r}).length ${o} ${n}`)}};ph.default=uN});var $x=Z(fh=>{"use strict";Object.defineProperty(fh,"__esModule",{value:!0});var Ys=Zt(),Xs=ue(),dN=$e(),pN={message:({params:{missingProperty:t}})=>(0,Xs.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Xs._)`{missingProperty: ${t}}`},fN={keyword:"required",type:"object",schemaType:"array",$data:!0,error:pN,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?l():u(),a.strictRequired){let m=t.parentSchema.properties,{definedProperties:f}=t.it;for(let y of r)if(m?.[y]===void 0&&!f.has(y)){let v=i.schemaEnv.baseId+i.errSchemaPath,E=`required property "${y}" is not defined at "${v}" (strictRequired)`;(0,dN.checkStrictMode)(i,E,i.opts.strictRequired)}}function l(){if(c||s)t.block$data(Xs.nil,d);else for(let m of r)(0,Ys.checkReportMissingProp)(t,m)}function u(){let m=e.let("missing");if(c||s){let f=e.let("valid",!0);t.block$data(f,()=>b(m,f)),t.ok(f)}else e.if((0,Ys.checkMissingProp)(t,r,m)),(0,Ys.reportMissingProp)(t,m),e.else()}function d(){e.forOf("prop",n,m=>{t.setParams({missingProperty:m}),e.if((0,Ys.noPropertyInData)(e,o,m,a.ownProperties),()=>t.error())})}function b(m,f){t.setParams({missingProperty:m}),e.forOf(m,n,()=>{e.assign(f,(0,Ys.propertyInData)(e,o,m,a.ownProperties)),e.if((0,Xs.not)(f),()=>{t.error(),e.break()})},Xs.nil)}}};fh.default=fN});var Sx=Z(hh=>{"use strict";Object.defineProperty(hh,"__esModule",{value:!0});var Qs=ue(),hN={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Qs.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Qs._)`{limit: ${t}}`},mN={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:hN,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Qs.operators.GT:Qs.operators.LT;t.fail$data((0,Qs._)`${r}.length ${o} ${n}`)}};hh.default=mN});var fc=Z(mh=>{"use strict";Object.defineProperty(mh,"__esModule",{value:!0});var Tx=Mf();Tx.code='require("ajv/dist/runtime/equal").default';mh.default=Tx});var Ex=Z(yh=>{"use strict";Object.defineProperty(yh,"__esModule",{value:!0});var gh=Ds(),ot=ue(),gN=$e(),yN=fc(),bN={message:({params:{i:t,j:e}})=>(0,ot.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,ot._)`{i: ${t}, j: ${e}}`},wN={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:bN,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),l=s.items?(0,gh.getSchemaTypes)(s.items):[];t.block$data(c,u,(0,ot._)`${i} === false`),t.ok(c);function u(){let f=e.let("i",(0,ot._)`${r}.length`),y=e.let("j");t.setParams({i:f,j:y}),e.assign(c,!0),e.if((0,ot._)`${f} > 1`,()=>(d()?b:m)(f,y))}function d(){return l.length>0&&!l.some(f=>f==="object"||f==="array")}function b(f,y){let v=e.name("item"),E=(0,gh.checkDataTypes)(l,v,a.opts.strictNumbers,gh.DataType.Wrong),R=e.const("indices",(0,ot._)`{}`);e.for((0,ot._)`;${f}--;`,()=>{e.let(v,(0,ot._)`${r}[${f}]`),e.if(E,(0,ot._)`continue`),l.length>1&&e.if((0,ot._)`typeof ${v} == "string"`,(0,ot._)`${v} += "_"`),e.if((0,ot._)`typeof ${R}[${v}] == "number"`,()=>{e.assign(y,(0,ot._)`${R}[${v}]`),t.error(),e.assign(c,!1).break()}).code((0,ot._)`${R}[${v}] = ${f}`)})}function m(f,y){let v=(0,gN.useFunc)(e,yN.default),E=e.name("outer");e.label(E).for((0,ot._)`;${f}--;`,()=>e.for((0,ot._)`${y} = ${f}; ${y}--;`,()=>e.if((0,ot._)`${v}(${r}[${f}], ${r}[${y}])`,()=>{t.error(),e.assign(c,!1).break(E)})))}}};yh.default=wN});var Rx=Z(wh=>{"use strict";Object.defineProperty(wh,"__esModule",{value:!0});var bh=ue(),_N=$e(),vN=fc(),xN={message:"must be equal to constant",params:({schemaCode:t})=>(0,bh._)`{allowedValue: ${t}}`},kN={keyword:"const",$data:!0,error:xN,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,bh._)`!${(0,_N.useFunc)(e,vN.default)}(${r}, ${o})`):t.fail((0,bh._)`${s} !== ${r}`)}};wh.default=kN});var Px=Z(_h=>{"use strict";Object.defineProperty(_h,"__esModule",{value:!0});var ei=ue(),$N=$e(),SN=fc(),TN={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,ei._)`{allowedValues: ${t}}`},EN={keyword:"enum",schemaType:"array",$data:!0,error:TN,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,l=()=>c??(c=(0,$N.useFunc)(e,SN.default)),u;if(a||n)u=e.let("valid"),t.block$data(u,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let m=e.const("vSchema",s);u=(0,ei.or)(...o.map((f,y)=>b(m,y)))}t.pass(u);function d(){e.assign(u,!1),e.forOf("v",s,m=>e.if((0,ei._)`${l()}(${r}, ${m})`,()=>e.assign(u,!0).break()))}function b(m,f){let y=o[f];return typeof y=="object"&&y!==null?(0,ei._)`${l()}(${r}, ${m}[${f}])`:(0,ei._)`${r} === ${y}`}}};_h.default=EN});var Ax=Z(vh=>{"use strict";Object.defineProperty(vh,"__esModule",{value:!0});var RN=yx(),PN=bx(),AN=vx(),IN=xx(),ON=kx(),CN=$x(),zN=Sx(),NN=Ex(),jN=Rx(),LN=Px(),MN=[RN.default,PN.default,AN.default,IN.default,ON.default,CN.default,zN.default,NN.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},jN.default,LN.default];vh.default=MN});var kh=Z(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});ti.validateAdditionalItems=void 0;var Dn=ue(),xh=$e(),DN={message:({params:{len:t}})=>(0,Dn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Dn._)`{limit: ${t}}`},UN={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:DN,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,xh.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Ix(t,n)}};function Ix(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Dn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Dn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,xh.alwaysValidSchema)(i,n)){let l=r.var("valid",(0,Dn._)`${a} <= ${e.length}`);r.if((0,Dn.not)(l),()=>c(l)),t.ok(l)}function c(l){r.forRange("i",e.length,a,u=>{t.subschema({keyword:s,dataProp:u,dataPropType:xh.Type.Num},l),i.allErrors||r.if((0,Dn.not)(l),()=>r.break())})}}ti.validateAdditionalItems=Ix;ti.default=UN});var $h=Z(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});ri.validateTuple=void 0;var Ox=ue(),hc=$e(),ZN=Zt(),qN={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Cx(t,"additionalItems",e);r.items=!0,!(0,hc.alwaysValidSchema)(r,e)&&t.ok((0,ZN.validateArray)(t))}};function Cx(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;u(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=hc.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,Ox._)`${s}.length`);r.forEach((d,b)=>{(0,hc.alwaysValidSchema)(a,d)||(n.if((0,Ox._)`${l} > ${b}`,()=>t.subschema({keyword:i,schemaProp:b,dataProp:b},c)),t.ok(c))});function u(d){let{opts:b,errSchemaPath:m}=a,f=r.length,y=f===d.minItems&&(f===d.maxItems||d[e]===!1);if(b.strictTuples&&!y){let v=`"${i}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${m}"`;(0,hc.checkStrictMode)(a,v,b.strictTuples)}}}ri.validateTuple=Cx;ri.default=qN});var zx=Z(Sh=>{"use strict";Object.defineProperty(Sh,"__esModule",{value:!0});var FN=$h(),BN={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,FN.validateTuple)(t,"items")};Sh.default=BN});var jx=Z(Th=>{"use strict";Object.defineProperty(Th,"__esModule",{value:!0});var Nx=ue(),VN=$e(),HN=Zt(),KN=kh(),WN={message:({params:{len:t}})=>(0,Nx.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Nx._)`{limit: ${t}}`},GN={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:WN,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,VN.alwaysValidSchema)(n,e)&&(o?(0,KN.validateAdditionalItems)(t,o):t.ok((0,HN.validateArray)(t)))}};Th.default=GN});var Lx=Z(Eh=>{"use strict";Object.defineProperty(Eh,"__esModule",{value:!0});var Ft=ue(),mc=$e(),JN={message:({params:{min:t,max:e}})=>e===void 0?(0,Ft.str)`must contain at least ${t} valid item(s)`:(0,Ft.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Ft._)`{minContains: ${t}}`:(0,Ft._)`{minContains: ${t}, maxContains: ${e}}`},YN={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:JN,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:l}=n;s.opts.next?(i=c===void 0?1:c,a=l):i=1;let u=e.const("len",(0,Ft._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,mc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,mc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,mc.alwaysValidSchema)(s,r)){let y=(0,Ft._)`${u} >= ${i}`;a!==void 0&&(y=(0,Ft._)`${y} && ${u} <= ${a}`),t.pass(y);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?m(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,Ft._)`${o}.length > 0`,b)):(e.let(d,!1),b()),t.result(d,()=>t.reset());function b(){let y=e.name("_valid"),v=e.let("count",0);m(y,()=>e.if(y,()=>f(v)))}function m(y,v){e.forRange("i",0,u,E=>{t.subschema({keyword:"contains",dataProp:E,dataPropType:mc.Type.Num,compositeRule:!0},y),v()})}function f(y){e.code((0,Ft._)`${y}++`),a===void 0?e.if((0,Ft._)`${y} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,Ft._)`${y} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,Ft._)`${y} >= ${i}`,()=>e.assign(d,!0)))}}};Eh.default=YN});var Ux=Z(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.validateSchemaDeps=pr.validatePropertyDeps=pr.error=void 0;var Rh=ue(),XN=$e(),ni=Zt();pr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Rh.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Rh._)`{property: ${t},
1132
+ ]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var Hp,Jt,KI,Ba=O(()=>{Kr();Jt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Hp===void 0&&(Hp=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Hp),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};KI=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function Va(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===D.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:re(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??qe(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:re(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===D.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Fa(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===D.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===D.ZodBranded&&t.keyType._def.type._def.typeName===D.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Za(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var Ha=O(()=>{us();Ge();Ba();qa();Zt()});function L_(t,e){if(e.mapStrategy==="record")return Va(t,e);let r=re(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||qe(e),n=re(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||qe(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var Gp=O(()=>{Ge();Ha();Zt()});function D_(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}var Wp=O(()=>{});function M_(t){return t.target==="openAi"?void 0:{not:qe({...t,currentPath:[...t.currentPath,"not"]})}}var Jp=O(()=>{Zt()});function U_(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Yp=O(()=>{});function q_(t,e){if(e.target==="openApi3")return Z_(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in js&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=js[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return Z_(t,e)}var js,Z_,Ka=O(()=>{Ge();js={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Z_=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>re(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function F_(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:js[t.innerType._def.typeName],nullable:!0}:{type:[js[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=re(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=re(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var Xp=O(()=>{Ge();Ka()});function B_(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",zp(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?xe(r,"minimum",n.value,n.message,e):xe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),xe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?xe(r,"maximum",n.value,n.message,e):xe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),xe(r,"maximum",n.value,n.message,e));break;case"multipleOf":xe(r,"multipleOf",n.value,n.message,e);break}return r}var Qp=O(()=>{Kr()});function V_(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let l=JI(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=re(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});u!==void 0&&(n.properties[a]=u,l||o.push(a))}o.length&&(n.required=o);let i=WI(t,e);return i!==void 0&&(n.additionalProperties=i),n}function WI(t,e){if(t.catchall._def.typeName!=="ZodNever")return re(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function JI(t){try{return t.isOptional()}catch{return!0}}var ef=O(()=>{Ge()});var H_,tf=O(()=>{Ge();Zt();H_=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return re(t.innerType._def,e);let r=re(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:qe(e)},r]}:qe(e)}});var K_,rf=O(()=>{Ge();K_=(t,e)=>{if(e.pipeStrategy==="input")return re(t.in._def,e);if(e.pipeStrategy==="output")return re(t.out._def,e);let r=re(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=re(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function G_(t,e){return re(t.type._def,e)}var nf=O(()=>{Ge()});function W_(t,e){let n={type:"array",uniqueItems:!0,items:re(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&xe(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&xe(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var of=O(()=>{Kr();Ge()});function J_(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>re(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:re(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>re(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var sf=O(()=>{Ge()});function Y_(t){return{not:qe(t)}}var af=O(()=>{Zt()});function X_(t){return qe(t)}var cf=O(()=>{Zt()});var Q_,lf=O(()=>{Ge();Q_=(t,e)=>re(t.innerType._def,e)});var ev,uf=O(()=>{us();Zt();Np();jp();Lp();qa();Dp();Up();Zp();qp();Fp();Bp();Vp();Gp();Wp();Jp();Yp();Xp();Qp();ef();tf();rf();nf();Ha();of();Ba();sf();af();Ka();cf();lf();ev=(t,e,r)=>{switch(e){case D.ZodString:return Fa(t,r);case D.ZodNumber:return B_(t,r);case D.ZodObject:return V_(t,r);case D.ZodBigInt:return R_(t,r);case D.ZodBoolean:return P_();case D.ZodDate:return Mp(t,r);case D.ZodUndefined:return Y_(r);case D.ZodNull:return U_(r);case D.ZodArray:return E_(t,r);case D.ZodUnion:case D.ZodDiscriminatedUnion:return q_(t,r);case D.ZodIntersection:return z_(t,r);case D.ZodTuple:return J_(t,r);case D.ZodRecord:return Va(t,r);case D.ZodLiteral:return N_(t,r);case D.ZodEnum:return C_(t);case D.ZodNativeEnum:return D_(t);case D.ZodNullable:return F_(t,r);case D.ZodOptional:return H_(t,r);case D.ZodMap:return L_(t,r);case D.ZodSet:return W_(t,r);case D.ZodLazy:return()=>t.getter()._def;case D.ZodPromise:return G_(t,r);case D.ZodNaN:case D.ZodNever:return M_(r);case D.ZodEffects:return O_(t,r);case D.ZodAny:return qe(r);case D.ZodUnknown:return X_(r);case D.ZodDefault:return I_(t,r);case D.ZodBranded:return Za(t,r);case D.ZodReadonly:return Q_(t,r);case D.ZodCatch:return A_(t,r);case D.ZodPipeline:return K_(t,r);case D.ZodFunction:case D.ZodVoid:case D.ZodSymbol:return;default:return(n=>{})(e)}}});function re(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==$_)return a}if(n&&!r){let a=YI(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=ev(t,t.typeName,e),i=typeof s=="function"?re(s(),e):s;if(i&&XI(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var YI,XI,Ge=O(()=>{Da();uf();Ua();Zt();YI=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Ma(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),qe(e)):e.$refStrategy==="seen"?qe(e):void 0}},XI=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var tv=O(()=>{});var df,pf=O(()=>{Ge();Cp();Zt();df=(t,e)=>{let r=T_(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:re(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??qe(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=re(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??qe(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var rv=O(()=>{Da();Cp();Kr();Ua();Ge();tv();Zt();Np();jp();Lp();qa();Dp();Up();Zp();qp();Fp();Bp();Vp();Gp();Wp();Jp();Yp();Xp();Qp();ef();tf();rf();nf();lf();Ha();of();Ba();sf();af();Ka();cf();uf();pf();pf()});function QI(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function ff(t,e){return lr(t)?Qd(t,{target:QI(e?.target),io:e?.pipeStrategy??"input"}):df(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function hf(t){let r=Br(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=fo(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function mf(t,e){let r=Fr(t,e);if(!r.success)throw r.error;return r.data}var gf=O(()=>{rp();ks();rv()});function nv(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ov(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];nv(i)&&nv(s)?r[o]={...i,...s}:r[o]=s}return r}var eO,Ga,sv=O(()=>{ks();wo();x_();gf();eO=6e4,Ga=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(va,r=>{this._oncancel(r)}),this.setNotificationHandler(ka,r=>{this._onprogress(r)}),this.setRequestHandler(xa,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler($a,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new G(X.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Ta,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),a.type==="response")u(c);else{let d=c,b=new G(d.error.code,d.error.message,d.error.data);u(b)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${l}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new G(X.InvalidParams,`Task not found: ${s}`);if(!Hr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Hr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Vr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Ea,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new G(X.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Pa,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new G(X.InvalidParams,`Task not found: ${r.params.taskId}`);if(Hr(o.status))throw new G(X.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new G(X.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof G?o:new G(X.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),G.fromError(X.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),Es(s)||d_(s)?this._onresponse(s):wp(s)?this._onrequest(s,i):u_(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=G.fromError(X.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[Vr]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:X.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(u).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=a_(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,l={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(u,d)},sendRequest:async(u,d,b)=>{if(i.signal.aborted)throw new G(X.ConnectionClosed,"Request was cancelled");let m={...b,relatedRequestId:e.id};s&&!m.relatedTask&&(m.relatedTask={taskId:s});let f=m.relatedTask?.taskId??s;return f&&c&&await c.updateTaskStatus(f,"input_required"),await this.request(u,d,m)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async u=>{if(i.signal.aborted)return;let d={result:u,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async u=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:X.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Es(e))n(e);else{let i=new G(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Es(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),Es(e))o(e);else{let i=G.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof G?i:new G(X.InternalError,String(i))}}return}let s;try{let i=await this.request(e,mo,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new G(X.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Hr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new G(X.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new G(X.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof G?i:new G(X.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let d=R=>{u(R)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(R){d(R);return}n?.signal?.throwIfAborted();let b=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:b};n?.onprogress&&(this._progressHandlers.set(b,n.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:b}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Vr]:c}});let f=R=>{this._responseHandlers.delete(b),this._progressHandlers.delete(b),this._cleanupTimeout(b),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:b,reason:String(R)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(H=>this._onerror(new Error(`Failed to send cancellation: ${H}`)));let z=R instanceof G?R:new G(X.RequestTimeout,String(R));u(z)};this._responseHandlers.set(b,R=>{if(!n?.signal?.aborted){if(R instanceof Error)return u(R);try{let z=Fr(r,R.result);z.success?l(z.data):u(z.error)}catch(z){u(z)}}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});let y=n?.timeout??eO,v=()=>f(G.fromError(X.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(b,y,n?.maxTotalTimeout,v,n?.resetTimeoutOnProgress??!1);let E=c?.taskId;if(E){let R=z=>{let H=this._responseHandlers.get(b);H?H(z):this._onerror(new Error(`Response handler missing for side-channeled request ${b}`))};this._requestResolvers.set(b,R),this._enqueueTaskMessage(E,{type:"request",message:m,timestamp:Date.now()}).catch(z=>{this._cleanupTimeout(b),u(z)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(R=>{this._cleanupTimeout(b),u(R)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Sa,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Ra,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},h_,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Vr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Vr]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Vr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=hf(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=mf(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=hf(e);this._notificationHandlers.set(n,o=>{let s=mf(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&wp(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new G(X.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new G(X.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new G(X.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new G(X.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=Os.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Hr(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new G(X.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Hr(a.status))throw new G(X.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let l=Os.parse({method:"notifications/tasks/status",params:c});await this.notification(l),Hr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var Ms=Z(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.regexpCode=Ee.getEsmExportName=Ee.getProperty=Ee.safeStringify=Ee.stringify=Ee.strConcat=Ee.addCodeArg=Ee.str=Ee._=Ee.nil=Ee._Code=Ee.Name=Ee.IDENTIFIER=Ee._CodeOrName=void 0;var Ls=class{};Ee._CodeOrName=Ls;Ee.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Pn=class extends Ls{constructor(e){if(super(),!Ee.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};Ee.Name=Pn;var qt=class extends Ls{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(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Pn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Ee._Code=qt;Ee.nil=new qt("");function iv(t,...e){let r=[t[0]],n=0;for(;n<e.length;)bf(r,e[n]),r.push(t[++n]);return new qt(r)}Ee._=iv;var yf=new qt("+");function av(t,...e){let r=[Ds(t[0])],n=0;for(;n<e.length;)r.push(yf),bf(r,e[n]),r.push(yf,Ds(t[++n]));return tO(r),new qt(r)}Ee.str=av;function bf(t,e){e instanceof qt?t.push(...e._items):e instanceof Pn?t.push(e):t.push(oO(e))}Ee.addCodeArg=bf;function tO(t){let e=1;for(;e<t.length-1;){if(t[e]===yf){let r=rO(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function rO(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Pn||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Pn))return`"${t}${e.slice(1)}`}function nO(t,e){return e.emptyStr()?t:t.emptyStr()?e:av`${t}${e}`}Ee.strConcat=nO;function oO(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Ds(Array.isArray(t)?t.join(","):t)}function sO(t){return new qt(Ds(t))}Ee.stringify=sO;function Ds(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Ee.safeStringify=Ds;function iO(t){return typeof t=="string"&&Ee.IDENTIFIER.test(t)?new qt(`.${t}`):iv`[${t}]`}Ee.getProperty=iO;function aO(t){if(typeof t=="string"&&Ee.IDENTIFIER.test(t))return new qt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Ee.getEsmExportName=aO;function cO(t){return new qt(t.toString())}Ee.regexpCode=cO});var vf=Z(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.ValueScope=xt.ValueScopeName=xt.Scope=xt.varKinds=xt.UsedValueState=void 0;var vt=Ms(),wf=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Wa;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Wa||(xt.UsedValueState=Wa={}));xt.varKinds={const:new vt.Name("const"),let:new vt.Name("let"),var:new vt.Name("var")};var Ja=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof vt.Name?e:this.name(e)}name(e){return new vt.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};xt.Scope=Ja;var Ya=class extends vt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,vt._)`.${new vt.Name(r)}[${n}]`}};xt.ValueScopeName=Ya;var lO=(0,vt._)`\n`,_f=class extends Ja{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?lO:vt.nil}}get(){return this._scope}name(e){return new Ya(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let u=a.get(i);if(u)return u}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),l=c.length;return c[l]=r.ref,o.setValue(r,{property:s,itemIndex:l}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,vt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=vt.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,Wa.Started);let u=r(l);if(u){let d=this.opts.es5?xt.varKinds.var:xt.varKinds.const;s=(0,vt._)`${s}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))s=(0,vt._)`${s}${u}${this.opts._n}`;else throw new wf(l);c.set(l,Wa.Completed)})}return s}};xt.ValueScope=_f});var pe=Z(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.or=fe.and=fe.not=fe.CodeGen=fe.operators=fe.varKinds=fe.ValueScopeName=fe.ValueScope=fe.Scope=fe.Name=fe.regexpCode=fe.stringify=fe.getProperty=fe.nil=fe.strConcat=fe.str=fe._=void 0;var ke=Ms(),Xt=vf(),Gr=Ms();Object.defineProperty(fe,"_",{enumerable:!0,get:function(){return Gr._}});Object.defineProperty(fe,"str",{enumerable:!0,get:function(){return Gr.str}});Object.defineProperty(fe,"strConcat",{enumerable:!0,get:function(){return Gr.strConcat}});Object.defineProperty(fe,"nil",{enumerable:!0,get:function(){return Gr.nil}});Object.defineProperty(fe,"getProperty",{enumerable:!0,get:function(){return Gr.getProperty}});Object.defineProperty(fe,"stringify",{enumerable:!0,get:function(){return Gr.stringify}});Object.defineProperty(fe,"regexpCode",{enumerable:!0,get:function(){return Gr.regexpCode}});Object.defineProperty(fe,"Name",{enumerable:!0,get:function(){return Gr.Name}});var tc=vf();Object.defineProperty(fe,"Scope",{enumerable:!0,get:function(){return tc.Scope}});Object.defineProperty(fe,"ValueScope",{enumerable:!0,get:function(){return tc.ValueScope}});Object.defineProperty(fe,"ValueScopeName",{enumerable:!0,get:function(){return tc.ValueScopeName}});Object.defineProperty(fe,"varKinds",{enumerable:!0,get:function(){return tc.varKinds}});fe.operators={GT:new ke._Code(">"),GTE:new ke._Code(">="),LT:new ke._Code("<"),LTE:new ke._Code("<="),EQ:new ke._Code("==="),NEQ:new ke._Code("!=="),NOT:new ke._Code("!"),OR:new ke._Code("||"),AND:new ke._Code("&&"),ADD:new ke._Code("+")};var $r=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},xf=class extends $r{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Xt.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=vo(this.rhs,e,r)),this}get names(){return this.rhs instanceof ke._CodeOrName?this.rhs.names:{}}},Xa=class extends $r{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof ke.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=vo(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ke.Name?{}:{...this.lhs.names};return ec(e,this.rhs)}},kf=class extends Xa{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},$f=class extends $r{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Sf=class extends $r{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Tf=class extends $r{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Ef=class extends $r{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=vo(this.code,e,r),this}get names(){return this.code instanceof ke._CodeOrName?this.code.names:{}}},Us=class extends $r{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(uO(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>On(e,r.names),{})}},Sr=class extends Us{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Rf=class extends Us{},_o=class extends Sr{};_o.kind="else";var An=class t extends Sr{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new _o(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(cv(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=vo(this.condition,e,r),this}get names(){let e=super.names;return ec(e,this.condition),this.else&&On(e,this.else.names),e}};An.kind="if";var In=class extends Sr{};In.kind="for";var Pf=class extends In{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=vo(this.iteration,e,r),this}get names(){return On(super.names,this.iteration.names)}},Af=class extends In{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?Xt.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=ec(super.names,this.from);return ec(e,this.to)}},Qa=class extends In{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=vo(this.iterable,e,r),this}get names(){return On(super.names,this.iterable.names)}},Zs=class extends Sr{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Zs.kind="func";var qs=class extends Us{render(e){return"return "+super.render(e)}};qs.kind="return";var If=class extends Sr{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&On(e,this.catch.names),this.finally&&On(e,this.finally.names),e}},Fs=class extends Sr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Fs.kind="catch";var Bs=class extends Sr{render(e){return"finally"+super.render(e)}};Bs.kind="finally";var Of=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
1133
+ `:""},this._extScope=e,this._scope=new Xt.Scope({parent:e}),this._nodes=[new Rf]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new xf(e,s,n)),s}const(e,r,n){return this._def(Xt.varKinds.const,e,r,n)}let(e,r,n){return this._def(Xt.varKinds.let,e,r,n)}var(e,r,n){return this._def(Xt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Xa(e,r,n))}add(e,r){return this._leafNode(new kf(e,fe.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ke.nil&&this._leafNode(new Ef(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,ke.addCodeArg)(r,o));return r.push("}"),new ke._Code(r)}if(e,r,n){if(this._blockNode(new An(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new An(e))}else(){return this._elseNode(new _o)}endIf(){return this._endBlockNode(An,_o)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Pf(e),r)}forRange(e,r,n,o,s=this.opts.es5?Xt.varKinds.var:Xt.varKinds.let){let i=this._scope.toName(e);return this._for(new Af(s,i,r,n),()=>o(i))}forOf(e,r,n,o=Xt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof ke.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ke._)`${i}.length`,a=>{this.var(s,(0,ke._)`${i}[${a}]`),n(s)})}return this._for(new Qa("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?Xt.varKinds.var:Xt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ke._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Qa("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(In)}label(e){return this._leafNode(new $f(e))}break(e){return this._leafNode(new Sf(e))}return(e){let r=new qs;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(qs)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new If;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Fs(s),r(s)}return n&&(this._currNode=o.finally=new Bs,this.code(n)),this._endBlockNode(Fs,Bs)}throw(e){return this._leafNode(new Tf(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=ke.nil,n,o){return this._blockNode(new Zs(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Zs)}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,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof An))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};fe.CodeGen=Of;function On(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function ec(t,e){return e instanceof ke._CodeOrName?On(t,e.names):t}function vo(t,e,r){if(t instanceof ke.Name)return n(t);if(!o(t))return t;return new ke._Code(t._items.reduce((s,i)=>(i instanceof ke.Name&&(i=n(i)),i instanceof ke._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof ke._Code&&s._items.some(i=>i instanceof ke.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function uO(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function cv(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ke._)`!${Cf(t)}`}fe.not=cv;var dO=lv(fe.operators.AND);function pO(...t){return t.reduce(dO)}fe.and=pO;var fO=lv(fe.operators.OR);function hO(...t){return t.reduce(fO)}fe.or=hO;function lv(t){return(e,r)=>e===ke.nil?r:r===ke.nil?e:(0,ke._)`${Cf(e)} ${t} ${Cf(r)}`}function Cf(t){return t instanceof ke.Name?t:(0,ke._)`(${t})`}});var $e=Z(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.checkStrictMode=ge.getErrorPath=ge.Type=ge.useFunc=ge.setEvaluated=ge.evaluatedPropsToName=ge.mergeEvaluated=ge.eachItem=ge.unescapeJsonPointer=ge.escapeJsonPointer=ge.escapeFragment=ge.unescapeFragment=ge.schemaRefOrVal=ge.schemaHasRulesButRef=ge.schemaHasRules=ge.checkUnknownRules=ge.alwaysValidSchema=ge.toHash=void 0;var Ie=pe(),mO=Ms();function gO(t){let e={};for(let r of t)e[r]=!0;return e}ge.toHash=gO;function yO(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(pv(t,e),!fv(e,t.self.RULES.all))}ge.alwaysValidSchema=yO;function pv(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||gv(t,`unknown keyword: "${s}"`)}ge.checkUnknownRules=pv;function fv(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}ge.schemaHasRules=fv;function bO(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}ge.schemaHasRulesButRef=bO;function wO({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Ie._)`${r}`}return(0,Ie._)`${t}${e}${(0,Ie.getProperty)(n)}`}ge.schemaRefOrVal=wO;function _O(t){return hv(decodeURIComponent(t))}ge.unescapeFragment=_O;function vO(t){return encodeURIComponent(Nf(t))}ge.escapeFragment=vO;function Nf(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ge.escapeJsonPointer=Nf;function hv(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ge.unescapeJsonPointer=hv;function xO(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}ge.eachItem=xO;function uv({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof Ie.Name?(s instanceof Ie.Name?t(o,s,i):e(o,s,i),i):s instanceof Ie.Name?(e(o,i,s),s):r(s,i);return a===Ie.Name&&!(c instanceof Ie.Name)?n(o,c):c}}ge.mergeEvaluated={props:uv({mergeNames:(t,e,r)=>t.if((0,Ie._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Ie._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Ie._)`${r} || {}`).code((0,Ie._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Ie._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Ie._)`${r} || {}`),jf(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:mv}),items:uv({mergeNames:(t,e,r)=>t.if((0,Ie._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Ie._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Ie._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Ie._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function mv(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Ie._)`{}`);return e!==void 0&&jf(t,r,e),r}ge.evaluatedPropsToName=mv;function jf(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Ie._)`${e}${(0,Ie.getProperty)(n)}`,!0))}ge.setEvaluated=jf;var dv={};function kO(t,e){return t.scopeValue("func",{ref:e,code:dv[e.code]||(dv[e.code]=new mO._Code(e.code))})}ge.useFunc=kO;var zf;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(zf||(ge.Type=zf={}));function $O(t,e,r){if(t instanceof Ie.Name){let n=e===zf.Num;return r?n?(0,Ie._)`"[" + ${t} + "]"`:(0,Ie._)`"['" + ${t} + "']"`:n?(0,Ie._)`"/" + ${t}`:(0,Ie._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Ie.getProperty)(t).toString():"/"+Nf(t)}ge.getErrorPath=$O;function gv(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}ge.checkStrictMode=gv});var Tr=Z(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});var at=pe(),SO={data:new at.Name("data"),valCxt:new at.Name("valCxt"),instancePath:new at.Name("instancePath"),parentData:new at.Name("parentData"),parentDataProperty:new at.Name("parentDataProperty"),rootData:new at.Name("rootData"),dynamicAnchors:new at.Name("dynamicAnchors"),vErrors:new at.Name("vErrors"),errors:new at.Name("errors"),this:new at.Name("this"),self:new at.Name("self"),scope:new at.Name("scope"),json:new at.Name("json"),jsonPos:new at.Name("jsonPos"),jsonLen:new at.Name("jsonLen"),jsonPart:new at.Name("jsonPart")};Lf.default=SO});var Vs=Z(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.extendErrors=ct.resetErrorsCount=ct.reportExtraError=ct.reportError=ct.keyword$DataError=ct.keywordError=void 0;var Se=pe(),rc=$e(),ht=Tr();ct.keywordError={message:({keyword:t})=>(0,Se.str)`must pass "${t}" keyword validation`};ct.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,Se.str)`"${t}" keyword must be ${e} ($data)`:(0,Se.str)`"${t}" keyword is invalid ($data)`};function TO(t,e=ct.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=wv(t,e,r);n??(i||a)?yv(s,c):bv(o,(0,Se._)`[${c}]`)}ct.reportError=TO;function EO(t,e=ct.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=wv(t,e,r);yv(o,a),s||i||bv(n,ht.default.vErrors)}ct.reportExtraError=EO;function RO(t,e){t.assign(ht.default.errors,e),t.if((0,Se._)`${ht.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,Se._)`${ht.default.vErrors}.length`,e),()=>t.assign(ht.default.vErrors,null)))}ct.resetErrorsCount=RO;function PO({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,ht.default.errors,a=>{t.const(i,(0,Se._)`${ht.default.vErrors}[${a}]`),t.if((0,Se._)`${i}.instancePath === undefined`,()=>t.assign((0,Se._)`${i}.instancePath`,(0,Se.strConcat)(ht.default.instancePath,s.errorPath))),t.assign((0,Se._)`${i}.schemaPath`,(0,Se.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,Se._)`${i}.schema`,r),t.assign((0,Se._)`${i}.data`,n))})}ct.extendErrors=PO;function yv(t,e){let r=t.const("err",e);t.if((0,Se._)`${ht.default.vErrors} === null`,()=>t.assign(ht.default.vErrors,(0,Se._)`[${r}]`),(0,Se._)`${ht.default.vErrors}.push(${r})`),t.code((0,Se._)`${ht.default.errors}++`)}function bv(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,Se._)`new ${t.ValidationError}(${e})`):(r.assign((0,Se._)`${n}.errors`,e),r.return(!1))}var Cn={keyword:new Se.Name("keyword"),schemaPath:new Se.Name("schemaPath"),params:new Se.Name("params"),propertyName:new Se.Name("propertyName"),message:new Se.Name("message"),schema:new Se.Name("schema"),parentSchema:new Se.Name("parentSchema")};function wv(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,Se._)`{}`:AO(t,e,r)}function AO(t,e,r={}){let{gen:n,it:o}=t,s=[IO(o,r),OO(t,r)];return CO(t,e,s),n.object(...s)}function IO({errorPath:t},{instancePath:e}){let r=e?(0,Se.str)`${t}${(0,rc.getErrorPath)(e,rc.Type.Str)}`:t;return[ht.default.instancePath,(0,Se.strConcat)(ht.default.instancePath,r)]}function OO({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,Se.str)`${e}/${t}`;return r&&(o=(0,Se.str)`${o}${(0,rc.getErrorPath)(r,rc.Type.Str)}`),[Cn.schemaPath,o]}function CO(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;n.push([Cn.keyword,o],[Cn.params,typeof e=="function"?e(t):e||(0,Se._)`{}`]),c.messages&&n.push([Cn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Cn.schema,i],[Cn.parentSchema,(0,Se._)`${u}${d}`],[ht.default.data,s]),l&&n.push([Cn.propertyName,l])}});var vv=Z(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});xo.boolOrEmptySchema=xo.topBoolOrEmptySchema=void 0;var zO=Vs(),NO=pe(),jO=Tr(),LO={message:"boolean schema is false"};function DO(t){let{gen:e,schema:r,validateName:n}=t;r===!1?_v(t,!1):typeof r=="object"&&r.$async===!0?e.return(jO.default.data):(e.assign((0,NO._)`${n}.errors`,null),e.return(!0))}xo.topBoolOrEmptySchema=DO;function MO(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),_v(t)):r.var(e,!0)}xo.boolOrEmptySchema=MO;function _v(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,zO.reportError)(o,LO,void 0,e)}});var Df=Z(ko=>{"use strict";Object.defineProperty(ko,"__esModule",{value:!0});ko.getRules=ko.isJSONType=void 0;var UO=["string","number","integer","boolean","null","object","array"],ZO=new Set(UO);function qO(t){return typeof t=="string"&&ZO.has(t)}ko.isJSONType=qO;function FO(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}ko.getRules=FO});var Mf=Z(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.shouldUseRule=Wr.shouldUseGroup=Wr.schemaHasRulesForType=void 0;function BO({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&xv(t,n)}Wr.schemaHasRulesForType=BO;function xv(t,e){return e.rules.some(r=>kv(t,r))}Wr.shouldUseGroup=xv;function kv(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}Wr.shouldUseRule=kv});var Hs=Z(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.reportTypeError=lt.checkDataTypes=lt.checkDataType=lt.coerceAndCheckDataType=lt.getJSONTypes=lt.getSchemaTypes=lt.DataType=void 0;var VO=Df(),HO=Mf(),KO=Vs(),ue=pe(),$v=$e(),$o;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})($o||(lt.DataType=$o={}));function GO(t){let e=Sv(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}lt.getSchemaTypes=GO;function Sv(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(VO.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}lt.getJSONTypes=Sv;function WO(t,e){let{gen:r,data:n,opts:o}=t,s=JO(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,HO.schemaHasRulesForType)(t,e[0]));if(i){let a=Zf(e,n,o.strictNumbers,$o.Wrong);r.if(a,()=>{s.length?YO(t,e,s):qf(t)})}return i}lt.coerceAndCheckDataType=WO;var Tv=new Set(["string","number","integer","boolean","null"]);function JO(t,e){return e?t.filter(r=>Tv.has(r)||e==="array"&&r==="array"):[]}function YO(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,ue._)`typeof ${o}`),a=n.let("coerced",(0,ue._)`undefined`);s.coerceTypes==="array"&&n.if((0,ue._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,ue._)`${o}[0]`).assign(i,(0,ue._)`typeof ${o}`).if(Zf(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,ue._)`${a} !== undefined`);for(let l of r)(Tv.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),qf(t),n.endIf(),n.if((0,ue._)`${a} !== undefined`,()=>{n.assign(o,a),XO(t,a)});function c(l){switch(l){case"string":n.elseIf((0,ue._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,ue._)`"" + ${o}`).elseIf((0,ue._)`${o} === null`).assign(a,(0,ue._)`""`);return;case"number":n.elseIf((0,ue._)`${i} == "boolean" || ${o} === null
1134
+ || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,ue._)`+${o}`);return;case"integer":n.elseIf((0,ue._)`${i} === "boolean" || ${o} === null
1135
+ || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,ue._)`+${o}`);return;case"boolean":n.elseIf((0,ue._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,ue._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,ue._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,ue._)`${i} === "string" || ${i} === "number"
1136
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,ue._)`[${o}]`)}}}function XO({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,ue._)`${e} !== undefined`,()=>t.assign((0,ue._)`${e}[${r}]`,n))}function Uf(t,e,r,n=$o.Correct){let o=n===$o.Correct?ue.operators.EQ:ue.operators.NEQ,s;switch(t){case"null":return(0,ue._)`${e} ${o} null`;case"array":s=(0,ue._)`Array.isArray(${e})`;break;case"object":s=(0,ue._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,ue._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,ue._)`typeof ${e} ${o} ${t}`}return n===$o.Correct?s:(0,ue.not)(s);function i(a=ue.nil){return(0,ue.and)((0,ue._)`typeof ${e} == "number"`,a,r?(0,ue._)`isFinite(${e})`:ue.nil)}}lt.checkDataType=Uf;function Zf(t,e,r,n){if(t.length===1)return Uf(t[0],e,r,n);let o,s=(0,$v.toHash)(t);if(s.array&&s.object){let i=(0,ue._)`typeof ${e} != "object"`;o=s.null?i:(0,ue._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=ue.nil;s.number&&delete s.integer;for(let i in s)o=(0,ue.and)(o,Uf(i,e,r,n));return o}lt.checkDataTypes=Zf;var QO={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ue._)`{type: ${t}}`:(0,ue._)`{type: ${e}}`};function qf(t){let e=eC(t);(0,KO.reportError)(e,QO)}lt.reportTypeError=qf;function eC(t){let{gen:e,data:r,schema:n}=t,o=(0,$v.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Rv=Z(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});nc.assignDefaults=void 0;var So=pe(),tC=$e();function rC(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Ev(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Ev(t,s,o.default))}nc.assignDefaults=rC;function Ev(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,So._)`${s}${(0,So.getProperty)(e)}`;if(o){(0,tC.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,So._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,So._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,So._)`${a} = ${(0,So.stringify)(r)}`)}});var Ft=Z(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.validateUnion=Ae.validateArray=Ae.usePattern=Ae.callValidateCode=Ae.schemaProperties=Ae.allSchemaProperties=Ae.noPropertyInData=Ae.propertyInData=Ae.isOwnProperty=Ae.hasPropFunc=Ae.reportMissingProp=Ae.checkMissingProp=Ae.checkReportMissingProp=void 0;var je=pe(),Ff=$e(),Jr=Tr(),nC=$e();function oC(t,e){let{gen:r,data:n,it:o}=t;r.if(Vf(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,je._)`${e}`},!0),t.error()})}Ae.checkReportMissingProp=oC;function sC({gen:t,data:e,it:{opts:r}},n,o){return(0,je.or)(...n.map(s=>(0,je.and)(Vf(t,e,s,r.ownProperties),(0,je._)`${o} = ${s}`)))}Ae.checkMissingProp=sC;function iC(t,e){t.setParams({missingProperty:e},!0),t.error()}Ae.reportMissingProp=iC;function Pv(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,je._)`Object.prototype.hasOwnProperty`})}Ae.hasPropFunc=Pv;function Bf(t,e,r){return(0,je._)`${Pv(t)}.call(${e}, ${r})`}Ae.isOwnProperty=Bf;function aC(t,e,r,n){let o=(0,je._)`${e}${(0,je.getProperty)(r)} !== undefined`;return n?(0,je._)`${o} && ${Bf(t,e,r)}`:o}Ae.propertyInData=aC;function Vf(t,e,r,n){let o=(0,je._)`${e}${(0,je.getProperty)(r)} === undefined`;return n?(0,je.or)(o,(0,je.not)(Bf(t,e,r))):o}Ae.noPropertyInData=Vf;function Av(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Ae.allSchemaProperties=Av;function cC(t,e){return Av(e).filter(r=>!(0,Ff.alwaysValidSchema)(t,e[r]))}Ae.schemaProperties=cC;function lC({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,l){let u=l?(0,je._)`${t}, ${e}, ${n}${o}`:e,d=[[Jr.default.instancePath,(0,je.strConcat)(Jr.default.instancePath,s)],[Jr.default.parentData,i.parentData],[Jr.default.parentDataProperty,i.parentDataProperty],[Jr.default.rootData,Jr.default.rootData]];i.opts.dynamicRef&&d.push([Jr.default.dynamicAnchors,Jr.default.dynamicAnchors]);let b=(0,je._)`${u}, ${r.object(...d)}`;return c!==je.nil?(0,je._)`${a}.call(${c}, ${b})`:(0,je._)`${a}(${b})`}Ae.callValidateCode=lC;var uC=(0,je._)`new RegExp`;function dC({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,je._)`${o.code==="new RegExp"?uC:(0,nC.useFunc)(t,o)}(${r}, ${n})`})}Ae.usePattern=dC;function pC(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,je._)`${r}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:n,dataProp:l,dataPropType:Ff.Type.Num},s),e.if((0,je.not)(s),a)})}}Ae.validateArray=pC;function fC(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Ff.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,l)=>{let u=t.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);e.assign(i,(0,je._)`${i} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,je.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Ae.validateUnion=fC});var Cv=Z(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.validateKeywordUsage=ur.validSchemaType=ur.funcKeywordCode=ur.macroKeywordCode=void 0;var mt=pe(),zn=Tr(),hC=Ft(),mC=Vs();function gC(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Ov(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=r.name("valid");t.subschema({schema:a,schemaPath:mt.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}ur.macroKeywordCode=gC;function yC(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;wC(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,u=Ov(n,o,l),d=n.let("valid");t.block$data(d,b),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function b(){if(e.errors===!1)y(),e.modifying&&Iv(t),v(()=>t.error());else{let E=e.async?m():f();e.modifying&&Iv(t),v(()=>bC(t,E))}}function m(){let E=n.let("ruleErrs",null);return n.try(()=>y((0,mt._)`await `),R=>n.assign(d,!1).if((0,mt._)`${R} instanceof ${c.ValidationError}`,()=>n.assign(E,(0,mt._)`${R}.errors`),()=>n.throw(R))),E}function f(){let E=(0,mt._)`${u}.errors`;return n.assign(E,null),y(mt.nil),E}function y(E=e.async?(0,mt._)`await `:mt.nil){let R=c.opts.passContext?zn.default.this:zn.default.self,z=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,mt._)`${E}${(0,hC.callValidateCode)(t,u,R,z)}`,e.modifying)}function v(E){var R;n.if((0,mt.not)((R=e.valid)!==null&&R!==void 0?R:d),E)}}ur.funcKeywordCode=yC;function Iv(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,mt._)`${n.parentData}[${n.parentDataProperty}]`))}function bC(t,e){let{gen:r}=t;r.if((0,mt._)`Array.isArray(${e})`,()=>{r.assign(zn.default.vErrors,(0,mt._)`${zn.default.vErrors} === null ? ${e} : ${zn.default.vErrors}.concat(${e})`).assign(zn.default.errors,(0,mt._)`${zn.default.vErrors}.length`),(0,mC.extendErrors)(t)},()=>t.error())}function wC({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Ov(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,mt.stringify)(r)})}function _C(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}ur.validSchemaType=_C;function vC({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}ur.validateKeywordUsage=vC});var Nv=Z(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.extendSubschemaMode=Yr.extendSubschemaData=Yr.getSubschema=void 0;var dr=pe(),zv=$e();function xC(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,dr._)`${t.schemaPath}${(0,dr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,dr._)`${t.schemaPath}${(0,dr.getProperty)(e)}${(0,dr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,zv.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Yr.getSubschema=xC;function kC(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:l,dataPathArr:u,opts:d}=e,b=a.let("data",(0,dr._)`${e.data}${(0,dr.getProperty)(r)}`,!0);c(b),t.errorPath=(0,dr.str)`${l}${(0,zv.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,dr._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(o!==void 0){let l=o instanceof dr.Name?o:a.let("data",o,!0);c(l),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(l){t.data=l,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,l]}}Yr.extendSubschemaData=kC;function $C(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}Yr.extendSubschemaMode=$C});var Hf=Z((o2,jv)=>{"use strict";jv.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var Dv=Z((s2,Lv)=>{"use strict";var Xr=Lv.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};oc(e,n,o,t,"",t)};Xr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Xr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Xr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Xr.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 oc(t,e,r,n,o,s,i,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,l);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in Xr.arrayKeywords)for(var b=0;b<d.length;b++)oc(t,e,r,d[b],o+"/"+u+"/"+b,s,o,u,n,b)}else if(u in Xr.propsKeywords){if(d&&typeof d=="object")for(var m in d)oc(t,e,r,d[m],o+"/"+u+"/"+SC(m),s,o,u,n,m)}else(u in Xr.keywords||t.allKeys&&!(u in Xr.skipKeywords))&&oc(t,e,r,d,o+"/"+u,s,o,u,n)}r(n,o,s,i,a,c,l)}}function SC(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Ks=Z(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.getSchemaRefs=kt.resolveUrl=kt.normalizeId=kt._getFullPath=kt.getFullPath=kt.inlineRef=void 0;var TC=$e(),EC=Hf(),RC=Dv(),PC=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function AC(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Kf(t):e?Mv(t)<=e:!1}kt.inlineRef=AC;var IC=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Kf(t){for(let e in t){if(IC.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Kf)||typeof r=="object"&&Kf(r))return!0}return!1}function Mv(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!PC.has(r)&&(typeof t[r]=="object"&&(0,TC.eachItem)(t[r],n=>e+=Mv(n)),e===1/0))return 1/0}return e}function Uv(t,e="",r){r!==!1&&(e=To(e));let n=t.parse(e);return Zv(t,n)}kt.getFullPath=Uv;function Zv(t,e){return t.serialize(e).split("#")[0]+"#"}kt._getFullPath=Zv;var OC=/#\/?$/;function To(t){return t?t.replace(OC,""):""}kt.normalizeId=To;function CC(t,e,r){return r=To(r),t.resolve(e,r)}kt.resolveUrl=CC;var zC=/^[a-z_][-a-z0-9._]*$/i;function NC(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=To(t[r]||e),s={"":o},i=Uv(n,o,!1),a={},c=new Set;return RC(t,{allKeys:!0},(d,b,m,f)=>{if(f===void 0)return;let y=i+b,v=s[f];typeof d[r]=="string"&&(v=E.call(this,d[r])),R.call(this,d.$anchor),R.call(this,d.$dynamicAnchor),s[b]=v;function E(z){let H=this.opts.uriResolver.resolve;if(z=To(v?H(v,z):z),c.has(z))throw u(z);c.add(z);let Y=this.refs[z];return typeof Y=="string"&&(Y=this.refs[Y]),typeof Y=="object"?l(d,Y.schema,z):z!==To(y)&&(z[0]==="#"?(l(d,a[z],z),a[z]=d):this.refs[z]=y),z}function R(z){if(typeof z=="string"){if(!zC.test(z))throw new Error(`invalid anchor "${z}"`);E.call(this,`#${z}`)}}}),a;function l(d,b,m){if(b!==void 0&&!EC(d,b))throw u(m)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}kt.getSchemaRefs=NC});var Js=Z(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});Qr.getData=Qr.KeywordCxt=Qr.validateFunctionCode=void 0;var Hv=vv(),qv=Hs(),Wf=Mf(),sc=Hs(),jC=Rv(),Ws=Cv(),Gf=Nv(),J=pe(),ie=Tr(),LC=Ks(),Er=$e(),Gs=Vs();function DC(t){if(Wv(t)&&(Jv(t),Gv(t))){ZC(t);return}Kv(t,()=>(0,Hv.topBoolOrEmptySchema)(t))}Qr.validateFunctionCode=DC;function Kv({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,J._)`${ie.default.data}, ${ie.default.valCxt}`,n.$async,()=>{t.code((0,J._)`"use strict"; ${Fv(r,o)}`),UC(t,o),t.code(s)}):t.func(e,(0,J._)`${ie.default.data}, ${MC(o)}`,n.$async,()=>t.code(Fv(r,o)).code(s))}function MC(t){return(0,J._)`{${ie.default.instancePath}="", ${ie.default.parentData}, ${ie.default.parentDataProperty}, ${ie.default.rootData}=${ie.default.data}${t.dynamicRef?(0,J._)`, ${ie.default.dynamicAnchors}={}`:J.nil}}={}`}function UC(t,e){t.if(ie.default.valCxt,()=>{t.var(ie.default.instancePath,(0,J._)`${ie.default.valCxt}.${ie.default.instancePath}`),t.var(ie.default.parentData,(0,J._)`${ie.default.valCxt}.${ie.default.parentData}`),t.var(ie.default.parentDataProperty,(0,J._)`${ie.default.valCxt}.${ie.default.parentDataProperty}`),t.var(ie.default.rootData,(0,J._)`${ie.default.valCxt}.${ie.default.rootData}`),e.dynamicRef&&t.var(ie.default.dynamicAnchors,(0,J._)`${ie.default.valCxt}.${ie.default.dynamicAnchors}`)},()=>{t.var(ie.default.instancePath,(0,J._)`""`),t.var(ie.default.parentData,(0,J._)`undefined`),t.var(ie.default.parentDataProperty,(0,J._)`undefined`),t.var(ie.default.rootData,ie.default.data),e.dynamicRef&&t.var(ie.default.dynamicAnchors,(0,J._)`{}`)})}function ZC(t){let{schema:e,opts:r,gen:n}=t;Kv(t,()=>{r.$comment&&e.$comment&&Xv(t),HC(t),n.let(ie.default.vErrors,null),n.let(ie.default.errors,0),r.unevaluated&&qC(t),Yv(t),WC(t)})}function qC(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,J._)`${r}.evaluated`),e.if((0,J._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,J._)`${t.evaluated}.props`,(0,J._)`undefined`)),e.if((0,J._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,J._)`${t.evaluated}.items`,(0,J._)`undefined`))}function Fv(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,J._)`/*# sourceURL=${r} */`:J.nil}function FC(t,e){if(Wv(t)&&(Jv(t),Gv(t))){BC(t,e);return}(0,Hv.boolOrEmptySchema)(t,e)}function Gv({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function Wv(t){return typeof t.schema!="boolean"}function BC(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Xv(t),KC(t),GC(t);let s=n.const("_errs",ie.default.errors);Yv(t,s),n.var(e,(0,J._)`${s} === ${ie.default.errors}`)}function Jv(t){(0,Er.checkUnknownRules)(t),VC(t)}function Yv(t,e){if(t.opts.jtd)return Bv(t,[],!1,e);let r=(0,qv.getSchemaTypes)(t.schema),n=(0,qv.coerceAndCheckDataType)(t,r);Bv(t,r,!n,e)}function VC(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Er.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function HC(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Er.checkStrictMode)(t,"default is ignored in the schema root")}function KC(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,LC.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function GC(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Xv({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,J._)`${ie.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,J.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,J._)`${ie.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function WC(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,J._)`${ie.default.errors} === 0`,()=>e.return(ie.default.data),()=>e.throw((0,J._)`new ${o}(${ie.default.vErrors})`)):(e.assign((0,J._)`${n}.errors`,ie.default.vErrors),s.unevaluated&&JC(t),e.return((0,J._)`${ie.default.errors} === 0`))}function JC({gen:t,evaluated:e,props:r,items:n}){r instanceof J.Name&&t.assign((0,J._)`${e}.props`,r),n instanceof J.Name&&t.assign((0,J._)`${e}.items`,n)}function Bv(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:l}=t,{RULES:u}=l;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,Er.schemaHasRulesButRef)(s,u))){o.block(()=>ex(t,"$ref",u.all.$ref.definition));return}c.jtd||YC(t,e),o.block(()=>{for(let b of u.rules)d(b);d(u.post)});function d(b){(0,Wf.shouldUseGroup)(s,b)&&(b.type?(o.if((0,sc.checkDataType)(b.type,i,c.strictNumbers)),Vv(t,b),e.length===1&&e[0]===b.type&&r&&(o.else(),(0,sc.reportTypeError)(t)),o.endIf()):Vv(t,b),a||o.if((0,J._)`${ie.default.errors} === ${n||0}`))}}function Vv(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,jC.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Wf.shouldUseRule)(n,s)&&ex(t,s.keyword,s.definition,e.type)})}function YC(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(XC(t,e),t.opts.allowUnionTypes||QC(t,e),ez(t,t.dataTypes))}function XC(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Qv(t.dataTypes,r)||Jf(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),rz(t,e)}}function QC(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Jf(t,"use allowUnionTypes to allow union type keyword")}function ez(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Wf.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>tz(e,i))&&Jf(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function tz(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Qv(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function rz(t,e){let r=[];for(let n of t.dataTypes)Qv(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Jf(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Er.checkStrictMode)(t,e,t.opts.strictTypes)}var ic=class{constructor(e,r,n){if((0,Ws.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Er.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",tx(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ws.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",ie.default.errors))}result(e,r,n){this.failResult((0,J.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,J.not)(e),void 0,r)}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:r}=this;this.fail((0,J._)`${r} !== undefined && (${(0,J.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?Gs.reportExtraError:Gs.reportError)(this,this.def.error,r)}$dataError(){(0,Gs.reportError)(this,this.def.$dataError||Gs.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Gs.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=J.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=J.nil,r=J.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,J.or)((0,J._)`${o} === undefined`,r)),e!==J.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==J.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,J.or)(i(),a());function i(){if(n.length){if(!(r instanceof J.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,J._)`${(0,sc.checkDataTypes)(c,r,s.opts.strictNumbers,sc.DataType.Wrong)}`}return J.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,J._)`!${c}(${r})`}return J.nil}}subschema(e,r){let n=(0,Gf.getSubschema)(this.it,e);(0,Gf.extendSubschemaData)(n,this.it,e),(0,Gf.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return FC(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Er.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Er.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,J.Name)),!0}};Qr.KeywordCxt=ic;function ex(t,e,r,n){let o=new ic(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Ws.funcKeywordCode)(o,r):"macro"in r?(0,Ws.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Ws.funcKeywordCode)(o,r)}var nz=/^\/(?:[^~]|~0|~1)*$/,oz=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function tx(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return ie.default.rootData;if(t[0]==="/"){if(!nz.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ie.default.rootData}else{let l=oz.exec(t);if(!l)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+l[1];if(o=l[2],o==="#"){if(u>=e)throw new Error(c("property/index",u));return n[e-u]}if(u>e)throw new Error(c("data",u));if(s=r[e-u],!o)return s}let i=s,a=o.split("/");for(let l of a)l&&(s=(0,J._)`${s}${(0,J.getProperty)((0,Er.unescapeJsonPointer)(l))}`,i=(0,J._)`${i} && ${s}`);return i;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}Qr.getData=tx});var ac=Z(Xf=>{"use strict";Object.defineProperty(Xf,"__esModule",{value:!0});var Yf=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Xf.default=Yf});var Ys=Z(th=>{"use strict";Object.defineProperty(th,"__esModule",{value:!0});var Qf=Ks(),eh=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Qf.resolveUrl)(e,r,n),this.missingSchema=(0,Qf.normalizeId)((0,Qf.getFullPath)(e,this.missingRef))}};th.default=eh});var lc=Z(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.resolveSchema=Bt.getCompilingSchema=Bt.resolveRef=Bt.compileSchema=Bt.SchemaEnv=void 0;var Qt=pe(),sz=ac(),Nn=Tr(),er=Ks(),rx=$e(),iz=Js(),Eo=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,er.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Bt.SchemaEnv=Eo;function nh(t){let e=nx.call(this,t);if(e)return e;let r=(0,er.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Qt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:sz.default,code:(0,Qt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:Nn.default.data,parentData:Nn.default.parentData,parentDataProperty:Nn.default.parentDataProperty,dataNames:[Nn.default.data],dataPathArr:[Qt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Qt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Qt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Qt._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,iz.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let d=i.toString();u=`${i.scopeRefs(Nn.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let m=new Function(`${Nn.default.self}`,`${Nn.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:m}),m.errors=null,m.schema=t.schema,m.schemaEnv=t,t.$async&&(m.$async=!0),this.opts.code.source===!0&&(m.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:f,items:y}=l;m.evaluated={props:f instanceof Qt.Name?void 0:f,items:y instanceof Qt.Name?void 0:y,dynamicProps:f instanceof Qt.Name,dynamicItems:y instanceof Qt.Name},m.source&&(m.source.evaluated=(0,Qt.stringify)(m.evaluated))}return t.validate=m,t}catch(d){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(t)}}Bt.compileSchema=nh;function az(t,e,r){var n;r=(0,er.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=uz.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new Eo({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=cz.call(this,s)}Bt.resolveRef=az;function cz(t){return(0,er.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:nh.call(this,t)}function nx(t){for(let e of this._compilations)if(lz(e,t))return e}Bt.getCompilingSchema=nx;function lz(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function uz(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||cc.call(this,t,e)}function cc(t,e){let r=this.opts.uriResolver.parse(e),n=(0,er._getFullPath)(this.opts.uriResolver,r),o=(0,er.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return rh.call(this,r,t);let s=(0,er.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=cc.call(this,t,i);return typeof a?.schema!="object"?void 0:rh.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||nh.call(this,i),s===(0,er.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,er.resolveUrl)(this.opts.uriResolver,o,l)),new Eo({schema:a,schemaId:c,root:t,baseId:o})}return rh.call(this,r,i)}}Bt.resolveSchema=cc;var dz=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function rh(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,rx.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!dz.has(a)&&l&&(e=(0,er.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,rx.schemaHasRulesButRef)(r,this.RULES)){let a=(0,er.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=cc.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Eo({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var ox=Z((d2,pz)=>{pz.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}});var ih=Z((p2,ux)=>{"use strict";var fz=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),ix=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),oh=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),ax=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),hz=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function sh(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var mz=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function sx(t){return t.length=0,!0}function gz(t,e,r){if(t.length){let n=sh(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function yz(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=gz;for(let c=0;c<t.length;c++){let l=t[c];if(!(l==="["||l==="]"))if(l===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(l==="%"){if(!a(o,n,r))break;a=sx}else{o.push(l);continue}}return o.length&&(a===sx?r.zone=o.join(""):i?n.push(o.join("")):n.push(sh(o))),r.address=n.join(""),r}function cx(t){if(bz(t,":")<2)return{host:t,isIPV6:!1};let e=yz(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function bz(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function wz(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}var _z={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},vz=/[@/?#:]/g,xz=/[@/?#]/g;function lx(t,e){let r=e?xz:vz;return r.lastIndex=0,t.replace(r,n=>_z[n])}function kz(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(oh(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&ax(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function $z(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(oh(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&ax(s)?e+=s:e+="%"+o,r+=2;continue}}hz(t[r])?e+=t[r]:e+=escape(t[r])}return e}function Sz(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(oh(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function Tz(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!ix(r)){let n=cx(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=lx(r,!1)}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}ux.exports={nonSimpleDomain:mz,recomposeAuthority:Tz,reescapeHostDelimiters:lx,normalizePercentEncoding:kz,normalizePathEncoding:$z,escapePreservingEscapes:Sz,removeDotSegments:wz,isIPv4:ix,isUUID:fz,normalizeIPv6:cx,stringArrayToHexStripped:sh}});var mx=Z((f2,hx)=>{"use strict";var{isUUID:Ez}=ih(),Rz=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Pz=["http","https","ws","wss","urn","urn:uuid"];function Az(t){return Pz.indexOf(t)!==-1}function ah(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function dx(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function px(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function Iz(t){return t.secure=ah(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function Oz(t){if((t.port===(ah(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function Cz(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(Rz);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=ch(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function zz(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=ch(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function Nz(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!Ez(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function jz(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var fx={scheme:"http",domainHost:!0,parse:dx,serialize:px},Lz={scheme:"https",domainHost:fx.domainHost,parse:dx,serialize:px},uc={scheme:"ws",domainHost:!0,parse:Iz,serialize:Oz},Dz={scheme:"wss",domainHost:uc.domainHost,parse:uc.parse,serialize:uc.serialize},Mz={scheme:"urn",parse:Cz,serialize:zz,skipNormalize:!0},Uz={scheme:"urn:uuid",parse:Nz,serialize:jz,skipNormalize:!0},dc={http:fx,https:Lz,ws:uc,wss:Dz,urn:Mz,"urn:uuid":Uz};Object.setPrototypeOf(dc,null);function ch(t){return t&&(dc[t]||dc[t.toLowerCase()])||void 0}hx.exports={wsIsSecure:ah,SCHEMES:dc,isValidSchemeName:Az,getSchemeHandler:ch}});var _x=Z((h2,hc)=>{"use strict";var{normalizeIPv6:Zz,removeDotSegments:Xs,recomposeAuthority:qz,normalizePercentEncoding:Fz,normalizePathEncoding:Bz,escapePreservingEscapes:Vz,reescapeHostDelimiters:Hz,isIPv4:Kz,nonSimpleDomain:Gz}=ih(),{SCHEMES:Wz,getSchemeHandler:yx}=mx();function Jz(t,e){return typeof t=="string"?t=nN(t,e):typeof t=="object"&&(t=fc(jn(t,e),e)),t}function Yz(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=pc(t,n),{parsed:i,malformedAuthorityOrPort:a}=pc(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let c=bx(o,i,n,!0);return n.skipEscape=!0,jn(c,n)}function bx(t,e,r,n){let o={};return n||(t=fc(jn(t,r),r),e=fc(jn(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Xs(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Xs(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Xs(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=Xs(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function Xz(t,e,r){let n=gx(t,r),o=gx(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function jn(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=yx(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=Fz(r.path):(r.path=Vz(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=qz(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=Xs(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var Qz=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,eN=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,tN=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function rN(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function pc(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let i=t.match(eN);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(tN);if(a!==null){let l=a[1],u=l.replace(/[\t\n\r]/g,"");u.length>=2&&(u.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):l.length!==u.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let c=t.match(Qz);if(c){n.scheme=c[1],n.userinfo=c[3],n.host=c[4],n.port=parseInt(c[5],10),n.path=c[6]||"",n.query=c[7],n.fragment=c[8],isNaN(n.port)&&(n.port=c[5]);let l=rN(n,c);if(l!==void 0&&(n.error=n.error||l,o=!0),n.host)if(Kz(n.host)===!1){let b=Zz(n.host);n.host=b.host.toLowerCase(),s=b.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let u=yx(r.scheme||n.scheme);if(!r.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(r.domainHost||u&&u.domainHost)&&s===!1&&Gz(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(d){n.error=n.error||"Host's domain name can not be converted to ASCII: "+d}if((!u||u&&!u.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=Hz(unescape(n.host),s))),n.path&&(n.path=Bz(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}u&&u.parse&&u.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function fc(t,e){return pc(t,e).parsed}function nN(t,e){return wx(t,e).normalized}function wx(t,e){let{parsed:r,malformedAuthorityOrPort:n}=pc(t,e);return{normalized:n?t:jn(r,e),malformedAuthorityOrPort:n}}function gx(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=wx(t,e);return n?void 0:r}if(typeof t=="object")return jn(t,e)}var lh={SCHEMES:Wz,normalize:Jz,resolve:Yz,resolveComponent:bx,equal:Xz,serialize:jn,parse:fc};hc.exports=lh;hc.exports.default=lh;hc.exports.fastUri=lh});var xx=Z(uh=>{"use strict";Object.defineProperty(uh,"__esModule",{value:!0});var vx=_x();vx.code='require("ajv/dist/runtime/uri").default';uh.default=vx});var Ax=Z(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.CodeGen=ot.Name=ot.nil=ot.stringify=ot.str=ot._=ot.KeywordCxt=void 0;var oN=Js();Object.defineProperty(ot,"KeywordCxt",{enumerable:!0,get:function(){return oN.KeywordCxt}});var Ro=pe();Object.defineProperty(ot,"_",{enumerable:!0,get:function(){return Ro._}});Object.defineProperty(ot,"str",{enumerable:!0,get:function(){return Ro.str}});Object.defineProperty(ot,"stringify",{enumerable:!0,get:function(){return Ro.stringify}});Object.defineProperty(ot,"nil",{enumerable:!0,get:function(){return Ro.nil}});Object.defineProperty(ot,"Name",{enumerable:!0,get:function(){return Ro.Name}});Object.defineProperty(ot,"CodeGen",{enumerable:!0,get:function(){return Ro.CodeGen}});var sN=ac(),Ex=Ys(),iN=Df(),Qs=lc(),aN=pe(),ei=Ks(),mc=Hs(),ph=$e(),kx=ox(),cN=xx(),Rx=(t,e)=>new RegExp(t,e);Rx.code="new RegExp";var lN=["removeAdditional","useDefaults","coerceTypes"],uN=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),dN={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."},pN={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},$x=200;function fN(t){var e,r,n,o,s,i,a,c,l,u,d,b,m,f,y,v,E,R,z,H,Y,He,Qe,Rr,nr;let nn=t.strict,Mo=(e=t.code)===null||e===void 0?void 0:e.optimize,Pr=Mo===!0||Mo===void 0?1:Mo||0,Un=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Rx,Uo=(o=t.uriResolver)!==null&&o!==void 0?o:cN.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:nn)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:nn)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:nn)!==null&&u!==void 0?u:"log",strictTuples:(b=(d=t.strictTuples)!==null&&d!==void 0?d:nn)!==null&&b!==void 0?b:"log",strictRequired:(f=(m=t.strictRequired)!==null&&m!==void 0?m:nn)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:Pr,regExp:Un}:{optimize:Pr,regExp:Un},loopRequired:(y=t.loopRequired)!==null&&y!==void 0?y:$x,loopEnum:(v=t.loopEnum)!==null&&v!==void 0?v:$x,meta:(E=t.meta)!==null&&E!==void 0?E:!0,messages:(R=t.messages)!==null&&R!==void 0?R:!0,inlineRefs:(z=t.inlineRefs)!==null&&z!==void 0?z:!0,schemaId:(H=t.schemaId)!==null&&H!==void 0?H:"$id",addUsedSchema:(Y=t.addUsedSchema)!==null&&Y!==void 0?Y:!0,validateSchema:(He=t.validateSchema)!==null&&He!==void 0?He:!0,validateFormats:(Qe=t.validateFormats)!==null&&Qe!==void 0?Qe:!0,unicodeRegExp:(Rr=t.unicodeRegExp)!==null&&Rr!==void 0?Rr:!0,int32range:(nr=t.int32range)!==null&&nr!==void 0?nr:!0,uriResolver:Uo}}var ti=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...fN(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new aN.ValueScope({scope:{},prefixes:uN,es5:r,lines:n}),this.logger=wN(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,iN.getRules)(),Sx.call(this,dN,e,"NOT SUPPORTED"),Sx.call(this,pN,e,"DEPRECATED","warn"),this._metaOpts=yN.call(this),e.formats&&mN.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&gN.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),hN.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=kx;n==="id"&&(o={...kx},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(u,d){await s.call(this,u.$schema);let b=this._addSchema(u,d);return b.validate||i.call(this,b)}async function s(u){u&&!this.getSchema(u)&&await o.call(this,{$ref:u},!0)}async function i(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof Ex.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,u)}}function a({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function c(u){let d=await l.call(this,u);this.refs[u]||await s.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,r)}async function l(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,ei.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new 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 o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=Tx.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Qs.SchemaEnv({schema:{},schemaId:n});if(r=Qs.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}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 r=Tx.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,ei.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(vN.call(this,n,r),!r)return(0,ph.eachItem)(n,s=>dh.call(this,s)),this;kN.call(this,r);let o={...r,type:(0,mc.getJSONTypes)(r.type),schemaType:(0,mc.getJSONTypes)(r.schemaType)};return(0,ph.eachItem)(n,o.type.length===0?s=>dh.call(this,s,o):s=>o.type.forEach(i=>dh.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=i[a];l&&u&&(i[a]=Px(u))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,ei.normalizeId)(i||n);let l=ei.getSchemaRefs.call(this,e,n);return c=new Qs.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:l}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Qs.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{Qs.compileSchema.call(this,e)}finally{this.opts=r}}};ti.ValidationError=sN.default;ti.MissingRefError=Ex.default;ot.default=ti;function Sx(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function Tx(t){return t=(0,ei.normalizeId)(t),this.schemas[t]||this.refs[t]}function hN(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function mN(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function gN(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function yN(){let t={...this.opts};for(let e of lN)delete t[e];return t}var bN={log(){},warn(){},error(){}};function wN(t){if(t===!1)return bN;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var _N=/^[a-z_$][a-z0-9_$:-]*$/i;function vN(t,e){let{RULES:r}=this;if((0,ph.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!_N.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function dh(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,mc.getJSONTypes)(e.type),schemaType:(0,mc.getJSONTypes)(e.schemaType)}};e.before?xN.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function xN(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function kN(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Px(e)),t.validateSchema=this.compile(e,!0))}var $N={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Px(t){return{anyOf:[t,$N]}}});var Ix=Z(fh=>{"use strict";Object.defineProperty(fh,"__esModule",{value:!0});var SN={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};fh.default=SN});var Nx=Z(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.callRef=Ln.getValidate=void 0;var TN=Ys(),Ox=Ft(),$t=pe(),Po=Tr(),Cx=lc(),gc=$e(),EN={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:l}=s;if((r==="#"||r==="#/")&&o===l.baseId)return d();let u=Cx.resolveRef.call(c,l,o,r);if(u===void 0)throw new TN.default(n.opts.uriResolver,o,r);if(u instanceof Cx.SchemaEnv)return b(u);return m(u);function d(){if(s===l)return yc(t,i,s,s.$async);let f=e.scopeValue("root",{ref:l});return yc(t,(0,$t._)`${f}.validate`,l,l.$async)}function b(f){let y=zx(t,f);yc(t,y,f,f.$async)}function m(f){let y=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,$t.stringify)(f)}:{ref:f}),v=e.name("valid"),E=t.subschema({schema:f,dataTypes:[],schemaPath:$t.nil,topSchemaRef:y,errSchemaPath:r},v);t.mergeEvaluated(E),t.ok(v)}}};function zx(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,$t._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Ln.getValidate=zx;function yc(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?Po.default.this:$t.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let f=o.let("valid");o.try(()=>{o.code((0,$t._)`await ${(0,Ox.callValidateCode)(t,e,l)}`),m(e),i||o.assign(f,!0)},y=>{o.if((0,$t._)`!(${y} instanceof ${s.ValidationError})`,()=>o.throw(y)),b(y),i||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,Ox.callValidateCode)(t,e,l),()=>m(e),()=>b(e))}function b(f){let y=(0,$t._)`${f}.errors`;o.assign(Po.default.vErrors,(0,$t._)`${Po.default.vErrors} === null ? ${y} : ${Po.default.vErrors}.concat(${y})`),o.assign(Po.default.errors,(0,$t._)`${Po.default.vErrors}.length`)}function m(f){var y;if(!s.opts.unevaluated)return;let v=(y=r?.validate)===null||y===void 0?void 0:y.evaluated;if(s.props!==!0)if(v&&!v.dynamicProps)v.props!==void 0&&(s.props=gc.mergeEvaluated.props(o,v.props,s.props));else{let E=o.var("props",(0,$t._)`${f}.evaluated.props`);s.props=gc.mergeEvaluated.props(o,E,s.props,$t.Name)}if(s.items!==!0)if(v&&!v.dynamicItems)v.items!==void 0&&(s.items=gc.mergeEvaluated.items(o,v.items,s.items));else{let E=o.var("items",(0,$t._)`${f}.evaluated.items`);s.items=gc.mergeEvaluated.items(o,E,s.items,$t.Name)}}}Ln.callRef=yc;Ln.default=EN});var jx=Z(hh=>{"use strict";Object.defineProperty(hh,"__esModule",{value:!0});var RN=Ix(),PN=Nx(),AN=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",RN.default,PN.default];hh.default=AN});var Lx=Z(mh=>{"use strict";Object.defineProperty(mh,"__esModule",{value:!0});var bc=pe(),en=bc.operators,wc={maximum:{okStr:"<=",ok:en.LTE,fail:en.GT},minimum:{okStr:">=",ok:en.GTE,fail:en.LT},exclusiveMaximum:{okStr:"<",ok:en.LT,fail:en.GTE},exclusiveMinimum:{okStr:">",ok:en.GT,fail:en.LTE}},IN={message:({keyword:t,schemaCode:e})=>(0,bc.str)`must be ${wc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,bc._)`{comparison: ${wc[t].okStr}, limit: ${e}}`},ON={keyword:Object.keys(wc),type:"number",schemaType:"number",$data:!0,error:IN,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,bc._)`${r} ${wc[e].fail} ${n} || isNaN(${r})`)}};mh.default=ON});var Dx=Z(gh=>{"use strict";Object.defineProperty(gh,"__esModule",{value:!0});var ri=pe(),CN={message:({schemaCode:t})=>(0,ri.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ri._)`{multipleOf: ${t}}`},zN={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:CN,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,ri._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,ri._)`${i} !== parseInt(${i})`;t.fail$data((0,ri._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};gh.default=zN});var Ux=Z(yh=>{"use strict";Object.defineProperty(yh,"__esModule",{value:!0});function Mx(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}yh.default=Mx;Mx.code='require("ajv/dist/runtime/ucs2length").default'});var Zx=Z(bh=>{"use strict";Object.defineProperty(bh,"__esModule",{value:!0});var Dn=pe(),NN=$e(),jN=Ux(),LN={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Dn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Dn._)`{limit: ${t}}`},DN={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:LN,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Dn.operators.GT:Dn.operators.LT,i=o.opts.unicode===!1?(0,Dn._)`${r}.length`:(0,Dn._)`${(0,NN.useFunc)(t.gen,jN.default)}(${r})`;t.fail$data((0,Dn._)`${i} ${s} ${n}`)}};bh.default=DN});var qx=Z(wh=>{"use strict";Object.defineProperty(wh,"__esModule",{value:!0});var MN=Ft(),UN=$e(),Ao=pe(),ZN={message:({schemaCode:t})=>(0,Ao.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Ao._)`{pattern: ${t}}`},qN={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:ZN,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,l=c.code==="new RegExp"?(0,Ao._)`new RegExp`:(0,UN.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,Ao._)`${l}(${s}, ${a}).test(${r})`),()=>e.assign(u,!1)),t.fail$data((0,Ao._)`!${u}`)}else{let c=(0,MN.usePattern)(t,o);t.fail$data((0,Ao._)`!${c}.test(${r})`)}}};wh.default=qN});var Fx=Z(_h=>{"use strict";Object.defineProperty(_h,"__esModule",{value:!0});var ni=pe(),FN={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,ni.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,ni._)`{limit: ${t}}`},BN={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:FN,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?ni.operators.GT:ni.operators.LT;t.fail$data((0,ni._)`Object.keys(${r}).length ${o} ${n}`)}};_h.default=BN});var Bx=Z(vh=>{"use strict";Object.defineProperty(vh,"__esModule",{value:!0});var oi=Ft(),si=pe(),VN=$e(),HN={message:({params:{missingProperty:t}})=>(0,si.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,si._)`{missingProperty: ${t}}`},KN={keyword:"required",type:"object",schemaType:"array",$data:!0,error:HN,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?l():u(),a.strictRequired){let m=t.parentSchema.properties,{definedProperties:f}=t.it;for(let y of r)if(m?.[y]===void 0&&!f.has(y)){let v=i.schemaEnv.baseId+i.errSchemaPath,E=`required property "${y}" is not defined at "${v}" (strictRequired)`;(0,VN.checkStrictMode)(i,E,i.opts.strictRequired)}}function l(){if(c||s)t.block$data(si.nil,d);else for(let m of r)(0,oi.checkReportMissingProp)(t,m)}function u(){let m=e.let("missing");if(c||s){let f=e.let("valid",!0);t.block$data(f,()=>b(m,f)),t.ok(f)}else e.if((0,oi.checkMissingProp)(t,r,m)),(0,oi.reportMissingProp)(t,m),e.else()}function d(){e.forOf("prop",n,m=>{t.setParams({missingProperty:m}),e.if((0,oi.noPropertyInData)(e,o,m,a.ownProperties),()=>t.error())})}function b(m,f){t.setParams({missingProperty:m}),e.forOf(m,n,()=>{e.assign(f,(0,oi.propertyInData)(e,o,m,a.ownProperties)),e.if((0,si.not)(f),()=>{t.error(),e.break()})},si.nil)}}};vh.default=KN});var Vx=Z(xh=>{"use strict";Object.defineProperty(xh,"__esModule",{value:!0});var ii=pe(),GN={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,ii.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,ii._)`{limit: ${t}}`},WN={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:GN,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?ii.operators.GT:ii.operators.LT;t.fail$data((0,ii._)`${r}.length ${o} ${n}`)}};xh.default=WN});var _c=Z(kh=>{"use strict";Object.defineProperty(kh,"__esModule",{value:!0});var Hx=Hf();Hx.code='require("ajv/dist/runtime/equal").default';kh.default=Hx});var Kx=Z(Sh=>{"use strict";Object.defineProperty(Sh,"__esModule",{value:!0});var $h=Hs(),st=pe(),JN=$e(),YN=_c(),XN={message:({params:{i:t,j:e}})=>(0,st.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,st._)`{i: ${t}, j: ${e}}`},QN={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:XN,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),l=s.items?(0,$h.getSchemaTypes)(s.items):[];t.block$data(c,u,(0,st._)`${i} === false`),t.ok(c);function u(){let f=e.let("i",(0,st._)`${r}.length`),y=e.let("j");t.setParams({i:f,j:y}),e.assign(c,!0),e.if((0,st._)`${f} > 1`,()=>(d()?b:m)(f,y))}function d(){return l.length>0&&!l.some(f=>f==="object"||f==="array")}function b(f,y){let v=e.name("item"),E=(0,$h.checkDataTypes)(l,v,a.opts.strictNumbers,$h.DataType.Wrong),R=e.const("indices",(0,st._)`{}`);e.for((0,st._)`;${f}--;`,()=>{e.let(v,(0,st._)`${r}[${f}]`),e.if(E,(0,st._)`continue`),l.length>1&&e.if((0,st._)`typeof ${v} == "string"`,(0,st._)`${v} += "_"`),e.if((0,st._)`typeof ${R}[${v}] == "number"`,()=>{e.assign(y,(0,st._)`${R}[${v}]`),t.error(),e.assign(c,!1).break()}).code((0,st._)`${R}[${v}] = ${f}`)})}function m(f,y){let v=(0,JN.useFunc)(e,YN.default),E=e.name("outer");e.label(E).for((0,st._)`;${f}--;`,()=>e.for((0,st._)`${y} = ${f}; ${y}--;`,()=>e.if((0,st._)`${v}(${r}[${f}], ${r}[${y}])`,()=>{t.error(),e.assign(c,!1).break(E)})))}}};Sh.default=QN});var Gx=Z(Eh=>{"use strict";Object.defineProperty(Eh,"__esModule",{value:!0});var Th=pe(),e1=$e(),t1=_c(),r1={message:"must be equal to constant",params:({schemaCode:t})=>(0,Th._)`{allowedValue: ${t}}`},n1={keyword:"const",$data:!0,error:r1,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Th._)`!${(0,e1.useFunc)(e,t1.default)}(${r}, ${o})`):t.fail((0,Th._)`${s} !== ${r}`)}};Eh.default=n1});var Wx=Z(Rh=>{"use strict";Object.defineProperty(Rh,"__esModule",{value:!0});var ai=pe(),o1=$e(),s1=_c(),i1={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,ai._)`{allowedValues: ${t}}`},a1={keyword:"enum",schemaType:"array",$data:!0,error:i1,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,l=()=>c??(c=(0,o1.useFunc)(e,s1.default)),u;if(a||n)u=e.let("valid"),t.block$data(u,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let m=e.const("vSchema",s);u=(0,ai.or)(...o.map((f,y)=>b(m,y)))}t.pass(u);function d(){e.assign(u,!1),e.forOf("v",s,m=>e.if((0,ai._)`${l()}(${r}, ${m})`,()=>e.assign(u,!0).break()))}function b(m,f){let y=o[f];return typeof y=="object"&&y!==null?(0,ai._)`${l()}(${r}, ${m}[${f}])`:(0,ai._)`${r} === ${y}`}}};Rh.default=a1});var Jx=Z(Ph=>{"use strict";Object.defineProperty(Ph,"__esModule",{value:!0});var c1=Lx(),l1=Dx(),u1=Zx(),d1=qx(),p1=Fx(),f1=Bx(),h1=Vx(),m1=Kx(),g1=Gx(),y1=Wx(),b1=[c1.default,l1.default,u1.default,d1.default,p1.default,f1.default,h1.default,m1.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},g1.default,y1.default];Ph.default=b1});var Ih=Z(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});ci.validateAdditionalItems=void 0;var Mn=pe(),Ah=$e(),w1={message:({params:{len:t}})=>(0,Mn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Mn._)`{limit: ${t}}`},_1={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:w1,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Ah.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Yx(t,n)}};function Yx(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Mn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Mn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Ah.alwaysValidSchema)(i,n)){let l=r.var("valid",(0,Mn._)`${a} <= ${e.length}`);r.if((0,Mn.not)(l),()=>c(l)),t.ok(l)}function c(l){r.forRange("i",e.length,a,u=>{t.subschema({keyword:s,dataProp:u,dataPropType:Ah.Type.Num},l),i.allErrors||r.if((0,Mn.not)(l),()=>r.break())})}}ci.validateAdditionalItems=Yx;ci.default=_1});var Oh=Z(li=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});li.validateTuple=void 0;var Xx=pe(),vc=$e(),v1=Ft(),x1={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Qx(t,"additionalItems",e);r.items=!0,!(0,vc.alwaysValidSchema)(r,e)&&t.ok((0,v1.validateArray)(t))}};function Qx(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;u(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=vc.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,Xx._)`${s}.length`);r.forEach((d,b)=>{(0,vc.alwaysValidSchema)(a,d)||(n.if((0,Xx._)`${l} > ${b}`,()=>t.subschema({keyword:i,schemaProp:b,dataProp:b},c)),t.ok(c))});function u(d){let{opts:b,errSchemaPath:m}=a,f=r.length,y=f===d.minItems&&(f===d.maxItems||d[e]===!1);if(b.strictTuples&&!y){let v=`"${i}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${m}"`;(0,vc.checkStrictMode)(a,v,b.strictTuples)}}}li.validateTuple=Qx;li.default=x1});var ek=Z(Ch=>{"use strict";Object.defineProperty(Ch,"__esModule",{value:!0});var k1=Oh(),$1={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,k1.validateTuple)(t,"items")};Ch.default=$1});var rk=Z(zh=>{"use strict";Object.defineProperty(zh,"__esModule",{value:!0});var tk=pe(),S1=$e(),T1=Ft(),E1=Ih(),R1={message:({params:{len:t}})=>(0,tk.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,tk._)`{limit: ${t}}`},P1={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:R1,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,S1.alwaysValidSchema)(n,e)&&(o?(0,E1.validateAdditionalItems)(t,o):t.ok((0,T1.validateArray)(t)))}};zh.default=P1});var nk=Z(Nh=>{"use strict";Object.defineProperty(Nh,"__esModule",{value:!0});var Vt=pe(),xc=$e(),A1={message:({params:{min:t,max:e}})=>e===void 0?(0,Vt.str)`must contain at least ${t} valid item(s)`:(0,Vt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Vt._)`{minContains: ${t}}`:(0,Vt._)`{minContains: ${t}, maxContains: ${e}}`},I1={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:A1,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:l}=n;s.opts.next?(i=c===void 0?1:c,a=l):i=1;let u=e.const("len",(0,Vt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,xc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,xc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,xc.alwaysValidSchema)(s,r)){let y=(0,Vt._)`${u} >= ${i}`;a!==void 0&&(y=(0,Vt._)`${y} && ${u} <= ${a}`),t.pass(y);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?m(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,Vt._)`${o}.length > 0`,b)):(e.let(d,!1),b()),t.result(d,()=>t.reset());function b(){let y=e.name("_valid"),v=e.let("count",0);m(y,()=>e.if(y,()=>f(v)))}function m(y,v){e.forRange("i",0,u,E=>{t.subschema({keyword:"contains",dataProp:E,dataPropType:xc.Type.Num,compositeRule:!0},y),v()})}function f(y){e.code((0,Vt._)`${y}++`),a===void 0?e.if((0,Vt._)`${y} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,Vt._)`${y} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,Vt._)`${y} >= ${i}`,()=>e.assign(d,!0)))}}};Nh.default=I1});var ik=Z(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.validateSchemaDeps=pr.validatePropertyDeps=pr.error=void 0;var jh=pe(),O1=$e(),ui=Ft();pr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,jh.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,jh._)`{property: ${t},
990
1137
  missingProperty: ${n},
991
1138
  depsCount: ${e},
992
- deps: ${r}}`};var QN={keyword:"dependencies",type:"object",schemaType:"object",error:pr.error,code(t){let[e,r]=e1(t);Mx(t,e),Dx(t,r)}};function e1({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function Mx(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,ni.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let l of a)(0,ni.checkReportMissingProp)(t,l)}):(r.if((0,Rh._)`${c} && (${(0,ni.checkMissingProp)(t,a,s)})`),(0,ni.reportMissingProp)(t,s),r.else())}}pr.validatePropertyDeps=Mx;function Dx(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,XN.alwaysValidSchema)(s,e[a])||(r.if((0,ni.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}pr.validateSchemaDeps=Dx;pr.default=QN});var qx=Z(Ph=>{"use strict";Object.defineProperty(Ph,"__esModule",{value:!0});var Zx=ue(),t1=$e(),r1={message:"property name must be valid",params:({params:t})=>(0,Zx._)`{propertyName: ${t.propertyName}}`},n1={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:r1,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,t1.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,Zx.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Ph.default=n1});var Ih=Z(Ah=>{"use strict";Object.defineProperty(Ah,"__esModule",{value:!0});var gc=Zt(),er=ue(),o1=Tr(),yc=$e(),s1={message:"must NOT have additional properties",params:({params:t})=>(0,er._)`{additionalProperty: ${t.additionalProperty}}`},i1={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:s1,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,yc.alwaysValidSchema)(i,r))return;let l=(0,gc.allSchemaProperties)(n.properties),u=(0,gc.allSchemaProperties)(n.patternProperties);d(),t.ok((0,er._)`${s} === ${o1.default.errors}`);function d(){e.forIn("key",o,v=>{!l.length&&!u.length?f(v):e.if(b(v),()=>f(v))})}function b(v){let E;if(l.length>8){let R=(0,yc.schemaRefOrVal)(i,n.properties,"properties");E=(0,gc.isOwnProperty)(e,R,v)}else l.length?E=(0,er.or)(...l.map(R=>(0,er._)`${v} === ${R}`)):E=er.nil;return u.length&&(E=(0,er.or)(E,...u.map(R=>(0,er._)`${(0,gc.usePattern)(t,R)}.test(${v})`))),(0,er.not)(E)}function m(v){e.code((0,er._)`delete ${o}[${v}]`)}function f(v){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){m(v);return}if(r===!1){t.setParams({additionalProperty:v}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,yc.alwaysValidSchema)(i,r)){let E=e.name("valid");c.removeAdditional==="failing"?(y(v,E,!1),e.if((0,er.not)(E),()=>{t.reset(),m(v)})):(y(v,E),a||e.if((0,er.not)(E),()=>e.break()))}}function y(v,E,R){let z={keyword:"additionalProperties",dataProp:v,dataPropType:yc.Type.Str};R===!1&&Object.assign(z,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(z,E)}}};Ah.default=i1});var Vx=Z(Ch=>{"use strict";Object.defineProperty(Ch,"__esModule",{value:!0});var a1=Fs(),Fx=Zt(),Oh=$e(),Bx=Ih(),c1={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Bx.default.code(new a1.KeywordCxt(s,Bx.default,"additionalProperties"));let i=(0,Fx.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Oh.mergeEvaluated.props(e,(0,Oh.toHash)(i),s.props));let a=i.filter(d=>!(0,Oh.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)l(d)?u(d):(e.if((0,Fx.propertyInData)(e,o,d,s.opts.ownProperties)),u(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function l(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function u(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Ch.default=c1});var Gx=Z(zh=>{"use strict";Object.defineProperty(zh,"__esModule",{value:!0});var Hx=Zt(),bc=ue(),Kx=$e(),Wx=$e(),l1={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,Hx.allSchemaProperties)(r),c=a.filter(y=>(0,Kx.alwaysValidSchema)(s,r[y]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=i.strictSchema&&!i.allowMatchingProperties&&o.properties,u=e.name("valid");s.props!==!0&&!(s.props instanceof bc.Name)&&(s.props=(0,Wx.evaluatedPropsToName)(e,s.props));let{props:d}=s;b();function b(){for(let y of a)l&&m(y),s.allErrors?f(y):(e.var(u,!0),f(y),e.if(u))}function m(y){for(let v in l)new RegExp(y).test(v)&&(0,Kx.checkStrictMode)(s,`property ${v} matches pattern ${y} (use allowMatchingProperties)`)}function f(y){e.forIn("key",n,v=>{e.if((0,bc._)`${(0,Hx.usePattern)(t,y)}.test(${v})`,()=>{let E=c.includes(y);E||t.subschema({keyword:"patternProperties",schemaProp:y,dataProp:v,dataPropType:Wx.Type.Str},u),s.opts.unevaluated&&d!==!0?e.assign((0,bc._)`${d}[${v}]`,!0):!E&&!s.allErrors&&e.if((0,bc.not)(u),()=>e.break())})})}}};zh.default=l1});var Jx=Z(Nh=>{"use strict";Object.defineProperty(Nh,"__esModule",{value:!0});var u1=$e(),d1={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,u1.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Nh.default=d1});var Yx=Z(jh=>{"use strict";Object.defineProperty(jh,"__esModule",{value:!0});var p1=Zt(),f1={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:p1.validateUnion,error:{message:"must match a schema in anyOf"}};jh.default=f1});var Xx=Z(Lh=>{"use strict";Object.defineProperty(Lh,"__esModule",{value:!0});var wc=ue(),h1=$e(),m1={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,wc._)`{passingSchemas: ${t.passing}}`},g1={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:m1,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(l),t.result(i,()=>t.reset(),()=>t.error(!0));function l(){s.forEach((u,d)=>{let b;(0,h1.alwaysValidSchema)(o,u)?e.var(c,!0):b=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,wc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,wc._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),b&&t.mergeEvaluated(b,wc.Name)})})}}};Lh.default=g1});var Qx=Z(Mh=>{"use strict";Object.defineProperty(Mh,"__esModule",{value:!0});var y1=$e(),b1={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,y1.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Mh.default=b1});var rk=Z(Dh=>{"use strict";Object.defineProperty(Dh,"__esModule",{value:!0});var _c=ue(),tk=$e(),w1={message:({params:t})=>(0,_c.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,_c._)`{failingKeyword: ${t.ifClause}}`},_1={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:w1,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,tk.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=ek(n,"then"),s=ek(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,l("then",u),l("else",u))}else o?e.if(a,l("then")):e.if((0,_c.not)(a),l("else"));t.pass(i,()=>t.error(!0));function c(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function l(u,d){return()=>{let b=t.subschema({keyword:u},a);e.assign(i,a),t.mergeValidEvaluated(b,i),d?e.assign(d,(0,_c._)`${u}`):t.setParams({ifClause:u})}}}};function ek(t,e){let r=t.schema[e];return r!==void 0&&!(0,tk.alwaysValidSchema)(t,r)}Dh.default=_1});var nk=Z(Uh=>{"use strict";Object.defineProperty(Uh,"__esModule",{value:!0});var v1=$e(),x1={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,v1.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Uh.default=x1});var ok=Z(Zh=>{"use strict";Object.defineProperty(Zh,"__esModule",{value:!0});var k1=kh(),$1=zx(),S1=$h(),T1=jx(),E1=Lx(),R1=Ux(),P1=qx(),A1=Ih(),I1=Vx(),O1=Gx(),C1=Jx(),z1=Yx(),N1=Xx(),j1=Qx(),L1=rk(),M1=nk();function D1(t=!1){let e=[C1.default,z1.default,N1.default,j1.default,L1.default,M1.default,P1.default,A1.default,R1.default,I1.default,O1.default];return t?e.push($1.default,T1.default):e.push(k1.default,S1.default),e.push(E1.default),e}Zh.default=D1});var sk=Z(qh=>{"use strict";Object.defineProperty(qh,"__esModule",{value:!0});var Be=ue(),U1={message:({schemaCode:t})=>(0,Be.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Be._)`{format: ${t}}`},Z1={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:U1,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;o?b():m();function b(){let f=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),y=r.const("fDef",(0,Be._)`${f}[${i}]`),v=r.let("fType"),E=r.let("format");r.if((0,Be._)`typeof ${y} == "object" && !(${y} instanceof RegExp)`,()=>r.assign(v,(0,Be._)`${y}.type || "string"`).assign(E,(0,Be._)`${y}.validate`),()=>r.assign(v,(0,Be._)`"string"`).assign(E,y)),t.fail$data((0,Be.or)(R(),z()));function R(){return c.strictSchema===!1?Be.nil:(0,Be._)`${i} && !${E}`}function z(){let V=u.$async?(0,Be._)`(${y}.async ? await ${E}(${n}) : ${E}(${n}))`:(0,Be._)`${E}(${n})`,J=(0,Be._)`(typeof ${E} == "function" ? ${V} : ${E}.test(${n}))`;return(0,Be._)`${E} && ${E} !== true && ${v} === ${e} && !${J}`}}function m(){let f=d.formats[s];if(!f){R();return}if(f===!0)return;let[y,v,E]=z(f);y===e&&t.pass(V());function R(){if(c.strictSchema===!1){d.logger.warn(J());return}throw new Error(J());function J(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function z(J){let He=J instanceof RegExp?(0,Be.regexpCode)(J):c.code.formats?(0,Be._)`${c.code.formats}${(0,Be.getProperty)(s)}`:void 0,Xe=r.scopeValue("formats",{key:s,ref:J,code:He});return typeof J=="object"&&!(J instanceof RegExp)?[J.type||"string",J.validate,(0,Be._)`${Xe}.validate`]:["string",J,Xe]}function V(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Be._)`await ${E}(${n})`}return typeof v=="function"?(0,Be._)`${E}(${n})`:(0,Be._)`${E}.test(${n})`}}}};qh.default=Z1});var ik=Z(Fh=>{"use strict";Object.defineProperty(Fh,"__esModule",{value:!0});var q1=sk(),F1=[q1.default];Fh.default=F1});var ak=Z(Po=>{"use strict";Object.defineProperty(Po,"__esModule",{value:!0});Po.contentVocabulary=Po.metadataVocabulary=void 0;Po.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Po.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var lk=Z(Bh=>{"use strict";Object.defineProperty(Bh,"__esModule",{value:!0});var B1=gx(),V1=Ax(),H1=ok(),K1=ik(),ck=ak(),W1=[B1.default,V1.default,(0,H1.default)(),K1.default,ck.metadataVocabulary,ck.contentVocabulary];Bh.default=W1});var dk=Z(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});vc.DiscrError=void 0;var uk;(function(t){t.Tag="tag",t.Mapping="mapping"})(uk||(vc.DiscrError=uk={}))});var fk=Z(Hh=>{"use strict";Object.defineProperty(Hh,"__esModule",{value:!0});var Ao=ue(),Vh=dk(),pk=rc(),G1=Bs(),J1=$e(),Y1={message:({params:{discrError:t,tagName:e}})=>t===Vh.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Ao._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},X1={keyword:"discriminator",type:"object",schemaType:"object",error:Y1,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,Ao._)`${r}${(0,Ao.getProperty)(a)}`);e.if((0,Ao._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:Vh.DiscrError.Tag,tag:l,tagName:a})),t.ok(c);function u(){let m=b();e.if(!1);for(let f in m)e.elseIf((0,Ao._)`${l} === ${f}`),e.assign(c,d(m[f]));e.else(),t.error(!1,{discrError:Vh.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function d(m){let f=e.name("valid"),y=t.subschema({keyword:"oneOf",schemaProp:m},f);return t.mergeEvaluated(y,Ao.Name),f}function b(){var m;let f={},y=E(o),v=!0;for(let V=0;V<i.length;V++){let J=i[V];if(J?.$ref&&!(0,J1.schemaHasRulesButRef)(J,s.self.RULES)){let Xe=J.$ref;if(J=pk.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Xe),J instanceof pk.SchemaEnv&&(J=J.schema),J===void 0)throw new G1.default(s.opts.uriResolver,s.baseId,Xe)}let He=(m=J?.properties)===null||m===void 0?void 0:m[a];if(typeof He!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);v=v&&(y||E(J)),R(He,V)}if(!v)throw new Error(`discriminator: "${a}" must be required`);return f;function E({required:V}){return Array.isArray(V)&&V.includes(a)}function R(V,J){if(V.const)z(V.const,J);else if(V.enum)for(let He of V.enum)z(He,J);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function z(V,J){if(typeof V!="string"||V in f)throw new Error(`discriminator: "${a}" values must be unique strings`);f[V]=J}}}};Hh.default=X1});var hk=Z((c2,Q1)=>{Q1.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}});var Wh=Z((Le,Kh)=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.MissingRefError=Le.ValidationError=Le.CodeGen=Le.Name=Le.nil=Le.stringify=Le.str=Le._=Le.KeywordCxt=Le.Ajv=void 0;var ej=ux(),tj=lk(),rj=fk(),mk=hk(),nj=["/properties"],xc="http://json-schema.org/draft-07/schema",Io=class extends ej.default{_addVocabularies(){super._addVocabularies(),tj.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(rj.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(mk,nj):mk;this.addMetaSchema(e,xc,!1),this.refs["http://json-schema.org/schema"]=xc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(xc)?xc:void 0)}};Le.Ajv=Io;Kh.exports=Le=Io;Kh.exports.Ajv=Io;Object.defineProperty(Le,"__esModule",{value:!0});Le.default=Io;var oj=Fs();Object.defineProperty(Le,"KeywordCxt",{enumerable:!0,get:function(){return oj.KeywordCxt}});var Oo=ue();Object.defineProperty(Le,"_",{enumerable:!0,get:function(){return Oo._}});Object.defineProperty(Le,"str",{enumerable:!0,get:function(){return Oo.str}});Object.defineProperty(Le,"stringify",{enumerable:!0,get:function(){return Oo.stringify}});Object.defineProperty(Le,"nil",{enumerable:!0,get:function(){return Oo.nil}});Object.defineProperty(Le,"Name",{enumerable:!0,get:function(){return Oo.Name}});Object.defineProperty(Le,"CodeGen",{enumerable:!0,get:function(){return Oo.CodeGen}});var sj=ec();Object.defineProperty(Le,"ValidationError",{enumerable:!0,get:function(){return sj.default}});var ij=Bs();Object.defineProperty(Le,"MissingRefError",{enumerable:!0,get:function(){return ij.default}})});var kk=Z(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.formatNames=hr.fastFormats=hr.fullFormats=void 0;function fr(t,e){return{validate:t,compare:e}}hr.fullFormats={date:fr(wk,Xh),time:fr(Jh(!0),Qh),"date-time":fr(gk(!0),vk),"iso-time":fr(Jh(),_k),"iso-date-time":fr(gk(),xk),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:pj,"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:wj,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:fj,int32:{type:"number",validate:gj},int64:{type:"number",validate:yj},float:{type:"number",validate:bk},double:{type:"number",validate:bk},password:!0,binary:!0};hr.fastFormats={...hr.fullFormats,date:fr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Xh),time:fr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Qh),"date-time":fr(/^\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,vk),"iso-time":fr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,_k),"iso-date-time":fr(/^\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,xk),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};hr.formatNames=Object.keys(hr.fullFormats);function aj(t){return t%4===0&&(t%100!==0||t%400===0)}var cj=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,lj=[0,31,28,31,30,31,30,31,31,30,31,30,31];function wk(t){let e=cj.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&aj(r)?29:lj[n])}function Xh(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Gh=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Jh(t){return function(r){let n=Gh.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-u*c,b=o-l*c-(d<0?1:0);return(b===23||b===-1)&&(d===59||d===-1)&&i<61}}function Qh(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function _k(t,e){if(!(t&&e))return;let r=Gh.exec(t),n=Gh.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var Yh=/t|\s/i;function gk(t){let e=Jh(t);return function(n){let o=n.split(Yh);return o.length===2&&wk(o[0])&&e(o[1])}}function vk(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function xk(t,e){if(!(t&&e))return;let[r,n]=t.split(Yh),[o,s]=e.split(Yh),i=Xh(r,o);if(i!==void 0)return i||Qh(n,s)}var uj=/\/|:/,dj=/^(?:[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 pj(t){return uj.test(t)&&dj.test(t)}var yk=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function fj(t){return yk.lastIndex=0,yk.test(t)}var hj=-(2**31),mj=2**31-1;function gj(t){return Number.isInteger(t)&&t<=mj&&t>=hj}function yj(t){return Number.isInteger(t)}function bk(){return!0}var bj=/[^\\]\\Z/;function wj(t){if(bj.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var $k=Z(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});Co.formatLimitDefinition=void 0;var _j=Wh(),tr=ue(),Qr=tr.operators,kc={formatMaximum:{okStr:"<=",ok:Qr.LTE,fail:Qr.GT},formatMinimum:{okStr:">=",ok:Qr.GTE,fail:Qr.LT},formatExclusiveMaximum:{okStr:"<",ok:Qr.LT,fail:Qr.GTE},formatExclusiveMinimum:{okStr:">",ok:Qr.GT,fail:Qr.LTE}},vj={message:({keyword:t,schemaCode:e})=>(0,tr.str)`should be ${kc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,tr._)`{comparison: ${kc[t].okStr}, limit: ${e}}`};Co.formatLimitDefinition={keyword:Object.keys(kc),type:"string",schemaType:"string",$data:!0,error:vj,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new _j.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let b=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),m=e.const("fmt",(0,tr._)`${b}[${c.schemaCode}]`);t.fail$data((0,tr.or)((0,tr._)`typeof ${m} != "object"`,(0,tr._)`${m} instanceof RegExp`,(0,tr._)`typeof ${m}.compare != "function"`,d(m)))}function u(){let b=c.schema,m=a.formats[b];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw new Error(`"${o}": format "${b}" does not define "compare" function`);let f=e.scopeValue("formats",{key:b,ref:m,code:i.code.formats?(0,tr._)`${i.code.formats}${(0,tr.getProperty)(b)}`:void 0});t.fail$data(d(f))}function d(b){return(0,tr._)`${b}.compare(${r}, ${n}) ${kc[o].fail} 0`}},dependencies:["format"]};var xj=t=>(t.addKeyword(Co.formatLimitDefinition),t);Co.default=xj});var Rk=Z((oi,Ek)=>{"use strict";Object.defineProperty(oi,"__esModule",{value:!0});var zo=kk(),kj=$k(),em=ue(),Sk=new em.Name("fullFormats"),$j=new em.Name("fastFormats"),tm=(t,e={keywords:!0})=>{if(Array.isArray(e))return Tk(t,e,zo.fullFormats,Sk),t;let[r,n]=e.mode==="fast"?[zo.fastFormats,$j]:[zo.fullFormats,Sk],o=e.formats||zo.formatNames;return Tk(t,o,r,n),e.keywords&&(0,kj.default)(t),t};tm.get=(t,e="full")=>{let n=(e==="fast"?zo.fastFormats:zo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Tk(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,em._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}Ek.exports=oi=tm;Object.defineProperty(oi,"__esModule",{value:!0});oi.default=tm});function Sj(){let t=new Pk.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Ak.default)(t),t}var Pk,Ak,$c,Ik=O(()=>{Pk=zc(Wh(),1),Ak=zc(Rk(),1);$c=class{constructor(e){this._ajv=e??Sj()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}});var Sc,Ok=O(()=>{yo();Sc=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(u=>u.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],l=c.some(u=>u.type==="tool_use");if(i){if(s.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let u=new Set(c.filter(b=>b.type==="tool_use").map(b=>b.id)),d=new Set(s.filter(b=>b.type==="tool_result").map(b=>b.toolUseId));if(u.size!==d.size||![...u].every(b=>d.has(b)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Rs,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},go,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}}});function Ck(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function zk(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Nk=O(()=>{});var Tc,jk=O(()=>{D_();yo();Ik();gs();Ok();Nk();Tc=class extends Za{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Es.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new $c,this.setRequestHandler(hp,n=>this._oninitialize(n)),this.setNotificationHandler(mp,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(xp,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Es.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Sc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=M_(this._capabilities,e)}setRequestHandler(e,r){let o=qr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=uo(o);if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,l)=>{let u=Zr(mo,c);if(!u.success){let f=u.error instanceof Error?u.error.message:String(u.error);throw new K(Y.InvalidParams,`Invalid tools/call request: ${f}`)}let{params:d}=u.data,b=await Promise.resolve(r(c,l));if(d.task){let f=Zr(fo,b);if(!f.success){let y=f.error instanceof Error?f.error.message:String(f.error);throw new K(Y.InvalidParams,`Invalid task creation result: ${y}`)}return f.data}let m=Zr(Pa,b);if(!m.success){let f=m.error instanceof Error?m.error.message:String(m.error);throw new K(Y.InvalidParams,`Invalid tools/call result: ${f}`)}return m.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){zk(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Ck(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Mw.includes(r)?r:lp,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},fa)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(l=>l.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(l=>l.type==="tool_use");if(s){if(o.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let l=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),u=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(l.size!==u.size||![...l].every(d=>u.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},kp,r):this.request({method:"sampling/createMessage",params:e},Rs,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},go,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},go,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new K(Y.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof K?i:new K(Y.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},$p,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});function rm(t){return!!t&&typeof t=="object"&&Mk in t}function Dk(t){return t[Mk]?.complete}var Mk,Lk,Uk=O(()=>{Mk=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(Lk||(Lk={}))});var Zk=O(()=>{});function Ej(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!Tj.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function Rj(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function nm(t){let e=Ej(t);return Rj(t,e.warnings),e.isValid}var Tj,qk=O(()=>{Tj=/^[A-Za-z0-9._-]{1,128}$/});var Ec,Fk=O(()=>{Ec=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}}});function Hk(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Kk(t){return"_def"in t||"_zod"in t||Hk(t)}function om(t){return typeof t!="object"||t===null||Kk(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Hk)}function Bk(t){if(t){if(om(t))return Rn(t);if(!Kk(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function Aj(t){let e=qr(t);return e?Object.entries(e).map(([r,n])=>{let o=lw(n),s=uw(n);return{name:r,description:o,required:!s}}):[]}function en(t){let r=qr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=uo(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function Vk(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Rc,Pj,si,Wk=O(()=>{jk();gs();cf();yo();Uk();Zk();qk();Fk();Yn();Rc=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Tc(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Ec(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(en(Ra)),this.server.assertCanSetRequestHandler(en(mo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ra,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=lo(r.inputSchema);return o?of(o,{strictUnions:!0,pipeStrategy:"input"}):Pj})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=lo(r.outputSchema);o&&(n.outputSchema=of(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(mo,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new K(Y.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new K(Y.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new K(Y.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new K(Y.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof K&&n.code===Y.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=lo(e.inputSchema)??e.inputSchema,i=await ia(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=aa(a);throw new K(Y.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new K(Y.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=lo(e.outputSchema),s=await ia(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=aa(i);throw new K(Y.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,l=a.task,u=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(b=>setTimeout(b,u));let d=await n.taskStore.getTask(c);if(!d)throw new K(Y.InternalError,`Task ${c} not found during polling`);l=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(en(Aa)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Aa,async e=>{switch(e.params.ref.type){case"ref/prompt":return e_(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return t_(e),this.handleResourceCompletion(e,e.params.ref);default:throw new K(Y.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new K(Y.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new K(Y.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return si;let s=qr(n.argsSchema)?.[e.params.argument.name];if(!rm(s))return si;let i=Dk(s);if(!i)return si;let a=await i(e.params.argument.value,e.params.context);return Vk(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return si;throw new K(Y.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return si;let s=await o(e.params.argument.value,e.params.context);return Vk(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(en(ka)),this.server.assertCanSetRequestHandler(en($a)),this.server.assertCanSetRequestHandler(en(Sa)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(ka,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler($a,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Sa,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new K(Y.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new K(Y.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(en(Ta)),this.server.assertCanSetRequestHandler(en(Ea)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Ta,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?Aj(r.argsSchema):void 0}))})),this.server.setRequestHandler(Ea,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new K(Y.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new K(Y.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=lo(n.argsSchema),s=await ia(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",l=aa(c);throw new K(Y.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${l}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredResourceTemplates[e],l.name&&(this._registeredResourceTemplates[l.name]=i)),typeof l.title<"u"&&(i.title=l.title),typeof l.template<"u"&&(i.resourceTemplate=l.template),typeof l.metadata<"u"&&(i.metadata=l.metadata),typeof l.callback<"u"&&(i.readCallback=l.callback),typeof l.enabled<"u"&&(i.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(l=>!!n.completeCallback(l))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:Rn(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=Rn(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(c=>{let l=c instanceof gt?c._def?.innerType:c;return rm(l)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,l){nm(e);let u={title:r,description:n,inputSchema:Bk(o),outputSchema:Bk(s),annotations:i,execution:a,_meta:c,handler:l,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&nm(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=u)),typeof d.title<"u"&&(u.title=d.title),typeof d.description<"u"&&(u.description=d.description),typeof d.paramsSchema<"u"&&(u.inputSchema=Rn(d.paramsSchema)),typeof d.outputSchema<"u"&&(u.outputSchema=Rn(d.outputSchema)),typeof d.callback<"u"&&(u.handler=d.callback),typeof d.annotations<"u"&&(u.annotations=d.annotations),typeof d._meta<"u"&&(u._meta=d._meta),typeof d.enabled<"u"&&(u.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(om(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!om(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(l=>typeof l=="object"&&l!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:l}=r;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},l,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},Pj={type:"object",properties:{}};si={completion:{values:[],hasMore:!1}}});function Oj(t){return Hw.parse(JSON.parse(t))}function Gk(t){return JSON.stringify(t)+`
993
- `}var Ij,Pc,Jk=O(()=>{yo();Ij=10*1024*1024,Pc=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??Ij}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
994
- `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Oj(r)}clear(){this._buffer=void 0}}});import Yk from"node:process";var Ac,Xk=O(()=>{Jk();Ac=class{constructor(e=Yk.stdin,r=Yk.stdout,n){this._stdin=e,this._stdout=r,this._started=!1,this._ondata=o=>{try{this._readBuffer.append(o),this.processReadBuffer()}catch(s){this.onerror?.(s),this.close().catch(()=>{})}},this._onerror=o=>{this.onerror?.(o)},this._readBuffer=new Pc({maxBufferSize:n?.maxBufferSize})}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=Gk(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var Qk,e$=O(()=>{Qk=[]});var l$={};Mo(l$,{AUTHORING_MCP_SERVER_NAME:()=>s$,AUTHORING_MCP_SERVER_VERSION:()=>i$,AUTHORING_RESOURCES:()=>jj,AUTHORING_TOOLS:()=>Nj,AUTHORING_TOOLS_PUBLIC:()=>c$,buildAuthoringMcpServer:()=>a$,runAuthoringMcpServer:()=>Lj});import{promises as Cj}from"node:fs";import{resolve as t$}from"node:path";function o$(){return n$??=import("../mcp/grounding.js").then(e=>e,()=>null),n$}function Ve(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function zj(t,e={}){let r=e.fetchImpl??fetch;try{let n=await r(`${t.baseUrl.replace(/\/+$/,"")}/v1/extensions`,{headers:{Authorization:`Bearer ${t.token}`,Accept:"application/json"}});return n.ok?((await n.json()).extensions??[]).map(s=>s.hookId).filter(s=>typeof s=="string"):null}catch{return null}}async function a$(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let m=await ir(t.baseUrl);if(!m)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:m.baseUrl,token:m.token}}let r=t.grounding??{},n=await o$(),o=null;if(n)try{let m=await e();o={surface:"mcp-authoring",baseUrl:m.baseUrl,token:m.token}}catch{o=null}let s=n&&o?await n.loadActiveSources(o,r):[],i={...r,loadActiveSourcesImpl:async()=>s},a=[],c=[];if(n&&o){try{a=await n.listMcpPromptSkills(o,i)}catch{a=[]}try{c=(await n.listRecipesForSurface(o,i)).map(m=>({id:m.id,record_type:m.record_type,intent:m.intent}))}catch{c=[]}}let l=o?await zj(o,r):null,u=new Rc({name:s$,version:i$},n?{instructions:n.renderAuthoringInstructions({baseUrl:o?.baseUrl??t.baseUrl??"this instance",sources:s,recipeIntents:c,promptNames:a.map(m=>m.id),deployedExtensions:l,docsToken:r.docsToken??n.docsPublicToken()})}:void 0);if(n&&o){let m=o;for(let f of a)u.registerPrompt(f.id,{title:f.name,description:f.description},async()=>{let y=await n.getMcpPromptSkill(m,f.id,r);if(!y)throw new Error(`unknown prompt: ${f.id}`);return{description:y.description,messages:[{role:"user",content:{type:"text",text:(y.prompts??[]).join(`
1139
+ deps: ${r}}`};var C1={keyword:"dependencies",type:"object",schemaType:"object",error:pr.error,code(t){let[e,r]=z1(t);ok(t,e),sk(t,r)}};function z1({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function ok(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,ui.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let l of a)(0,ui.checkReportMissingProp)(t,l)}):(r.if((0,jh._)`${c} && (${(0,ui.checkMissingProp)(t,a,s)})`),(0,ui.reportMissingProp)(t,s),r.else())}}pr.validatePropertyDeps=ok;function sk(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,O1.alwaysValidSchema)(s,e[a])||(r.if((0,ui.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}pr.validateSchemaDeps=sk;pr.default=C1});var ck=Z(Lh=>{"use strict";Object.defineProperty(Lh,"__esModule",{value:!0});var ak=pe(),N1=$e(),j1={message:"property name must be valid",params:({params:t})=>(0,ak._)`{propertyName: ${t.propertyName}}`},L1={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:j1,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,N1.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,ak.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Lh.default=L1});var Mh=Z(Dh=>{"use strict";Object.defineProperty(Dh,"__esModule",{value:!0});var kc=Ft(),tr=pe(),D1=Tr(),$c=$e(),M1={message:"must NOT have additional properties",params:({params:t})=>(0,tr._)`{additionalProperty: ${t.additionalProperty}}`},U1={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:M1,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,$c.alwaysValidSchema)(i,r))return;let l=(0,kc.allSchemaProperties)(n.properties),u=(0,kc.allSchemaProperties)(n.patternProperties);d(),t.ok((0,tr._)`${s} === ${D1.default.errors}`);function d(){e.forIn("key",o,v=>{!l.length&&!u.length?f(v):e.if(b(v),()=>f(v))})}function b(v){let E;if(l.length>8){let R=(0,$c.schemaRefOrVal)(i,n.properties,"properties");E=(0,kc.isOwnProperty)(e,R,v)}else l.length?E=(0,tr.or)(...l.map(R=>(0,tr._)`${v} === ${R}`)):E=tr.nil;return u.length&&(E=(0,tr.or)(E,...u.map(R=>(0,tr._)`${(0,kc.usePattern)(t,R)}.test(${v})`))),(0,tr.not)(E)}function m(v){e.code((0,tr._)`delete ${o}[${v}]`)}function f(v){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){m(v);return}if(r===!1){t.setParams({additionalProperty:v}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,$c.alwaysValidSchema)(i,r)){let E=e.name("valid");c.removeAdditional==="failing"?(y(v,E,!1),e.if((0,tr.not)(E),()=>{t.reset(),m(v)})):(y(v,E),a||e.if((0,tr.not)(E),()=>e.break()))}}function y(v,E,R){let z={keyword:"additionalProperties",dataProp:v,dataPropType:$c.Type.Str};R===!1&&Object.assign(z,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(z,E)}}};Dh.default=U1});var dk=Z(Zh=>{"use strict";Object.defineProperty(Zh,"__esModule",{value:!0});var Z1=Js(),lk=Ft(),Uh=$e(),uk=Mh(),q1={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&uk.default.code(new Z1.KeywordCxt(s,uk.default,"additionalProperties"));let i=(0,lk.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Uh.mergeEvaluated.props(e,(0,Uh.toHash)(i),s.props));let a=i.filter(d=>!(0,Uh.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)l(d)?u(d):(e.if((0,lk.propertyInData)(e,o,d,s.opts.ownProperties)),u(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function l(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function u(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Zh.default=q1});var mk=Z(qh=>{"use strict";Object.defineProperty(qh,"__esModule",{value:!0});var pk=Ft(),Sc=pe(),fk=$e(),hk=$e(),F1={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,pk.allSchemaProperties)(r),c=a.filter(y=>(0,fk.alwaysValidSchema)(s,r[y]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=i.strictSchema&&!i.allowMatchingProperties&&o.properties,u=e.name("valid");s.props!==!0&&!(s.props instanceof Sc.Name)&&(s.props=(0,hk.evaluatedPropsToName)(e,s.props));let{props:d}=s;b();function b(){for(let y of a)l&&m(y),s.allErrors?f(y):(e.var(u,!0),f(y),e.if(u))}function m(y){for(let v in l)new RegExp(y).test(v)&&(0,fk.checkStrictMode)(s,`property ${v} matches pattern ${y} (use allowMatchingProperties)`)}function f(y){e.forIn("key",n,v=>{e.if((0,Sc._)`${(0,pk.usePattern)(t,y)}.test(${v})`,()=>{let E=c.includes(y);E||t.subschema({keyword:"patternProperties",schemaProp:y,dataProp:v,dataPropType:hk.Type.Str},u),s.opts.unevaluated&&d!==!0?e.assign((0,Sc._)`${d}[${v}]`,!0):!E&&!s.allErrors&&e.if((0,Sc.not)(u),()=>e.break())})})}}};qh.default=F1});var gk=Z(Fh=>{"use strict";Object.defineProperty(Fh,"__esModule",{value:!0});var B1=$e(),V1={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,B1.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Fh.default=V1});var yk=Z(Bh=>{"use strict";Object.defineProperty(Bh,"__esModule",{value:!0});var H1=Ft(),K1={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:H1.validateUnion,error:{message:"must match a schema in anyOf"}};Bh.default=K1});var bk=Z(Vh=>{"use strict";Object.defineProperty(Vh,"__esModule",{value:!0});var Tc=pe(),G1=$e(),W1={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Tc._)`{passingSchemas: ${t.passing}}`},J1={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:W1,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(l),t.result(i,()=>t.reset(),()=>t.error(!0));function l(){s.forEach((u,d)=>{let b;(0,G1.alwaysValidSchema)(o,u)?e.var(c,!0):b=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Tc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Tc._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),b&&t.mergeEvaluated(b,Tc.Name)})})}}};Vh.default=J1});var wk=Z(Hh=>{"use strict";Object.defineProperty(Hh,"__esModule",{value:!0});var Y1=$e(),X1={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,Y1.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Hh.default=X1});var xk=Z(Kh=>{"use strict";Object.defineProperty(Kh,"__esModule",{value:!0});var Ec=pe(),vk=$e(),Q1={message:({params:t})=>(0,Ec.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Ec._)`{failingKeyword: ${t.ifClause}}`},ej={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Q1,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,vk.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=_k(n,"then"),s=_k(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,l("then",u),l("else",u))}else o?e.if(a,l("then")):e.if((0,Ec.not)(a),l("else"));t.pass(i,()=>t.error(!0));function c(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function l(u,d){return()=>{let b=t.subschema({keyword:u},a);e.assign(i,a),t.mergeValidEvaluated(b,i),d?e.assign(d,(0,Ec._)`${u}`):t.setParams({ifClause:u})}}}};function _k(t,e){let r=t.schema[e];return r!==void 0&&!(0,vk.alwaysValidSchema)(t,r)}Kh.default=ej});var kk=Z(Gh=>{"use strict";Object.defineProperty(Gh,"__esModule",{value:!0});var tj=$e(),rj={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,tj.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Gh.default=rj});var $k=Z(Wh=>{"use strict";Object.defineProperty(Wh,"__esModule",{value:!0});var nj=Ih(),oj=ek(),sj=Oh(),ij=rk(),aj=nk(),cj=ik(),lj=ck(),uj=Mh(),dj=dk(),pj=mk(),fj=gk(),hj=yk(),mj=bk(),gj=wk(),yj=xk(),bj=kk();function wj(t=!1){let e=[fj.default,hj.default,mj.default,gj.default,yj.default,bj.default,lj.default,uj.default,cj.default,dj.default,pj.default];return t?e.push(oj.default,ij.default):e.push(nj.default,sj.default),e.push(aj.default),e}Wh.default=wj});var Sk=Z(Jh=>{"use strict";Object.defineProperty(Jh,"__esModule",{value:!0});var Be=pe(),_j={message:({schemaCode:t})=>(0,Be.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Be._)`{format: ${t}}`},vj={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:_j,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;o?b():m();function b(){let f=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),y=r.const("fDef",(0,Be._)`${f}[${i}]`),v=r.let("fType"),E=r.let("format");r.if((0,Be._)`typeof ${y} == "object" && !(${y} instanceof RegExp)`,()=>r.assign(v,(0,Be._)`${y}.type || "string"`).assign(E,(0,Be._)`${y}.validate`),()=>r.assign(v,(0,Be._)`"string"`).assign(E,y)),t.fail$data((0,Be.or)(R(),z()));function R(){return c.strictSchema===!1?Be.nil:(0,Be._)`${i} && !${E}`}function z(){let H=u.$async?(0,Be._)`(${y}.async ? await ${E}(${n}) : ${E}(${n}))`:(0,Be._)`${E}(${n})`,Y=(0,Be._)`(typeof ${E} == "function" ? ${H} : ${E}.test(${n}))`;return(0,Be._)`${E} && ${E} !== true && ${v} === ${e} && !${Y}`}}function m(){let f=d.formats[s];if(!f){R();return}if(f===!0)return;let[y,v,E]=z(f);y===e&&t.pass(H());function R(){if(c.strictSchema===!1){d.logger.warn(Y());return}throw new Error(Y());function Y(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function z(Y){let He=Y instanceof RegExp?(0,Be.regexpCode)(Y):c.code.formats?(0,Be._)`${c.code.formats}${(0,Be.getProperty)(s)}`:void 0,Qe=r.scopeValue("formats",{key:s,ref:Y,code:He});return typeof Y=="object"&&!(Y instanceof RegExp)?[Y.type||"string",Y.validate,(0,Be._)`${Qe}.validate`]:["string",Y,Qe]}function H(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Be._)`await ${E}(${n})`}return typeof v=="function"?(0,Be._)`${E}(${n})`:(0,Be._)`${E}.test(${n})`}}}};Jh.default=vj});var Tk=Z(Yh=>{"use strict";Object.defineProperty(Yh,"__esModule",{value:!0});var xj=Sk(),kj=[xj.default];Yh.default=kj});var Ek=Z(Io=>{"use strict";Object.defineProperty(Io,"__esModule",{value:!0});Io.contentVocabulary=Io.metadataVocabulary=void 0;Io.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Io.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Pk=Z(Xh=>{"use strict";Object.defineProperty(Xh,"__esModule",{value:!0});var $j=jx(),Sj=Jx(),Tj=$k(),Ej=Tk(),Rk=Ek(),Rj=[$j.default,Sj.default,(0,Tj.default)(),Ej.default,Rk.metadataVocabulary,Rk.contentVocabulary];Xh.default=Rj});var Ik=Z(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});Rc.DiscrError=void 0;var Ak;(function(t){t.Tag="tag",t.Mapping="mapping"})(Ak||(Rc.DiscrError=Ak={}))});var Ck=Z(em=>{"use strict";Object.defineProperty(em,"__esModule",{value:!0});var Oo=pe(),Qh=Ik(),Ok=lc(),Pj=Ys(),Aj=$e(),Ij={message:({params:{discrError:t,tagName:e}})=>t===Qh.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Oo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},Oj={keyword:"discriminator",type:"object",schemaType:"object",error:Ij,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,Oo._)`${r}${(0,Oo.getProperty)(a)}`);e.if((0,Oo._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:Qh.DiscrError.Tag,tag:l,tagName:a})),t.ok(c);function u(){let m=b();e.if(!1);for(let f in m)e.elseIf((0,Oo._)`${l} === ${f}`),e.assign(c,d(m[f]));e.else(),t.error(!1,{discrError:Qh.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function d(m){let f=e.name("valid"),y=t.subschema({keyword:"oneOf",schemaProp:m},f);return t.mergeEvaluated(y,Oo.Name),f}function b(){var m;let f={},y=E(o),v=!0;for(let H=0;H<i.length;H++){let Y=i[H];if(Y?.$ref&&!(0,Aj.schemaHasRulesButRef)(Y,s.self.RULES)){let Qe=Y.$ref;if(Y=Ok.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Qe),Y instanceof Ok.SchemaEnv&&(Y=Y.schema),Y===void 0)throw new Pj.default(s.opts.uriResolver,s.baseId,Qe)}let He=(m=Y?.properties)===null||m===void 0?void 0:m[a];if(typeof He!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);v=v&&(y||E(Y)),R(He,H)}if(!v)throw new Error(`discriminator: "${a}" must be required`);return f;function E({required:H}){return Array.isArray(H)&&H.includes(a)}function R(H,Y){if(H.const)z(H.const,Y);else if(H.enum)for(let He of H.enum)z(He,Y);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function z(H,Y){if(typeof H!="string"||H in f)throw new Error(`discriminator: "${a}" values must be unique strings`);f[H]=Y}}}};em.default=Oj});var zk=Z((r9,Cj)=>{Cj.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}});var rm=Z((Le,tm)=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.MissingRefError=Le.ValidationError=Le.CodeGen=Le.Name=Le.nil=Le.stringify=Le.str=Le._=Le.KeywordCxt=Le.Ajv=void 0;var zj=Ax(),Nj=Pk(),jj=Ck(),Nk=zk(),Lj=["/properties"],Pc="http://json-schema.org/draft-07/schema",Co=class extends zj.default{_addVocabularies(){super._addVocabularies(),Nj.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(jj.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Nk,Lj):Nk;this.addMetaSchema(e,Pc,!1),this.refs["http://json-schema.org/schema"]=Pc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Pc)?Pc:void 0)}};Le.Ajv=Co;tm.exports=Le=Co;tm.exports.Ajv=Co;Object.defineProperty(Le,"__esModule",{value:!0});Le.default=Co;var Dj=Js();Object.defineProperty(Le,"KeywordCxt",{enumerable:!0,get:function(){return Dj.KeywordCxt}});var zo=pe();Object.defineProperty(Le,"_",{enumerable:!0,get:function(){return zo._}});Object.defineProperty(Le,"str",{enumerable:!0,get:function(){return zo.str}});Object.defineProperty(Le,"stringify",{enumerable:!0,get:function(){return zo.stringify}});Object.defineProperty(Le,"nil",{enumerable:!0,get:function(){return zo.nil}});Object.defineProperty(Le,"Name",{enumerable:!0,get:function(){return zo.Name}});Object.defineProperty(Le,"CodeGen",{enumerable:!0,get:function(){return zo.CodeGen}});var Mj=ac();Object.defineProperty(Le,"ValidationError",{enumerable:!0,get:function(){return Mj.default}});var Uj=Ys();Object.defineProperty(Le,"MissingRefError",{enumerable:!0,get:function(){return Uj.default}})});var Fk=Z(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.formatNames=hr.fastFormats=hr.fullFormats=void 0;function fr(t,e){return{validate:t,compare:e}}hr.fullFormats={date:fr(Mk,im),time:fr(om(!0),am),"date-time":fr(jk(!0),Zk),"iso-time":fr(om(),Uk),"iso-date-time":fr(jk(),qk),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Hj,"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:Qj,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:Kj,int32:{type:"number",validate:Jj},int64:{type:"number",validate:Yj},float:{type:"number",validate:Dk},double:{type:"number",validate:Dk},password:!0,binary:!0};hr.fastFormats={...hr.fullFormats,date:fr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,im),time:fr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,am),"date-time":fr(/^\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,Zk),"iso-time":fr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Uk),"iso-date-time":fr(/^\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,qk),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};hr.formatNames=Object.keys(hr.fullFormats);function Zj(t){return t%4===0&&(t%100!==0||t%400===0)}var qj=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Fj=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Mk(t){let e=qj.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&Zj(r)?29:Fj[n])}function im(t,e){if(t&&e)return t>e?1:t<e?-1:0}var nm=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function om(t){return function(r){let n=nm.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-u*c,b=o-l*c-(d<0?1:0);return(b===23||b===-1)&&(d===59||d===-1)&&i<61}}function am(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function Uk(t,e){if(!(t&&e))return;let r=nm.exec(t),n=nm.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var sm=/t|\s/i;function jk(t){let e=om(t);return function(n){let o=n.split(sm);return o.length===2&&Mk(o[0])&&e(o[1])}}function Zk(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function qk(t,e){if(!(t&&e))return;let[r,n]=t.split(sm),[o,s]=e.split(sm),i=im(r,o);if(i!==void 0)return i||am(n,s)}var Bj=/\/|:/,Vj=/^(?:[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 Hj(t){return Bj.test(t)&&Vj.test(t)}var Lk=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function Kj(t){return Lk.lastIndex=0,Lk.test(t)}var Gj=-(2**31),Wj=2**31-1;function Jj(t){return Number.isInteger(t)&&t<=Wj&&t>=Gj}function Yj(t){return Number.isInteger(t)}function Dk(){return!0}var Xj=/[^\\]\\Z/;function Qj(t){if(Xj.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Bk=Z(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});No.formatLimitDefinition=void 0;var eL=rm(),rr=pe(),tn=rr.operators,Ac={formatMaximum:{okStr:"<=",ok:tn.LTE,fail:tn.GT},formatMinimum:{okStr:">=",ok:tn.GTE,fail:tn.LT},formatExclusiveMaximum:{okStr:"<",ok:tn.LT,fail:tn.GTE},formatExclusiveMinimum:{okStr:">",ok:tn.GT,fail:tn.LTE}},tL={message:({keyword:t,schemaCode:e})=>(0,rr.str)`should be ${Ac[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,rr._)`{comparison: ${Ac[t].okStr}, limit: ${e}}`};No.formatLimitDefinition={keyword:Object.keys(Ac),type:"string",schemaType:"string",$data:!0,error:tL,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new eL.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let b=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),m=e.const("fmt",(0,rr._)`${b}[${c.schemaCode}]`);t.fail$data((0,rr.or)((0,rr._)`typeof ${m} != "object"`,(0,rr._)`${m} instanceof RegExp`,(0,rr._)`typeof ${m}.compare != "function"`,d(m)))}function u(){let b=c.schema,m=a.formats[b];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw new Error(`"${o}": format "${b}" does not define "compare" function`);let f=e.scopeValue("formats",{key:b,ref:m,code:i.code.formats?(0,rr._)`${i.code.formats}${(0,rr.getProperty)(b)}`:void 0});t.fail$data(d(f))}function d(b){return(0,rr._)`${b}.compare(${r}, ${n}) ${Ac[o].fail} 0`}},dependencies:["format"]};var rL=t=>(t.addKeyword(No.formatLimitDefinition),t);No.default=rL});var Gk=Z((di,Kk)=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});var jo=Fk(),nL=Bk(),cm=pe(),Vk=new cm.Name("fullFormats"),oL=new cm.Name("fastFormats"),lm=(t,e={keywords:!0})=>{if(Array.isArray(e))return Hk(t,e,jo.fullFormats,Vk),t;let[r,n]=e.mode==="fast"?[jo.fastFormats,oL]:[jo.fullFormats,Vk],o=e.formats||jo.formatNames;return Hk(t,o,r,n),e.keywords&&(0,nL.default)(t),t};lm.get=(t,e="full")=>{let n=(e==="fast"?jo.fastFormats:jo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Hk(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,cm._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}Kk.exports=di=lm;Object.defineProperty(di,"__esModule",{value:!0});di.default=lm});function sL(){let t=new Wk.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Jk.default)(t),t}var Wk,Jk,Ic,Yk=O(()=>{Wk=Zc(rm(),1),Jk=Zc(Gk(),1);Ic=class{constructor(e){this._ajv=e??sL()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}});var Oc,Xk=O(()=>{wo();Oc=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(u=>u.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],l=c.some(u=>u.type==="tool_use");if(i){if(s.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let u=new Set(c.filter(b=>b.type==="tool_use").map(b=>b.id)),d=new Set(s.filter(b=>b.type==="tool_result").map(b=>b.toolUseId));if(u.size!==d.size||![...u].every(b=>d.has(b)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Ns,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},bo,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}}});function Qk(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function e$(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var t$=O(()=>{});var Cc,r$=O(()=>{sv();wo();Yk();ks();Xk();t$();Cc=class extends Ga{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(zs.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Ic,this.setRequestHandler(xp,n=>this._oninitialize(n)),this.setNotificationHandler(kp,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Ap,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=zs.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Oc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=ov(this._capabilities,e)}setRequestHandler(e,r){let o=Br(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=fo(o);if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,l)=>{let u=Fr(yo,c);if(!u.success){let f=u.error instanceof Error?u.error.message:String(u.error);throw new G(X.InvalidParams,`Invalid tools/call request: ${f}`)}let{params:d}=u.data,b=await Promise.resolve(r(c,l));if(d.task){let f=Fr(mo,b);if(!f.success){let y=f.error instanceof Error?f.error.message:String(f.error);throw new G(X.InvalidParams,`Invalid task creation result: ${y}`)}return f.data}let m=Fr(ja,b);if(!m.success){let f=m.error instanceof Error?m.error.message:String(m.error);throw new G(X.InvalidParams,`Invalid tools/call result: ${f}`)}return m.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){e$(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Qk(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:o_.includes(r)?r:yp,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},_a)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(l=>l.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(l=>l.type==="tool_use");if(s){if(o.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let l=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),u=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(l.size!==u.size||![...l].every(d=>u.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Ip,r):this.request({method:"sampling/createMessage",params:e},Ns,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},bo,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},bo,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new G(X.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof G?i:new G(X.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},Op,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});function um(t){return!!t&&typeof t=="object"&&o$ in t}function s$(t){return t[o$]?.complete}var o$,n$,i$=O(()=>{o$=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(n$||(n$={}))});var a$=O(()=>{});function aL(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!iL.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function cL(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function dm(t){let e=aL(t);return cL(t,e.warnings),e.isValid}var iL,c$=O(()=>{iL=/^[A-Za-z0-9._-]{1,128}$/});var zc,l$=O(()=>{zc=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}}});function p$(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function f$(t){return"_def"in t||"_zod"in t||p$(t)}function pm(t){return typeof t!="object"||t===null||f$(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(p$)}function u$(t){if(t){if(pm(t))return Rn(t);if(!f$(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function uL(t){let e=Br(t);return e?Object.entries(e).map(([r,n])=>{let o=Pw(n),s=Aw(n);return{name:r,description:o,required:!s}}):[]}function rn(t){let r=Br(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=fo(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function d$(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Nc,lL,pi,h$=O(()=>{r$();ks();gf();wo();i$();a$();c$();l$();Jn();Nc=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Cc(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new zc(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(rn(Na)),this.server.assertCanSetRequestHandler(rn(yo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Na,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=po(r.inputSchema);return o?ff(o,{strictUnions:!0,pipeStrategy:"input"}):lL})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=po(r.outputSchema);o&&(n.outputSchema=ff(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(yo,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new G(X.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new G(X.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new G(X.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new G(X.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof G&&n.code===X.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=po(e.inputSchema)??e.inputSchema,i=await fa(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=ha(a);throw new G(X.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new G(X.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=po(e.outputSchema),s=await fa(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=ha(i);throw new G(X.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,l=a.task,u=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(b=>setTimeout(b,u));let d=await n.taskStore.getTask(c);if(!d)throw new G(X.InternalError,`Task ${c} not found during polling`);l=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(rn(La)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(La,async e=>{switch(e.params.ref.type){case"ref/prompt":return __(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return v_(e),this.handleResourceCompletion(e,e.params.ref);default:throw new G(X.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new G(X.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new G(X.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return pi;let s=Br(n.argsSchema)?.[e.params.argument.name];if(!um(s))return pi;let i=s$(s);if(!i)return pi;let a=await i(e.params.argument.value,e.params.context);return d$(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return pi;throw new G(X.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return pi;let s=await o(e.params.argument.value,e.params.context);return d$(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(rn(Aa)),this.server.assertCanSetRequestHandler(rn(Ia)),this.server.assertCanSetRequestHandler(rn(Oa)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Aa,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(Ia,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Oa,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new G(X.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new G(X.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(rn(Ca)),this.server.assertCanSetRequestHandler(rn(za)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Ca,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?uL(r.argsSchema):void 0}))})),this.server.setRequestHandler(za,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new G(X.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new G(X.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=po(n.argsSchema),s=await fa(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",l=ha(c);throw new G(X.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${l}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredResourceTemplates[e],l.name&&(this._registeredResourceTemplates[l.name]=i)),typeof l.title<"u"&&(i.title=l.title),typeof l.template<"u"&&(i.resourceTemplate=l.template),typeof l.metadata<"u"&&(i.metadata=l.metadata),typeof l.callback<"u"&&(i.readCallback=l.callback),typeof l.enabled<"u"&&(i.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(l=>!!n.completeCallback(l))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:Rn(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=Rn(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(c=>{let l=c instanceof yt?c._def?.innerType:c;return um(l)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,l){dm(e);let u={title:r,description:n,inputSchema:u$(o),outputSchema:u$(s),annotations:i,execution:a,_meta:c,handler:l,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&dm(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=u)),typeof d.title<"u"&&(u.title=d.title),typeof d.description<"u"&&(u.description=d.description),typeof d.paramsSchema<"u"&&(u.inputSchema=Rn(d.paramsSchema)),typeof d.outputSchema<"u"&&(u.outputSchema=Rn(d.outputSchema)),typeof d.callback<"u"&&(u.handler=d.callback),typeof d.annotations<"u"&&(u.annotations=d.annotations),typeof d._meta<"u"&&(u._meta=d._meta),typeof d.enabled<"u"&&(u.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(pm(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!pm(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(l=>typeof l=="object"&&l!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:l}=r;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},l,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},lL={type:"object",properties:{}};pi={completion:{values:[],hasMore:!1}}});function pL(t){return p_.parse(JSON.parse(t))}function m$(t){return JSON.stringify(t)+`
1140
+ `}var dL,jc,g$=O(()=>{wo();dL=10*1024*1024,jc=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??dL}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
1141
+ `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),pL(r)}clear(){this._buffer=void 0}}});import y$ from"node:process";var Lc,b$=O(()=>{g$();Lc=class{constructor(e=y$.stdin,r=y$.stdout,n){this._stdin=e,this._stdout=r,this._started=!1,this._ondata=o=>{try{this._readBuffer.append(o),this.processReadBuffer()}catch(s){this.onerror?.(s),this.close().catch(()=>{})}},this._onerror=o=>{this.onerror?.(o)},this._readBuffer=new jc({maxBufferSize:n?.maxBufferSize})}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=m$(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var w$,_$=O(()=>{w$=[]});var P$={};qo(P$,{AUTHORING_MCP_SERVER_NAME:()=>S$,AUTHORING_MCP_SERVER_VERSION:()=>T$,AUTHORING_RESOURCES:()=>gL,AUTHORING_TOOLS:()=>mL,AUTHORING_TOOLS_PUBLIC:()=>R$,buildAuthoringMcpServer:()=>E$,runAuthoringMcpServer:()=>yL});import{promises as fL}from"node:fs";import{resolve as v$}from"node:path";function $$(){return k$??=import("../mcp/grounding.js").then(e=>e,()=>null),k$}function Ve(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function hL(t,e={}){let r=e.fetchImpl??fetch;try{let n=await r(`${t.baseUrl.replace(/\/+$/,"")}/v1/extensions`,{headers:{Authorization:`Bearer ${t.token}`,Accept:"application/json"}});return n.ok?((await n.json()).extensions??[]).map(s=>s.hookId).filter(s=>typeof s=="string"):null}catch{return null}}async function E$(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let m=await Gt(t.baseUrl);if(!m)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:m.baseUrl,token:m.token}}let r=t.grounding??{},n=await $$(),o=null;if(n)try{let m=await e();o={surface:"mcp-authoring",baseUrl:m.baseUrl,token:m.token}}catch{o=null}let s=n&&o?await n.loadActiveSources(o,r):[],i={...r,loadActiveSourcesImpl:async()=>s},a=[],c=[];if(n&&o){try{a=await n.listMcpPromptSkills(o,i)}catch{a=[]}try{c=(await n.listRecipesForSurface(o,i)).map(m=>({id:m.id,record_type:m.record_type,intent:m.intent}))}catch{c=[]}}let l=o?await hL(o,r):null,u=new Nc({name:S$,version:T$},n?{instructions:n.renderAuthoringInstructions({baseUrl:o?.baseUrl??t.baseUrl??"this instance",sources:s,recipeIntents:c,promptNames:a.map(m=>m.id),deployedExtensions:l,docsToken:r.docsToken??n.docsPublicToken()})}:void 0);if(n&&o){let m=o;for(let f of a)u.registerPrompt(f.id,{title:f.name,description:f.description},async()=>{let y=await n.getMcpPromptSkill(m,f.id,r);if(!y)throw new Error(`unknown prompt: ${f.id}`);return{description:y.description,messages:[{role:"user",content:{type:"text",text:(y.prompts??[]).join(`
995
1142
 
996
- `)}}]}})}u.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:m,token:f}=await e(),y=await fetch(`${m}/v1/catalog/records`,{headers:{Authorization:`Bearer ${f}`,Accept:"application/json"}});if(!y.ok)throw new Error(`catalog fetch failed: ${y.status}`);return Ve(await y.json())}),u.registerTool("record_anatomy",{title:"Record anatomy + display contract",description:"Fetch ONE record type in depth (/v1/catalog/records/:type): anatomy markdown (field meanings, sublists, gotchas, relations), authored recipe display contracts (columns/labels/formats), semantic column metadata and the record's plain-English description. Read this BEFORE building UI over a record \u2014 column names alone routinely mislead (e.g. tran_id is the human-facing document number, entity_id has a display twin entity_name). Also reports `unpopulatedColumns`: columns that EXIST but carry no value in any sampled row on this instance (currency_name is the classic \u2014 currency_id holds the data). Rendering one of those produces a blank column while faithfully following the display contract, so check it before choosing what to show. And reports `lines`: the record's LINE tables with their columns, including line-level custom fields (custcol_*). Check the lines before concluding a link is absent \u2014 a transaction routinely carries a reference on its LINES while the header field is NULL, and reading only the header reports a real link as missing.",inputSchema:{recordType:N.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:N.string().optional().describe('Which connector publishes this recordType, e.g. "netsuite" or "stripe". 29 record types are published by more than one source ("customer" by six) and each is a different shape behind the same name. Omit it and the catalog collapse rule picks one; the answer names its choice in `source`.')}},async({recordType:m,source:f})=>{let{baseUrl:y,token:v}=await e(),E=f?`?source=${encodeURIComponent(f)}`:"",R=await fetch(`${y}/v1/catalog/records/${encodeURIComponent(m)}${E}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});if(R.status===404)throw new Error(`unknown record type "${m}" \u2014 list them with catalog_get.`);if(!R.ok)throw new Error(`record anatomy fetch failed: ${R.status}`);return Ve(await R.json())}),u.registerTool("common_columns",{title:"Columns common to several record types",description:"Given SEVERAL record types, return the columns present on ALL of them (safe to select in one shared query shape) and the columns present on only some, with exactly which types lack each. Use this BEFORE writing a query that spans record types \u2014 transaction tables are NOT uniform (memo, total, created_from_id and even pg_row_id are missing from some), and PostgREST rejects an unknown column with 42703 and fails the ENTIRE request, so one wrong name loses the whole table rather than one field. Record types the caller cannot read come back in unknownRecordTypes \u2014 if that is non-empty the intersection covers fewer types than you asked for.",inputSchema:{recordTypes:N.array(N.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:N.string().optional().describe("Pin every requested type to ONE connector, e.g. \"netsuite\". Without it each name collapses by the catalog rule, so an intersection can silently mix two sources' tables for the same name. The response's `resolvedSources` names what it used.")}},async({recordTypes:m,source:f})=>{let{baseUrl:y,token:v}=await e(),E=new URLSearchParams({types:m.join(",")});f&&E.set("source",f);let R=await fetch(`${y}/v1/catalog/columns?${E}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});if(R.status===404)throw new Error(`none of those record types resolved: ${m.join(", ")} \u2014 list them with catalog_get.`);if(!R.ok)throw new Error(`common columns fetch failed: ${R.status}`);return Ve(await R.json())}),u.registerTool("catalog_census",{title:"Count the customer's customizations",description:'Count the whole customization catalog: every object by kind AND by whether it can be changed (editable / partner_owned / turbobase_managed / unknown), plus which classes were never collected and why. Call this BEFORE search_catalog when the question is "how much is there" / "what is this account made of" / "how much of this is even ours to change". Takes no arguments.',inputSchema:{}},async()=>{let{baseUrl:m,token:f}=await e(),y=await fetch(`${m}/v1/catalog/census`,{headers:{Authorization:`Bearer ${f}`,Accept:"application/json"}});if(!y.ok)throw new Error(`catalog census failed: ${y.status}`);return Ve(await y.json())}),u.registerTool("search_catalog",{title:"Search the customization catalog",description:'Survey the customer\'s customization catalog by free text \u2014 scripts, custom records, fields, lists, workflows, roles, saved searches, and installed bundles. Matches ids, names AND the generated plain-English explanations, so ask what you actually want ("which object handles rebates?"), not just an exact id. Returns compact {kind, externalId, name, summary, modifiability} hits plus the TRUE match total, so you can see when the page truncated; pass a hit to explain_object for the full definition + prose. A `partner_owned` object CANNOT be edited by this account however well you understand it \u2014 check that before planning a change. Search this before building over a custom record: its definition and explanation are the spec.',inputSchema:{query:N.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:N.enum(r$).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:N.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:m,kind:f,limit:y})=>{let{baseUrl:v,token:E}=await e(),R=new URLSearchParams({q:m});f&&R.set("kind",f),y!==void 0&&R.set("limit",String(y));let z=await fetch(`${v}/v1/catalog/objects?${R}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(!z.ok)throw new Error(`catalog object search failed: ${z.status}`);return Ve(await z.json())}),u.registerTool("explain_object",{title:"Explain one catalog object",description:"Fetch ONE customization-catalog object in depth: its captured definition (or script source, or a bundle\u2019s membership), human label, the generated plain-English explanation (tldr + markdown) of what it is for, and its OWNERSHIP \u2014 `modifiability` plus a one-line reason saying whether this account can change it at all. Address it by the {kind, externalId} a search_catalog hit returns. For a FIELD it also reports `selectTarget`: where a List/Record field ACTUALLY points, resolved to a mirrored table plus the filter needed to read it correctly. Do not infer a target from the field name \u2014 a carrier-named field can point at `entity` (vendors), and building on the wrong guess resolves nothing while looking like an empty table.",inputSchema:{kind:N.enum(r$),externalId:N.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:m,externalId:f})=>{let{baseUrl:y,token:v}=await e(),E=await fetch(`${y}/v1/catalog/objects/${encodeURIComponent(m)}/${encodeURIComponent(f)}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});if(E.status===404)throw new Error(`unknown object ${m}:${f} \u2014 find it with search_catalog.`);if(!E.ok)throw new Error(`catalog object fetch failed: ${E.status}`);return Ve(await E.json())}),u.registerTool("search_documentation",{title:"Search the knowledge base",description:'Search this instance\'s published knowledge base \u2014 internal documentation: processes, policies, playbooks, how-tos. Route questions about how the ORGANISATION works here ("what\'s our receiving process", "how do we handle returns"), and ALWAYS search it before building UI over a custom record \u2014 the KB is the only spec a custom record has. Returns up to `limit` {slug, title, snippet} hits; pass a slug to read_document for the full text. Published release only \u2014 drafts are never returned.',inputSchema:{query:N.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:N.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:m,limit:f})=>{let{baseUrl:y,token:v}=await e(),E=new URLSearchParams({q:m});f!==void 0&&E.set("limit",String(f));let R=await fetch(`${y}/v1/kb/search?${E}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});if(!R.ok)throw new Error(`kb search failed: ${R.status}`);return Ve(await R.json())}),u.registerTool("read_document",{title:"Read a knowledge-base document",description:"Read one published knowledge-base document in full by its slug (from a search_documentation hit). Returns {found, slug, title, body_markdown}. Published release only \u2014 unpublished / admin-only drafts are never returned.",inputSchema:{slug:N.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:m})=>{let{baseUrl:f,token:y}=await e(),v=await fetch(`${f}/v1/kb/document/${encodeURIComponent(m)}`,{headers:{Authorization:`Bearer ${y}`,Accept:"application/json"}});if(!v.ok&&v.status!==404)throw new Error(`kb document fetch failed: ${v.status}`);return Ve(await v.json())}),u.registerTool("generate_types",{title:"Generate types.ts",description:"Generate the instance's types.ts (record shapes + PostgREST ops). Returns the source.",inputSchema:{recordsOnly:N.boolean().optional()}},async({recordsOnly:m})=>{let{baseUrl:f,token:y}=await e();return{content:[{type:"text",text:await zr({baseUrl:f,token:y,recordsOnly:m})}]}}),u.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:N.string(),event:N.string().optional(),template:N.enum(["require-field","enforce-format","blank"]).optional(),field:N.string().optional(),regex:N.string().optional(),source:N.string().optional(),id:N.string().optional()}},async m=>{let f=ro("hook",{recordType:m.recordType,event:m.event,template:m.template,field:m.field,regex:m.regex,source:m.source,id:m.id});return Ve({path:f.relativePath,content:f.content})}),u.registerTool("scaffold_conduit",{title:"Scaffold a conduit",description:"Generate a conduit file body that bridges a canonical record from one source into another (does not write to disk; returns path + content).",inputSchema:{source:N.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:N.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:N.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:N.string().optional().describe("Target record type (defaults to the trigger record type)."),event:N.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:N.string().optional()}},async m=>{let f=ro("conduit",{recordType:m.recordType,source:m.source,to:m.to,toRecordType:m.toRecordType,event:m.event,id:m.id});return Ve({path:f.relativePath,content:f.content})}),u.registerTool("mock_test",{title:"Dry-run an extension against samples",description:"Bundle the given source through the production sandbox and run it against samples/ fixtures.",inputSchema:{source:N.string().describe("The extension TS source."),samplesDir:N.string().optional().describe('Samples directory (default "samples").')}},async({source:m,samplesDir:f})=>{let y=t$(process.cwd(),f??"samples"),v=await Wo(y),E=await Ai(m,v.map(z=>z.fixture)),R=E.filter(z=>!z.pass).length;return Ve({total:E.length,passed:E.length-R,results:E})}),u.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:N.string(),recordType:N.string(),event:N.string(),source:N.string().describe('Adapter id or "standalone".'),sourceCode:N.string().describe("The verbatim extension TS."),extensionKind:N.string().optional()}},async m=>{let{baseUrl:f,token:y}=await e(),E=await new ee({baseUrl:f,token:y}).deploy({id:m.id,recordType:m.recordType,event:m.event,source:m.source,sourceCode:m.sourceCode,extensionKind:m.extensionKind});return Ve(E)}),u.registerTool("tail_logs",{title:"Tail an extension's logs",description:"Read an extension's log ring buffer (GET /v1/extensions/:id/logs).",inputSchema:{id:N.string(),limit:N.number().int().positive().optional()}},async({id:m,limit:f})=>{let{baseUrl:y,token:v}=await e(),E=new ee({baseUrl:y,token:v});return Ve({id:m,logs:await E.logs(m,f)})}),u.registerTool("apps_list",{title:"List hosted apps",description:"Every hosted app on this instance with its slug, whether it's deployed, and its latest source revision. `sourceRev: null` means the app has no source of record yet (deployed dist only) \u2014 pull will 404 until something is pushed. GET /v1/apps.",inputSchema:{}},async()=>{let{baseUrl:m,token:f}=await e(),y=new ee({baseUrl:m,token:f});return Ve(await y.appsList())}),u.registerTool("apps_create",{title:"Create a hosted app",description:"Create a bare hosted-app row so source can be pushed and a build shipped to it \u2014 the author-led path that needs no proposal. Creates the registration only; it serves nothing until a build is shipped. POST /v1/apps.",inputSchema:{slug:N.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:N.string().optional().describe("Display name (defaults to the slug)."),description:N.string().optional().describe("Short description.")}},async({slug:m,name:f,description:y})=>{let{baseUrl:v,token:E}=await e(),R=new ee({baseUrl:v,token:E});return Ve(await R.appsCreate({slug:m,name:f,description:y}))}),u.registerTool("apps_pull",{title:"Pull a hosted app's source",description:"Fetch the app's latest source tree as {path \u2192 contents} READ-ONLY \u2014 write it to disk, refine it, then apps_push it back. Returns 404 when the app has no source revision yet. NEVER deploys. GET /v1/apps/:id/pull.",inputSchema:{app:N.string().describe("App slug or id.")}},async({app:m})=>{let{baseUrl:f,token:y}=await e(),v=new ee({baseUrl:f,token:y});return Ve(await v.appsPull(m))}),u.registerTool("apps_push",{title:"Push a hosted app's source",description:"Record an edited source tree as the app's NEW source revision, so the instance holds the source of record rather than one laptop. Send the whole tree ({path \u2192 contents}, relative POSIX paths, no node_modules/dist/.git). SOURCE ONLY \u2014 this does not build and does not change what is live; run `turbobase apps deploy <slug>` for that. POST /v1/apps/:id/push.",inputSchema:{app:N.string().describe("App slug or id."),files:N.record(N.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:N.string().optional().describe("Short note stored with the revision.")}},async({app:m,files:f,note:y})=>{let{baseUrl:v,token:E}=await e(),R=new ee({baseUrl:v,token:E});return Ve(await R.appsPush(m,f,{note:y}))});let d=N.object({name:N.string().describe("Field name (lowercase identifier)."),type:N.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:N.boolean().optional()}),b=N.object({slug:N.string().describe("Table slug; the physical table is cr_<slug>."),displayName:N.string().optional(),fields:N.array(d).describe("At least one field."),rowLevelOwner:N.boolean().optional().describe("Restrict non-admins to rows they created.")});return u.registerTool("tables_list",{title:"List custom tables",description:"The instance's customer-authored tables, their fields, and which apps claim each one. Read the `column` on each field \u2014 that is the actual Postgres column an app SELECTs (cf_sa_<name>), which is not the same string as the field name. GET /v1/tables.",inputSchema:{}},async()=>{let{baseUrl:m,token:f}=await e(),y=new ee({baseUrl:m,token:f});return Ve(await y.tablesList())}),u.registerTool("tables_plan",{title:"Preview a table declaration",description:"What these table declarations WOULD do, without doing it. Several apps may claim one table and the instance merges their declarations, so this reports the merged shape and \u2014 the reason to call it \u2014 fails with a conflict report when another claimant already declares one of your field names at a different type. Writes NOTHING. POST /v1/tables/plan.",inputSchema:{tables:N.array(b),claimedBy:N.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:m,claimedBy:f})=>{let{baseUrl:y,token:v}=await e(),E=new ee({baseUrl:y,token:v});return Ve(await E.tablesPlan({tables:m,claimedBy:f}))}),u.registerTool("tables_apply",{title:"Create or evolve custom tables",description:"Record these table declarations and reconcile them into real Postgres tables \u2014 RLS, realtime, and the write path included. Additive: an existing table gains the fields you declare and keeps the ones other claimants declared. Never drops a column, so removing a field from your declaration releases your claim on it rather than deleting data. Prefer declaring tables in the app manifest (public/turbobase.json) so the deploy applies them; use this when authoring outside an app. POST /v1/tables/apply.",inputSchema:{tables:N.array(b),claimedBy:N.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:m,claimedBy:f})=>{let{baseUrl:y,token:v}=await e(),E=new ee({baseUrl:y,token:v});return Ve(await E.tablesApply({tables:m,claimedBy:f}))}),u.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async m=>{let{baseUrl:f,token:y}=await e(),E=await(await fetch(`${f}/v1/catalog/records`,{headers:{Authorization:`Bearer ${y}`,Accept:"application/json"}})).text();return{contents:[{uri:m.href,mimeType:"application/json",text:E}]}}),u.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async m=>{let{baseUrl:f,token:y}=await e(),v=await zr({baseUrl:f,token:y});return{contents:[{uri:m.href,mimeType:"text/plain",text:v}]}}),u.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async m=>{let f=t$(process.cwd(),"samples"),y=[];try{y=(await Cj.readdir(f)).filter(E=>E.endsWith(".json"))}catch{y=[]}let v=await Wo(f);return{contents:[{uri:m.href,mimeType:"application/json",text:JSON.stringify({files:y,samples:v.map(E=>E.fixture)},null,2)}]}}),u.registerResource("recipes","recipes:///",{title:"Intent recipes",description:"Intent recipes (columns / stats / actions per record type + intent), filtered to the instance's installed sources.",mimeType:"application/json"},async m=>{let f=await o$(),y=[];if(f){let{baseUrl:v,token:E}=await e();y=await f.listRecipesForSurface({surface:"mcp-authoring",baseUrl:v,token:E},r)}return{contents:[{uri:m.href,mimeType:"application/json",text:JSON.stringify({recipes:y})}]}}),u}async function Lj(t={}){let e=await a$(t),r=new Ac;await e.connect(r)}var r$,n$,s$,i$,c$,Nj,jj,u$=O(()=>{Wk();Xk();Yn();pl();Ei();wn();vl();Rl();e$();r$=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];s$="turbobase-authoring",i$="0.1.0";c$=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","search_catalog","catalog_census","explain_object","generate_types","scaffold_hook","scaffold_conduit","mock_test","deploy","tail_logs","apps_list","apps_create","apps_pull","apps_push","tables_list","tables_plan","tables_apply"],Nj=[...c$,...Qk],jj=["catalog:///","types://all","samples:///","recipes:///"]});import{spawn as um}from"node:child_process";import{promises as ye}from"node:fs";import{homedir as Mj}from"node:os";import{basename as p$,dirname as No,join as Rt,relative as Ic,resolve as Te,sep as lm}from"node:path";var Rm=zc(Em(),1),{program:sL,createCommand:iL,createArgument:aL,createOption:cL,CommanderError:lL,InvalidArgumentError:uL,InvalidOptionArgumentError:dL,Command:Pm,Argument:pL,Option:fL,Help:hL}=Rm.default;pl();Ei();wn();vl();wl();import{promises as fg}from"node:fs";function dg(t,e){return e===t?"same-type-merge":"different-type-mint"}var hg=4;function xl(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=Qn(t,"id"),r=Qn(t,"on"),n=Qn(t,"source"),o=Qn(t,"recordType"),s=/to\s*:\s*\{([^}]*)\}/.exec(t)?.[1]??"",i=Qn(s,"source"),a=Qn(s,"recordType"),c=/cycleBudget\s*:\s*(\d+)/.exec(t);if(!e||!n||!o||!i||!a)throw new Error("could not parse id/from.{source,recordType}/to.{source,recordType} \u2014 is it a reference-shape defineConduit({...})?");return{id:e,on:r,fromSource:n,fromRecordType:o,toSource:i,toRecordType:a,cycleBudget:c?Number(c[1]):hg}}function Qn(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function bT(t){return{recordType:t.recordType,event:t.event??"after_canonicalize_inbound",direction:"inbound",origin:"system",source:t.fromSource,payload:t.payload??{},tenantConfig:t.tenantConfig??{},metadata:{externalId:t.externalId,lines:t.lines??[]},bindings:t.bindings??[],atlasLinks:t.atlasLinks??{}}}async function mg(t,e,r="fixture"){let n=e.name??r,o=[],s;try{s=xl(t)}catch(c){return{fixtureName:n,conduit:_T(),guards:o,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],logs:[],error:c instanceof Error?c.message:String(c)}}let i=bT(e),a=Object.entries(e.atlasLinks??{}).map(([c,l])=>({key:c,resolved:l}));try{let c=await Pi(t),u=!!(await Ko(c,i,{member:"when",timeoutMs:200})).whenResult;o.push({name:"from.when",status:u?"passed":"failed",detail:u?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let d=e.hop??0;if(o.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${d} vs cycleBudget=${s.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),o.push({name:"opposite-direction-loop",status:"skipped-offline",detail:"reads committed conduit_event rows for the reverse leg \u2014 requires live sandbox state (skipped in fixture mode)"}),o.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!u)return{fixtureName:n,conduit:s,guards:o,whenPassed:u,atlasResolutions:a,wouldWriteBindings:[],logs:[]};let b=await Ko(c,i,{member:"transform",timeoutMs:200}),m=b.effects.logs,f=b.effects.result;if(!f||typeof f!="object")throw new Error(`conduit ${s.id} transform returned no result (expected { patch, createdFrom? })`);let y=f,v=dg(s.fromRecordType,s.toRecordType),{wouldWriteBindings:E,masterAction:R}=wT(s,v,e);return{fixtureName:n,conduit:s,guards:o,whenPassed:u,atlasResolutions:a,transformResult:y,applyBranch:v,wouldWriteBindings:E,masterAction:R,logs:m}}catch(c){return{fixtureName:n,conduit:s,guards:o,whenPassed:!1,atlasResolutions:a,wouldWriteBindings:[],logs:[],error:c instanceof Error?c.message:String(c)}}}function wT(t,e,r){return e==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${r.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:r.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:t.toSource,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${t.toRecordType} master (source_system='${t.toSource}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:t.toSource,externalId:null,role:"origin",why:"this conduit CREATED the new master, so the target is its origin; external_id null until writeback mints it"},{source:t.fromSource,externalId:r.externalId,role:"replica",why:"firing source bound onto the created master (supplementary lineage; best-effort, may collide in a 1\u2192N fan)"}]}}function _T(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",cycleBudget:hg}}async function gg(t){return Promise.reject(new Error("`replay --against sandbox` requires a running sandbox (TURBOBASE_SANDBOX=1 + a local DB). No local Postgres / k3d in this environment \u2014 deferred to a DB-backed run. Use `replay --fixture <file>` for the offline transform/apply-branch dry-run."))}async function yg(t){let e=await fg.readFile(t,"utf8");return JSON.parse(e)}function bg(t){return fg.readFile(t,"utf8")}function wg(t,e){let r=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;if(!e)return t.whenPassed?`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`:`replay ${t.fixtureName} [${r.id}]: WHEN-FAILED (conduit short-circuited)`;let n=[];n.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),n.push(`conduit: ${r.id}`),n.push(`route: ${r.fromSource}.${r.fromRecordType} \u2192 ${r.toSource}.${r.toRecordType}${r.on?` on=${r.on}`:""}`),n.push(""),n.push("guards (dispatch order):");for(let o of t.guards){let s=o.status==="passed"?"\u2713":o.status==="failed"?"\u2717":"\u2298";n.push(` ${s} ${o.name} [${o.status}] \u2014 ${o.detail}`)}if(n.push(""),n.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)n.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let o of t.atlasResolutions)n.push(` ${o.key} \u2192 ${o.resolved===null?"null (no Atlas link \u2014 noted)":o.resolved}`);if(!t.whenPassed)return n.push(""),n.push("transform: SKIPPED (from.when gate did not fire)."),n.join(`
997
- `);if(n.push(""),n.push("transform \u2192 patch:"),n.push(vT(JSON.stringify(t.transformResult?.patch??{},null,2)," ")),t.transformResult?.createdFrom&&n.push(` createdFrom: ${JSON.stringify(t.transformResult.createdFrom)}`),t.logs.length>0){n.push(""),n.push("conduit logs:");for(let o of t.logs)n.push(` [${o.level}] ${o.message}${o.meta?` ${JSON.stringify(o.meta)}`:""}`)}n.push(""),n.push(`apply-branch: ${t.applyBranch}`),n.push(` ${t.masterAction}`),n.push(""),n.push("bindings that WOULD be written (txn_source_link):");for(let o of t.wouldWriteBindings)n.push(` ${o.source} role=${o.role} external_id=${o.externalId??"null"} \u2014 ${o.why}`);return n.join(`
998
- `)}function vT(t,e){return t.split(`
1143
+ `)}}]}})}u.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:m,token:f}=await e(),y=await fetch(`${m}/v1/catalog/records`,{headers:{Authorization:`Bearer ${f}`,Accept:"application/json"}});if(!y.ok)throw new Error(`catalog fetch failed: ${y.status}`);return Ve(await y.json())}),u.registerTool("record_anatomy",{title:"Record anatomy + display contract",description:"Fetch ONE record type in depth (/v1/catalog/records/:type): anatomy markdown (field meanings, sublists, gotchas, relations), authored recipe display contracts (columns/labels/formats), semantic column metadata and the record's plain-English description. Read this BEFORE building UI over a record \u2014 column names alone routinely mislead (e.g. tran_id is the human-facing document number, entity_id has a display twin entity_name). Also reports `unpopulatedColumns`: columns that EXIST but carry no value in any sampled row on this instance (currency_name is the classic \u2014 currency_id holds the data). Rendering one of those produces a blank column while faithfully following the display contract, so check it before choosing what to show. And reports `lines`: the record's LINE tables with their columns, including line-level custom fields (custcol_*). Check the lines before concluding a link is absent \u2014 a transaction routinely carries a reference on its LINES while the header field is NULL, and reading only the header reports a real link as missing.",inputSchema:{recordType:N.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:N.string().optional().describe('Which connector publishes this recordType, e.g. "netsuite" or "stripe". 29 record types are published by more than one source ("customer" by six) and each is a different shape behind the same name. Omit it and the catalog collapse rule picks one; the answer names its choice in `source`.')}},async({recordType:m,source:f})=>{let{baseUrl:y,token:v}=await e(),E=f?`?source=${encodeURIComponent(f)}`:"",R=await fetch(`${y}/v1/catalog/records/${encodeURIComponent(m)}${E}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});if(R.status===404)throw new Error(`unknown record type "${m}" \u2014 list them with catalog_get.`);if(!R.ok)throw new Error(`record anatomy fetch failed: ${R.status}`);return Ve(await R.json())}),u.registerTool("common_columns",{title:"Columns common to several record types",description:"Given SEVERAL record types, return the columns present on ALL of them (safe to select in one shared query shape) and the columns present on only some, with exactly which types lack each. Use this BEFORE writing a query that spans record types \u2014 transaction tables are NOT uniform (memo, total, created_from_id and even pg_row_id are missing from some), and PostgREST rejects an unknown column with 42703 and fails the ENTIRE request, so one wrong name loses the whole table rather than one field. Record types the caller cannot read come back in unknownRecordTypes \u2014 if that is non-empty the intersection covers fewer types than you asked for.",inputSchema:{recordTypes:N.array(N.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:N.string().optional().describe("Pin every requested type to ONE connector, e.g. \"netsuite\". Without it each name collapses by the catalog rule, so an intersection can silently mix two sources' tables for the same name. The response's `resolvedSources` names what it used.")}},async({recordTypes:m,source:f})=>{let{baseUrl:y,token:v}=await e(),E=new URLSearchParams({types:m.join(",")});f&&E.set("source",f);let R=await fetch(`${y}/v1/catalog/columns?${E}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});if(R.status===404)throw new Error(`none of those record types resolved: ${m.join(", ")} \u2014 list them with catalog_get.`);if(!R.ok)throw new Error(`common columns fetch failed: ${R.status}`);return Ve(await R.json())}),u.registerTool("catalog_census",{title:"Count the customer's customizations",description:'Count the whole customization catalog: every object by kind AND by whether it can be changed (editable / partner_owned / turbobase_managed / unknown), plus which classes were never collected and why. Call this BEFORE search_catalog when the question is "how much is there" / "what is this account made of" / "how much of this is even ours to change". Takes no arguments.',inputSchema:{}},async()=>{let{baseUrl:m,token:f}=await e(),y=await fetch(`${m}/v1/catalog/census`,{headers:{Authorization:`Bearer ${f}`,Accept:"application/json"}});if(!y.ok)throw new Error(`catalog census failed: ${y.status}`);return Ve(await y.json())}),u.registerTool("search_catalog",{title:"Search the customization catalog",description:'Survey the customer\'s customization catalog by free text \u2014 scripts, custom records, fields, lists, workflows, roles, saved searches, and installed bundles. Matches ids, names AND the generated plain-English explanations, so ask what you actually want ("which object handles rebates?"), not just an exact id. Returns compact {kind, externalId, name, summary, modifiability} hits plus the TRUE match total, so you can see when the page truncated; pass a hit to explain_object for the full definition + prose. A `partner_owned` object CANNOT be edited by this account however well you understand it \u2014 check that before planning a change. Search this before building over a custom record: its definition and explanation are the spec.',inputSchema:{query:N.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:N.enum(x$).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:N.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:m,kind:f,limit:y})=>{let{baseUrl:v,token:E}=await e(),R=new URLSearchParams({q:m});f&&R.set("kind",f),y!==void 0&&R.set("limit",String(y));let z=await fetch(`${v}/v1/catalog/objects?${R}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(!z.ok)throw new Error(`catalog object search failed: ${z.status}`);return Ve(await z.json())}),u.registerTool("explain_object",{title:"Explain one catalog object",description:"Fetch ONE customization-catalog object in depth: its captured definition (or script source, or a bundle\u2019s membership), human label, the generated plain-English explanation (tldr + markdown) of what it is for, and its OWNERSHIP \u2014 `modifiability` plus a one-line reason saying whether this account can change it at all. Address it by the {kind, externalId} a search_catalog hit returns. For a FIELD it also reports `selectTarget`: where a List/Record field ACTUALLY points, resolved to a mirrored table plus the filter needed to read it correctly. Do not infer a target from the field name \u2014 a carrier-named field can point at `entity` (vendors), and building on the wrong guess resolves nothing while looking like an empty table.",inputSchema:{kind:N.enum(x$),externalId:N.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:m,externalId:f})=>{let{baseUrl:y,token:v}=await e(),E=await fetch(`${y}/v1/catalog/objects/${encodeURIComponent(m)}/${encodeURIComponent(f)}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});if(E.status===404)throw new Error(`unknown object ${m}:${f} \u2014 find it with search_catalog.`);if(!E.ok)throw new Error(`catalog object fetch failed: ${E.status}`);return Ve(await E.json())}),u.registerTool("search_documentation",{title:"Search the knowledge base",description:'Search this instance\'s published knowledge base \u2014 internal documentation: processes, policies, playbooks, how-tos. Route questions about how the ORGANISATION works here ("what\'s our receiving process", "how do we handle returns"), and ALWAYS search it before building UI over a custom record \u2014 the KB is the only spec a custom record has. Returns up to `limit` {slug, title, snippet} hits; pass a slug to read_document for the full text. Published release only \u2014 drafts are never returned.',inputSchema:{query:N.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:N.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:m,limit:f})=>{let{baseUrl:y,token:v}=await e(),E=new URLSearchParams({q:m});f!==void 0&&E.set("limit",String(f));let R=await fetch(`${y}/v1/kb/search?${E}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});if(!R.ok)throw new Error(`kb search failed: ${R.status}`);return Ve(await R.json())}),u.registerTool("read_document",{title:"Read a knowledge-base document",description:"Read one published knowledge-base document in full by its slug (from a search_documentation hit). Returns {found, slug, title, body_markdown}. Published release only \u2014 unpublished / admin-only drafts are never returned.",inputSchema:{slug:N.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:m})=>{let{baseUrl:f,token:y}=await e(),v=await fetch(`${f}/v1/kb/document/${encodeURIComponent(m)}`,{headers:{Authorization:`Bearer ${y}`,Accept:"application/json"}});if(!v.ok&&v.status!==404)throw new Error(`kb document fetch failed: ${v.status}`);return Ve(await v.json())}),u.registerTool("generate_types",{title:"Generate types.ts",description:"Generate the instance's types.ts (record shapes + PostgREST ops). Returns the source.",inputSchema:{recordsOnly:N.boolean().optional()}},async({recordsOnly:m})=>{let{baseUrl:f,token:y}=await e();return{content:[{type:"text",text:await Nr({baseUrl:f,token:y,recordsOnly:m})}]}}),u.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:N.string(),event:N.string().optional(),template:N.enum(["require-field","enforce-format","blank"]).optional(),field:N.string().optional(),regex:N.string().optional(),source:N.string().optional(),id:N.string().optional()}},async m=>{let f=to("hook",{recordType:m.recordType,event:m.event,template:m.template,field:m.field,regex:m.regex,source:m.source,id:m.id});return Ve({path:f.relativePath,content:f.content})}),u.registerTool("scaffold_conduit",{title:"Scaffold a conduit",description:"Generate a conduit file body that bridges a canonical record from one source into another (does not write to disk; returns path + content).",inputSchema:{source:N.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:N.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:N.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:N.string().optional().describe("Target record type (defaults to the trigger record type)."),event:N.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:N.string().optional()}},async m=>{let f=to("conduit",{recordType:m.recordType,source:m.source,to:m.to,toRecordType:m.toRecordType,event:m.event,id:m.id});return Ve({path:f.relativePath,content:f.content})}),u.registerTool("mock_test",{title:"Dry-run an extension against samples",description:"Bundle the given source through the production sandbox and run it against samples/ fixtures.",inputSchema:{source:N.string().describe("The extension TS source."),samplesDir:N.string().optional().describe('Samples directory (default "samples").')}},async({source:m,samplesDir:f})=>{let y=v$(process.cwd(),f??"samples"),v=await Qo(y),E=await ji(m,v.map(z=>z.fixture)),R=E.filter(z=>!z.pass).length;return Ve({total:E.length,passed:E.length-R,results:E})}),u.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:N.string(),recordType:N.string(),event:N.string(),source:N.string().describe('Adapter id or "standalone".'),sourceCode:N.string().describe("The verbatim extension TS."),extensionKind:N.string().optional()}},async m=>{let{baseUrl:f,token:y}=await e(),E=await new Q({baseUrl:f,token:y}).deploy({id:m.id,recordType:m.recordType,event:m.event,source:m.source,sourceCode:m.sourceCode,extensionKind:m.extensionKind});return Ve(E)}),u.registerTool("tail_logs",{title:"Tail an extension's logs",description:"Read an extension's log ring buffer (GET /v1/extensions/:id/logs).",inputSchema:{id:N.string(),limit:N.number().int().positive().optional()}},async({id:m,limit:f})=>{let{baseUrl:y,token:v}=await e(),E=new Q({baseUrl:y,token:v});return Ve({id:m,logs:await E.logs(m,f)})}),u.registerTool("apps_list",{title:"List hosted apps",description:"Every hosted app on this instance with its slug, whether it's deployed, and its latest source revision. `sourceRev: null` means the app has no source of record yet (deployed dist only) \u2014 pull will 404 until something is pushed. GET /v1/apps.",inputSchema:{}},async()=>{let{baseUrl:m,token:f}=await e(),y=new Q({baseUrl:m,token:f});return Ve(await y.appsList())}),u.registerTool("apps_create",{title:"Create a hosted app",description:"Create a bare hosted-app row so source can be pushed and a build shipped to it \u2014 the author-led path that needs no proposal. Creates the registration only; it serves nothing until a build is shipped. POST /v1/apps.",inputSchema:{slug:N.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:N.string().optional().describe("Display name (defaults to the slug)."),description:N.string().optional().describe("Short description.")}},async({slug:m,name:f,description:y})=>{let{baseUrl:v,token:E}=await e(),R=new Q({baseUrl:v,token:E});return Ve(await R.appsCreate({slug:m,name:f,description:y}))}),u.registerTool("apps_pull",{title:"Pull a hosted app's source",description:"Fetch the app's latest source tree as {path \u2192 contents} READ-ONLY \u2014 write it to disk, refine it, then apps_push it back. Returns 404 when the app has no source revision yet. NEVER deploys. GET /v1/apps/:id/pull.",inputSchema:{app:N.string().describe("App slug or id.")}},async({app:m})=>{let{baseUrl:f,token:y}=await e(),v=new Q({baseUrl:f,token:y});return Ve(await v.appsPull(m))}),u.registerTool("apps_push",{title:"Push a hosted app's source",description:"Record an edited source tree as the app's NEW source revision, so the instance holds the source of record rather than one laptop. Send the whole tree ({path \u2192 contents}, relative POSIX paths, no node_modules/dist/.git). SOURCE ONLY \u2014 this does not build and does not change what is live; run `turbobase apps deploy <slug>` for that. POST /v1/apps/:id/push.",inputSchema:{app:N.string().describe("App slug or id."),files:N.record(N.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:N.string().optional().describe("Short note stored with the revision.")}},async({app:m,files:f,note:y})=>{let{baseUrl:v,token:E}=await e(),R=new Q({baseUrl:v,token:E});return Ve(await R.appsPush(m,f,{note:y}))});let d=N.object({name:N.string().describe("Field name (lowercase identifier)."),type:N.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:N.boolean().optional()}),b=N.object({slug:N.string().describe("Table slug; the physical table is cr_<slug>."),displayName:N.string().optional(),fields:N.array(d).describe("At least one field."),rowLevelOwner:N.boolean().optional().describe("Restrict non-admins to rows they created.")});return u.registerTool("tables_list",{title:"List custom tables",description:"The instance's customer-authored tables, their fields, and which apps claim each one. Read the `column` on each field \u2014 that is the actual Postgres column an app SELECTs (cf_sa_<name>), which is not the same string as the field name. GET /v1/tables.",inputSchema:{}},async()=>{let{baseUrl:m,token:f}=await e(),y=new Q({baseUrl:m,token:f});return Ve(await y.tablesList())}),u.registerTool("tables_plan",{title:"Preview a table declaration",description:"What these table declarations WOULD do, without doing it. Several apps may claim one table and the instance merges their declarations, so this reports the merged shape and \u2014 the reason to call it \u2014 fails with a conflict report when another claimant already declares one of your field names at a different type. Writes NOTHING. POST /v1/tables/plan.",inputSchema:{tables:N.array(b),claimedBy:N.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:m,claimedBy:f})=>{let{baseUrl:y,token:v}=await e(),E=new Q({baseUrl:y,token:v});return Ve(await E.tablesPlan({tables:m,claimedBy:f}))}),u.registerTool("tables_apply",{title:"Create or evolve custom tables",description:"Record these table declarations and reconcile them into real Postgres tables \u2014 RLS, realtime, and the write path included. Additive: an existing table gains the fields you declare and keeps the ones other claimants declared. Never drops a column, so removing a field from your declaration releases your claim on it rather than deleting data. Prefer declaring tables in the app manifest (public/turbobase.json) so the deploy applies them; use this when authoring outside an app. POST /v1/tables/apply.",inputSchema:{tables:N.array(b),claimedBy:N.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:m,claimedBy:f})=>{let{baseUrl:y,token:v}=await e(),E=new Q({baseUrl:y,token:v});return Ve(await E.tablesApply({tables:m,claimedBy:f}))}),u.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async m=>{let{baseUrl:f,token:y}=await e(),E=await(await fetch(`${f}/v1/catalog/records`,{headers:{Authorization:`Bearer ${y}`,Accept:"application/json"}})).text();return{contents:[{uri:m.href,mimeType:"application/json",text:E}]}}),u.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async m=>{let{baseUrl:f,token:y}=await e(),v=await Nr({baseUrl:f,token:y});return{contents:[{uri:m.href,mimeType:"text/plain",text:v}]}}),u.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async m=>{let f=v$(process.cwd(),"samples"),y=[];try{y=(await fL.readdir(f)).filter(E=>E.endsWith(".json"))}catch{y=[]}let v=await Qo(f);return{contents:[{uri:m.href,mimeType:"application/json",text:JSON.stringify({files:y,samples:v.map(E=>E.fixture)},null,2)}]}}),u.registerResource("recipes","recipes:///",{title:"Intent recipes",description:"Intent recipes (columns / stats / actions per record type + intent), filtered to the instance's installed sources.",mimeType:"application/json"},async m=>{let f=await $$(),y=[];if(f){let{baseUrl:v,token:E}=await e();y=await f.listRecipesForSurface({surface:"mcp-authoring",baseUrl:v,token:E},r)}return{contents:[{uri:m.href,mimeType:"application/json",text:JSON.stringify({recipes:y})}]}}),u}async function yL(t={}){let e=await E$(t),r=new Lc;await e.connect(r)}var x$,k$,S$,T$,R$,mL,gL,A$=O(()=>{h$();b$();Jn();wl();Jo();jr();Rl();Nl();_$();x$=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];S$="turbobase-authoring",T$="0.1.0";R$=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","search_catalog","catalog_census","explain_object","generate_types","scaffold_hook","scaffold_conduit","mock_test","deploy","tail_logs","apps_list","apps_create","apps_pull","apps_push","tables_list","tables_plan","tables_apply"],mL=[...R$,...w$],gL=["catalog:///","types://all","samples:///","recipes:///"]});import{spawn as bm}from"node:child_process";import{promises as we}from"node:fs";import{homedir as bL}from"node:os";import{basename as O$,dirname as Lo,join as At,relative as Dc,resolve as Te,sep as ym}from"node:path";var Lm=Zc(jm(),1),{program:UL,createCommand:ZL,createArgument:qL,createOption:FL,CommanderError:BL,InvalidArgumentError:VL,InvalidOptionArgumentError:HL,Command:Dm,Argument:KL,Option:GL,Help:WL}=Lm.default;wl();Jo();jr();Rl();Tl();import{promises as vg}from"node:fs";function wg(t,e){return e===t?"same-type-merge":"different-type-mint"}var xg=4;function Pl(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=Xn(t,"id"),r=Xn(t,"on"),n=Xn(t,"source"),o=Xn(t,"recordType"),s=/to\s*:\s*\{([^}]*)\}/.exec(t)?.[1]??"",i=Xn(s,"source"),a=Xn(s,"recordType"),c=/cycleBudget\s*:\s*(\d+)/.exec(t);if(!e||!n||!o||!i||!a)throw new Error("could not parse id/from.{source,recordType}/to.{source,recordType} \u2014 is it a reference-shape defineConduit({...})?");return{id:e,on:r,fromSource:n,fromRecordType:o,toSource:i,toRecordType:a,cycleBudget:c?Number(c[1]):xg}}function Xn(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function DT(t){return{recordType:t.recordType,event:t.event??"after_canonicalize_inbound",direction:"inbound",origin:"system",source:t.fromSource,payload:t.payload??{},tenantConfig:t.tenantConfig??{},metadata:{externalId:t.externalId,lines:t.lines??[]},bindings:t.bindings??[],atlasLinks:t.atlasLinks??{}}}async function kg(t,e,r="fixture"){let n=e.name??r,o=[],s;try{s=Pl(t)}catch(c){return{fixtureName:n,conduit:UT(),guards:o,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],logs:[],error:c instanceof Error?c.message:String(c)}}let i=DT(e),a=Object.entries(e.atlasLinks??{}).map(([c,l])=>({key:c,resolved:l}));try{let c=await Ni(t),u=!!(await Xo(c,i,{member:"when",timeoutMs:200})).whenResult;o.push({name:"from.when",status:u?"passed":"failed",detail:u?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let d=e.hop??0;if(o.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${d} vs cycleBudget=${s.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),o.push({name:"opposite-direction-loop",status:"skipped-offline",detail:"reads committed conduit_event rows for the reverse leg \u2014 requires live sandbox state (skipped in fixture mode)"}),o.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!u)return{fixtureName:n,conduit:s,guards:o,whenPassed:u,atlasResolutions:a,wouldWriteBindings:[],logs:[]};let b=await Xo(c,i,{member:"transform",timeoutMs:200}),m=b.effects.logs,f=b.effects.result;if(!f||typeof f!="object")throw new Error(`conduit ${s.id} transform returned no result (expected { patch, createdFrom? })`);let y=f,v=wg(s.fromRecordType,s.toRecordType),{wouldWriteBindings:E,masterAction:R}=MT(s,v,e);return{fixtureName:n,conduit:s,guards:o,whenPassed:u,atlasResolutions:a,transformResult:y,applyBranch:v,wouldWriteBindings:E,masterAction:R,logs:m}}catch(c){return{fixtureName:n,conduit:s,guards:o,whenPassed:!1,atlasResolutions:a,wouldWriteBindings:[],logs:[],error:c instanceof Error?c.message:String(c)}}}function MT(t,e,r){return e==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${r.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:r.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:t.toSource,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${t.toRecordType} master (source_system='${t.toSource}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:t.toSource,externalId:null,role:"origin",why:"this conduit CREATED the new master, so the target is its origin; external_id null until writeback mints it"},{source:t.fromSource,externalId:r.externalId,role:"replica",why:"firing source bound onto the created master (supplementary lineage; best-effort, may collide in a 1\u2192N fan)"}]}}function UT(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",cycleBudget:xg}}async function $g(t){return Promise.reject(new Error("`replay --against sandbox` requires a running sandbox (TURBOBASE_SANDBOX=1 + a local DB). No local Postgres / k3d in this environment \u2014 deferred to a DB-backed run. Use `replay --fixture <file>` for the offline transform/apply-branch dry-run."))}async function Sg(t){let e=await vg.readFile(t,"utf8");return JSON.parse(e)}function Tg(t){return vg.readFile(t,"utf8")}function Eg(t,e){let r=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;if(!e)return t.whenPassed?`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`:`replay ${t.fixtureName} [${r.id}]: WHEN-FAILED (conduit short-circuited)`;let n=[];n.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),n.push(`conduit: ${r.id}`),n.push(`route: ${r.fromSource}.${r.fromRecordType} \u2192 ${r.toSource}.${r.toRecordType}${r.on?` on=${r.on}`:""}`),n.push(""),n.push("guards (dispatch order):");for(let o of t.guards){let s=o.status==="passed"?"\u2713":o.status==="failed"?"\u2717":"\u2298";n.push(` ${s} ${o.name} [${o.status}] \u2014 ${o.detail}`)}if(n.push(""),n.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)n.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let o of t.atlasResolutions)n.push(` ${o.key} \u2192 ${o.resolved===null?"null (no Atlas link \u2014 noted)":o.resolved}`);if(!t.whenPassed)return n.push(""),n.push("transform: SKIPPED (from.when gate did not fire)."),n.join(`
1144
+ `);if(n.push(""),n.push("transform \u2192 patch:"),n.push(ZT(JSON.stringify(t.transformResult?.patch??{},null,2)," ")),t.transformResult?.createdFrom&&n.push(` createdFrom: ${JSON.stringify(t.transformResult.createdFrom)}`),t.logs.length>0){n.push(""),n.push("conduit logs:");for(let o of t.logs)n.push(` [${o.level}] ${o.message}${o.meta?` ${JSON.stringify(o.meta)}`:""}`)}n.push(""),n.push(`apply-branch: ${t.applyBranch}`),n.push(` ${t.masterAction}`),n.push(""),n.push("bindings that WOULD be written (txn_source_link):");for(let o of t.wouldWriteBindings)n.push(` ${o.source} role=${o.role} external_id=${o.externalId??"null"} \u2014 ${o.why}`);return n.join(`
1145
+ `)}function ZT(t,e){return t.split(`
999
1146
  `).map(r=>e+r).join(`
1000
- `)}var xT="2026-01-01",_g="2026-01-01T00:00:00.000Z";function kT(t,e){let r=t.trim().toLowerCase();return r==="boolean"||r==="bool"?!1:r==="smallint"||r==="integer"||r==="int"||r==="int2"||r==="int4"||r==="int8"||r==="bigint"||r==="serial"||r==="bigserial"?1:r==="numeric"||r==="decimal"||r==="real"||r==="double precision"||r==="float4"||r==="float8"||r==="money"?0:r==="date"?xT:r.startsWith("timestamp")?_g:r.startsWith("time")?"00:00:00":r==="json"||r==="jsonb"?e&&/^cf_[a-z]{2}_/.test(e)?1074:e==="raw"||e==="attrs"?{id:"1074",lastModifiedDate:_g}:{}:r==="uuid"?"00000000-0000-0000-0000-000000000000":r==="array"||r.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function $T(t){let e={};for(let r of t.columns)e[r.name]=kT(r.pgType,r.name);return e}function ST(t,e={}){let r=e.event??"before_save";return{name:`${t.recordType} ${r} (generated)`,context:{recordType:t.recordType,event:r,source:t.source,payload:$T(t)},expect:e.expect??"pass"}}function vg(t,e={}){return t.map(r=>({recordType:r.recordType,fixture:ST(r,e)}))}import{promises as xg}from"node:fs";import{join as kg,relative as TT,sep as ET}from"node:path";var RT=67324752,PT=33639248,AT=101010256,IT=(()=>{let t=new Uint32Array(256);for(let e=0;e<256;e++){let r=e;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;t[e]=r>>>0}return t})();function OT(t){let e=4294967295;for(let r=0;r<t.length;r++)e=IT[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}async function CT(t){let e=[];async function r(n){let o=await xg.readdir(n,{withFileTypes:!0});for(let s of o){let i=kg(n,s.name);s.isDirectory()?await r(i):s.isFile()&&e.push(TT(t,i).split(ET).join("/"))}}return await r(t),e.sort(),e}async function $g(t){let e=await CT(t),r=[],n=[],o=0;for(let a of e){let c=Buffer.from(a,"utf8"),l=await xg.readFile(kg(t,a)),u=OT(l),d=Buffer.alloc(30+c.length);d.writeUInt32LE(RT,0),d.writeUInt16LE(20,4),d.writeUInt16LE(0,6),d.writeUInt16LE(0,8),d.writeUInt32LE(u,14),d.writeUInt32LE(l.length,18),d.writeUInt32LE(l.length,22),d.writeUInt16LE(c.length,26),c.copy(d,30),r.push(d,l);let b=Buffer.alloc(46+c.length);b.writeUInt32LE(PT,0),b.writeUInt16LE(20,4),b.writeUInt16LE(20,6),b.writeUInt16LE(0,10),b.writeUInt32LE(u,16),b.writeUInt32LE(l.length,20),b.writeUInt32LE(l.length,24),b.writeUInt16LE(c.length,28),b.writeUInt32LE(o,42),c.copy(b,46),n.push(b),o+=d.length+l.length}let s=Buffer.concat(n),i=Buffer.alloc(22);return i.writeUInt32LE(AT,0),i.writeUInt16LE(e.length,8),i.writeUInt16LE(e.length,10),i.writeUInt32LE(s.length,12),i.writeUInt32LE(o,16),{buffer:Buffer.concat([...r,s,i]),fileCount:e.length}}function zT(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":"hook"}function Ii(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function NT(t){let e=Sg(t,"from"),r=Sg(t,"to");return{fromSource:e?Ii(e,"source"):void 0,fromRecordType:e?Ii(e,"recordType"):void 0,toSource:r?Ii(r,"source"):void 0,toRecordType:r?Ii(r,"recordType"):void 0}}function Sg(t,e){let r=new RegExp(`\\b${e}\\s*:\\s*\\{`).exec(t);if(!r)return null;let n=0,o=r.index+r[0].length-1;for(let s=o;s<t.length;s+=1){let i=t[s];if(i==="{")n+=1;else if(i==="}"&&(n-=1,n===0))return t.slice(o+1,s)}return null}function jT(t){let e=/idempotencyKey\s*:/.exec(t);if(!e)return null;let r=e.index+e[0].length,n=0,o=null,s=r;for(;s<t.length;s+=1){let c=t[s];if(o){c==="\\"?s+=1:c===o&&(o=null);continue}if(c==="'"||c==='"'||c==="`"){o=c;continue}if(c==="("||c==="{"||c==="[")n+=1;else if(c===")"||c==="}"||c==="]"){if(n===0)break;n-=1}else if(c===","&&n===0)break}let i=t.slice(r,s),a=i.indexOf("=>");return a>=0?i.slice(a+2):i}function LT(t,e){let r=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return r?Number(r[1]):void 0}function MT(t){return/\bcreatedFrom\b/.test(t)}function Tg(t){let e=zT(t),r=[];if(e==="hook")return{kind:e,warnings:r};let{fromSource:n,toSource:o,fromRecordType:s,toRecordType:i}=NT(t);n&&o&&n===o&&r.push({rule:"same-source-conduit",message:`from.source and to.source are both '${n}' \u2014 a conduit that doesn't cross sources isn't a conduit.`,fix:`Make 'to.source' a DIFFERENT source than 'from.source', or rewrite this as a hook (\`turbobase ext new hook --record ${s??"<type>"}\`) \u2014 a same-source transform belongs on the write path, not the cross-source bridge.`});let a=jT(t);if(a!==null){let l=/\bexternalId\b/.test(a),u=/\bfromSource\b/.test(a);!l&&!u&&r.push({rule:"weak-idempotency-key",message:"idempotencyKey omits both ctx.externalId and ctx.fromSource \u2014 two distinct re-fires (different records, or the same record from different sources) collapse onto one conduit_event ledger row and one of them is silently dropped as a duplicate.",fix:"Include `ctx.externalId` (and, for multi-source triggers, `ctx.fromSource`) in the key, e.g. `idempotencyKey: (ctx) => `${ctx.fromSource}:${ctx.externalId}``."})}s&&i&&s!==i&&!MT(t)&&r.push({rule:"missing-created-from",message:`this conduit bridges '${s}' \u2192 '${i}' (different record types) but its transform never returns 'createdFrom' \u2014 the created ${i} won't carry a lineage pointer back to its origin, so the reverse leg can't find it.`,fix:"Return `createdFrom: { source: ctx.fromSource, recordType: ctx.recordType, externalId: ctx.externalId }` from the transform so the counterpart is bound to the master by construction."});let c=LT(t,"cycleBudget");return c!==void 0&&(c<1?r.push({rule:"cycle-budget-too-low",message:`cycleBudget=${c} is below 1 \u2014 the cycle fuse trips before the first hop (hop 0 >= budget), so this conduit can never fire.`,fix:"Set cycleBudget to at least 1 (the engine default is 4, a sane range is 1\u201320)."}):c>20&&r.push({rule:"cycle-budget-too-high",message:`cycleBudget=${c} is far above the 20 ceiling \u2014 the max-hop safety fuse is effectively disarmed, so a misconfigured conduit pair can bounce a record dozens of times before anything stops it.`,fix:"Lower cycleBudget into the 1\u201320 range (the engine default is 4); a legitimate chain rarely needs more than a handful of hops."})),{kind:e,warnings:r}}function Eg(t,e,r={}){let n=r.warn??(a=>a),o=r.ok??(a=>a),s=r.dim??(a=>a),i=[];if(i.push(`lint: ${t} (${e.kind})`),e.warnings.length===0)return i.push(` ${o("ok")} \u2014 no warnings.`),i.join(`
1147
+ `)}var qT="2026-01-01",Rg="2026-01-01T00:00:00.000Z";function FT(t,e){let r=t.trim().toLowerCase();return r==="boolean"||r==="bool"?!1:r==="smallint"||r==="integer"||r==="int"||r==="int2"||r==="int4"||r==="int8"||r==="bigint"||r==="serial"||r==="bigserial"?1:r==="numeric"||r==="decimal"||r==="real"||r==="double precision"||r==="float4"||r==="float8"||r==="money"?0:r==="date"?qT:r.startsWith("timestamp")?Rg:r.startsWith("time")?"00:00:00":r==="json"||r==="jsonb"?e&&/^cf_[a-z]{2}_/.test(e)?1074:e==="raw"||e==="attrs"?{id:"1074",lastModifiedDate:Rg}:{}:r==="uuid"?"00000000-0000-0000-0000-000000000000":r==="array"||r.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function BT(t){let e={};for(let r of t.columns)e[r.name]=FT(r.pgType,r.name);return e}function VT(t,e={}){let r=e.event??"before_save";return{name:`${t.recordType} ${r} (generated)`,context:{recordType:t.recordType,event:r,source:t.source,payload:BT(t)},expect:e.expect??"pass"}}function Pg(t,e={}){return t.map(r=>({recordType:r.recordType,fixture:VT(r,e)}))}import{promises as Ag}from"node:fs";import{join as Ig,relative as HT,sep as KT}from"node:path";var GT=67324752,WT=33639248,JT=101010256,YT=(()=>{let t=new Uint32Array(256);for(let e=0;e<256;e++){let r=e;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;t[e]=r>>>0}return t})();function XT(t){let e=4294967295;for(let r=0;r<t.length;r++)e=YT[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}async function QT(t){let e=[];async function r(n){let o=await Ag.readdir(n,{withFileTypes:!0});for(let s of o){let i=Ig(n,s.name);s.isDirectory()?await r(i):s.isFile()&&e.push(HT(t,i).split(KT).join("/"))}}return await r(t),e.sort(),e}async function Og(t){let e=await QT(t),r=[],n=[],o=0;for(let a of e){let c=Buffer.from(a,"utf8"),l=await Ag.readFile(Ig(t,a)),u=XT(l),d=Buffer.alloc(30+c.length);d.writeUInt32LE(GT,0),d.writeUInt16LE(20,4),d.writeUInt16LE(0,6),d.writeUInt16LE(0,8),d.writeUInt32LE(u,14),d.writeUInt32LE(l.length,18),d.writeUInt32LE(l.length,22),d.writeUInt16LE(c.length,26),c.copy(d,30),r.push(d,l);let b=Buffer.alloc(46+c.length);b.writeUInt32LE(WT,0),b.writeUInt16LE(20,4),b.writeUInt16LE(20,6),b.writeUInt16LE(0,10),b.writeUInt32LE(u,16),b.writeUInt32LE(l.length,20),b.writeUInt32LE(l.length,24),b.writeUInt16LE(c.length,28),b.writeUInt32LE(o,42),c.copy(b,46),n.push(b),o+=d.length+l.length}let s=Buffer.concat(n),i=Buffer.alloc(22);return i.writeUInt32LE(JT,0),i.writeUInt16LE(e.length,8),i.writeUInt16LE(e.length,10),i.writeUInt32LE(s.length,12),i.writeUInt32LE(o,16),{buffer:Buffer.concat([...r,s,i]),fileCount:e.length}}function e0(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":"hook"}function Li(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function t0(t){let e=Cg(t,"from"),r=Cg(t,"to");return{fromSource:e?Li(e,"source"):void 0,fromRecordType:e?Li(e,"recordType"):void 0,toSource:r?Li(r,"source"):void 0,toRecordType:r?Li(r,"recordType"):void 0}}function Cg(t,e){let r=new RegExp(`\\b${e}\\s*:\\s*\\{`).exec(t);if(!r)return null;let n=0,o=r.index+r[0].length-1;for(let s=o;s<t.length;s+=1){let i=t[s];if(i==="{")n+=1;else if(i==="}"&&(n-=1,n===0))return t.slice(o+1,s)}return null}function r0(t){let e=/idempotencyKey\s*:/.exec(t);if(!e)return null;let r=e.index+e[0].length,n=0,o=null,s=r;for(;s<t.length;s+=1){let c=t[s];if(o){c==="\\"?s+=1:c===o&&(o=null);continue}if(c==="'"||c==='"'||c==="`"){o=c;continue}if(c==="("||c==="{"||c==="[")n+=1;else if(c===")"||c==="}"||c==="]"){if(n===0)break;n-=1}else if(c===","&&n===0)break}let i=t.slice(r,s),a=i.indexOf("=>");return a>=0?i.slice(a+2):i}function n0(t,e){let r=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return r?Number(r[1]):void 0}function o0(t){return/\bcreatedFrom\b/.test(t)}function zg(t){let e=e0(t),r=[];if(e==="hook")return{kind:e,warnings:r};let{fromSource:n,toSource:o,fromRecordType:s,toRecordType:i}=t0(t);n&&o&&n===o&&r.push({rule:"same-source-conduit",message:`from.source and to.source are both '${n}' \u2014 a conduit that doesn't cross sources isn't a conduit.`,fix:`Make 'to.source' a DIFFERENT source than 'from.source', or rewrite this as a hook (\`turbobase ext new hook --record ${s??"<type>"}\`) \u2014 a same-source transform belongs on the write path, not the cross-source bridge.`});let a=r0(t);if(a!==null){let l=/\bexternalId\b/.test(a),u=/\bfromSource\b/.test(a);!l&&!u&&r.push({rule:"weak-idempotency-key",message:"idempotencyKey omits both ctx.externalId and ctx.fromSource \u2014 two distinct re-fires (different records, or the same record from different sources) collapse onto one conduit_event ledger row and one of them is silently dropped as a duplicate.",fix:"Include `ctx.externalId` (and, for multi-source triggers, `ctx.fromSource`) in the key, e.g. `idempotencyKey: (ctx) => `${ctx.fromSource}:${ctx.externalId}``."})}s&&i&&s!==i&&!o0(t)&&r.push({rule:"missing-created-from",message:`this conduit bridges '${s}' \u2192 '${i}' (different record types) but its transform never returns 'createdFrom' \u2014 the created ${i} won't carry a lineage pointer back to its origin, so the reverse leg can't find it.`,fix:"Return `createdFrom: { source: ctx.fromSource, recordType: ctx.recordType, externalId: ctx.externalId }` from the transform so the counterpart is bound to the master by construction."});let c=n0(t,"cycleBudget");return c!==void 0&&(c<1?r.push({rule:"cycle-budget-too-low",message:`cycleBudget=${c} is below 1 \u2014 the cycle fuse trips before the first hop (hop 0 >= budget), so this conduit can never fire.`,fix:"Set cycleBudget to at least 1 (the engine default is 4, a sane range is 1\u201320)."}):c>20&&r.push({rule:"cycle-budget-too-high",message:`cycleBudget=${c} is far above the 20 ceiling \u2014 the max-hop safety fuse is effectively disarmed, so a misconfigured conduit pair can bounce a record dozens of times before anything stops it.`,fix:"Lower cycleBudget into the 1\u201320 range (the engine default is 4); a legitimate chain rarely needs more than a handful of hops."})),{kind:e,warnings:r}}function Ng(t,e,r={}){let n=r.warn??(a=>a),o=r.ok??(a=>a),s=r.dim??(a=>a),i=[];if(i.push(`lint: ${t} (${e.kind})`),e.warnings.length===0)return i.push(` ${o("ok")} \u2014 no warnings.`),i.join(`
1001
1148
  `);for(let a of e.warnings)i.push(` ${n("WARN")} ${s(`[${a.rule}]`)} ${a.message}`),i.push(` ${s("\u2192 fix:")} ${a.fix}`);return i.push(`
1002
1149
  lint: ${n(`${e.warnings.length} warning(s).`)}`),i.join(`
1003
- `)}function Rg(t){return t.cases.filter(e=>e.status==="failed").length}function Jo(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function DT(t){let e=Rg(t),r=[];r.push('<?xml version="1.0" encoding="UTF-8"?>'),r.push(`<testsuite name="${Jo(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let n of t.cases){let o=` <testcase name="${Jo(n.name)}"`;if(n.status==="passed"){r.push(`${o} />`);continue}r.push(`${o}>`);let s=n.detail??"failed",i=n.type?` type="${Jo(n.type)}"`:"";r.push(` <failure${i} message="${Jo(s)}">${Jo(s)}</failure>`),r.push(" </testcase>")}return r.push("</testsuite>"),`${r.join(`
1150
+ `)}function jg(t){return t.cases.filter(e=>e.status==="failed").length}function ts(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function s0(t){let e=jg(t),r=[];r.push('<?xml version="1.0" encoding="UTF-8"?>'),r.push(`<testsuite name="${ts(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let n of t.cases){let o=` <testcase name="${ts(n.name)}"`;if(n.status==="passed"){r.push(`${o} />`);continue}r.push(`${o}>`);let s=n.detail??"failed",i=n.type?` type="${ts(n.type)}"`:"";r.push(` <failure${i} message="${ts(s)}">${ts(s)}</failure>`),r.push(" </testcase>")}return r.push("</testsuite>"),`${r.join(`
1004
1151
  `)}
1005
- `}function UT(t){let e={suite:t.name,tests:t.cases.length,failures:Rg(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
1006
- `}function Oi(t,e){return e==="junit"?DT(t):UT(t)}var bt={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",invert:"\x1B[7m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",grey:"\x1B[90m"},Ke={hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",clearLine:"\x1B[2K",clearToEnd:"\x1B[0J",col0:"\r",cursorUp:t=>`\x1B[${t}A`},eo=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ct={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},Pg=/\x1b\[[0-9;]*m/g;function vr(t){return t.replace(Pg,"").length}function kl(t,e){return e<=0?1:Math.max(1,Math.ceil(vr(t)/e))}function ZT(){return process.env.NO_COLOR!=null&&process.env.NO_COLOR!==""?!1:process.env.FORCE_COLOR&&process.env.FORCE_COLOR!=="0"?!0:process.env.TERM==="dumb"?!1:process.stdout.isTTY===!0}var $l=ZT();function wt(){return $l}function Sl(t){$l=t}function Ht(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function zt(t,e){return $l?`${t}${e}${bt.reset}`:e}var x={bold:t=>zt(bt.bold,t),dim:t=>zt(bt.dim,t),red:t=>zt(bt.red,t),green:t=>zt(bt.green,t),yellow:t=>zt(bt.yellow,t),blue:t=>zt(bt.blue,t),magenta:t=>zt(bt.magenta,t),cyan:t=>zt(bt.cyan,t),grey:t=>zt(bt.grey,t)};var lt={success:t=>`${x.green("\u2713")} ${t}`,error:t=>`${x.red("\u2716")} ${t}`,warn:t=>`${x.yellow("\u26A0")} ${t}`,info:t=>`${x.dim("\xB7")} ${t}`,step:t=>`${x.cyan("\u25B8")} ${t}`},jr={add:t=>x.green(`+ ${t}`),change:t=>x.yellow(`~ ${t}`),destroy:t=>x.red(`- ${t}`)},qT=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),FT=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),BT=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function to(t){let e=t.toLowerCase();return qT.has(e)?x.green(t):FT.has(e)?x.red(t):BT.has(e)?x.yellow(t):t}function Lr(t,e=[]){let r=Math.max(vr(t),...e.map(vr),0),n=r+2,o=x.cyan(Ct.v),s=a=>` ${a}${" ".repeat(r-vr(a))} `,i=[x.cyan(`${Ct.tl}${Ct.h.repeat(n)}${Ct.tr}`),`${o}${x.bold(s(t))}${o}`];if(e.length){i.push(`${x.cyan(Ct.ml)}${x.dim(Ct.h.repeat(n))}${x.cyan(Ct.mr)}`);for(let a of e)i.push(`${o}${s(a)}${o}`)}return i.push(x.cyan(`${Ct.bl}${Ct.h.repeat(n)}${Ct.br}`)),i.join(`
1007
- `)}function _n(t,e={}){let r=e.indent??" ",n=e.gap??" ",o=e.head?[e.head,...t]:t,s=Math.max(0,...o.map(l=>l.length)),i=[];for(let l=0;l<s;l+=1)i[l]=Math.max(0,...o.map(u=>vr(u[l]??"")));let a=l=>{let u=l.map((d,b)=>{let m=d??"";return b===l.length-1?m:m+" ".repeat(Math.max(0,i[b]-vr(m)))});return r+u.join(n)},c=[];e.head&&(c.push(a(e.head.map(l=>x.bold(l)))),c.push(a(e.head.map((l,u)=>x.dim("\u2500".repeat(i[u]??vr(l)))))));for(let l of t)c.push(a(l));return c.join(`
1008
- `)}function Tl(t="the CLI for your Turbobase instance"){let e=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D"," \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2557 "," \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u255A\u2550\u2550\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D "," \u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"];return`${wt()?e.map(n=>zt(bt.cyan,n)).join(`
1152
+ `}function i0(t){let e={suite:t.name,tests:t.cases.length,failures:jg(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
1153
+ `}function Di(t,e){return e==="junit"?s0(t):i0(t)}var wt={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",invert:"\x1B[7m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",grey:"\x1B[90m"},Ke={hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",clearLine:"\x1B[2K",clearToEnd:"\x1B[0J",col0:"\r",cursorUp:t=>`\x1B[${t}A`},Qn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Nt={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},Lg=/\x1b\[[0-9;]*m/g;function vr(t){return t.replace(Lg,"").length}function Al(t,e){return e<=0?1:Math.max(1,Math.ceil(vr(t)/e))}function a0(){return process.env.NO_COLOR!=null&&process.env.NO_COLOR!==""?!1:process.env.FORCE_COLOR&&process.env.FORCE_COLOR!=="0"?!0:process.env.TERM==="dumb"?!1:process.stdout.isTTY===!0}var Il=a0();function Ye(){return Il}function Ol(t){Il=t}function St(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function jt(t,e){return Il?`${t}${e}${wt.reset}`:e}var w={bold:t=>jt(wt.bold,t),dim:t=>jt(wt.dim,t),red:t=>jt(wt.red,t),green:t=>jt(wt.green,t),yellow:t=>jt(wt.yellow,t),blue:t=>jt(wt.blue,t),magenta:t=>jt(wt.magenta,t),cyan:t=>jt(wt.cyan,t),grey:t=>jt(wt.grey,t)};var ut={success:t=>`${w.green("\u2713")} ${t}`,error:t=>`${w.red("\u2716")} ${t}`,warn:t=>`${w.yellow("\u26A0")} ${t}`,info:t=>`${w.dim("\xB7")} ${t}`,step:t=>`${w.cyan("\u25B8")} ${t}`},Lr={add:t=>w.green(`+ ${t}`),change:t=>w.yellow(`~ ${t}`),destroy:t=>w.red(`- ${t}`)},c0=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),l0=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),u0=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function eo(t){let e=t.toLowerCase();return c0.has(e)?w.green(t):l0.has(e)?w.red(t):u0.has(e)?w.yellow(t):t}function Dr(t,e=[]){let r=Math.max(vr(t),...e.map(vr),0),n=r+2,o=w.cyan(Nt.v),s=a=>` ${a}${" ".repeat(r-vr(a))} `,i=[w.cyan(`${Nt.tl}${Nt.h.repeat(n)}${Nt.tr}`),`${o}${w.bold(s(t))}${o}`];if(e.length){i.push(`${w.cyan(Nt.ml)}${w.dim(Nt.h.repeat(n))}${w.cyan(Nt.mr)}`);for(let a of e)i.push(`${o}${s(a)}${o}`)}return i.push(w.cyan(`${Nt.bl}${Nt.h.repeat(n)}${Nt.br}`)),i.join(`
1154
+ `)}function Mr(t,e={}){let r=e.indent??" ",n=e.gap??" ",o=e.head?[e.head,...t]:t,s=Math.max(0,...o.map(l=>l.length)),i=[];for(let l=0;l<s;l+=1)i[l]=Math.max(0,...o.map(u=>vr(u[l]??"")));let a=l=>{let u=l.map((d,b)=>{let m=d??"";return b===l.length-1?m:m+" ".repeat(Math.max(0,i[b]-vr(m)))});return r+u.join(n)},c=[];e.head&&(c.push(a(e.head.map(l=>w.bold(l)))),c.push(a(e.head.map((l,u)=>w.dim("\u2500".repeat(i[u]??vr(l)))))));for(let l of t)c.push(a(l));return c.join(`
1155
+ `)}function Cl(t="the CLI for your Turbobase instance"){let e=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D"," \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2557 "," \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u255A\u2550\u2550\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D "," \u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"];return`${Ye()?e.map(n=>jt(wt.cyan,n)).join(`
1009
1156
  `):e.join(`
1010
1157
  `)}
1011
- ${x.dim(` ${t}`)}`}var Nt=t=>{process.stderr.write(t)};function Ci(){return wt()&&process.stderr.isTTY===!0}function Ag(t,e=15){let r=Math.max(0,Math.min(100,t??0)),n=Math.round(r/100*e);return`${"\u2588".repeat(n)}${x.dim("\u2591".repeat(e-n))}`}async function fe(t,e){let r=Ci(),n=0,o;r&&(Nt(Ke.hideCursor),o=setInterval(()=>{Nt(`${Ke.col0}${Ke.clearLine}${x.magenta(eo[n++%eo.length])} ${t}`)},80));let s=()=>{o&&clearInterval(o),r&&Nt(`${Ke.col0}${Ke.clearLine}${Ke.showCursor}`)};try{let i=await e();return s(),r&&Nt(`${lt.success(t)}
1012
- `),i}catch(i){throw s(),r&&Nt(`${lt.error(t)}
1013
- `),i}}function El(t){let e=0,r={stage:"queued"},n=!1,o=()=>{let c=x.magenta(eo[e%eo.length]),l=x.cyan(r.stage),u=r.runStatus?` ${x.dim(`(${r.runStatus})`)}`:"",d=`${String(Math.round(r.percent??0)).padStart(3)}%`;return`${c} ${t} ${x.dim("\u25B8")} ${l}${u} ${Ag(r.percent)} ${d}`},s=()=>{Nt(`${Ke.col0}${Ke.clearLine}${o()}`),n=!0},i=()=>{n&&Nt(`${Ke.col0}${Ke.clearLine}`),n=!1};Nt(Ke.hideCursor);let a=setInterval(()=>{e+=1,s()},80);return{log(c){i(),Nt(`${c}
1014
- `),s()},status(c){r=c,s()},done(c){clearInterval(a),i(),Nt(Ke.showCursor);let l=c.stage!=="failed",u=`${t} ${x.dim("\u25B8")} ${VT(c.stage)}${c.runStatus?` (${c.runStatus})`:""}`;Nt(`${l?lt.success(u):lt.error(u)}
1015
- `)},stop(){clearInterval(a),i(),Nt(Ke.showCursor)}}}function VT(t){return t==="completed"?x.green(t):t==="failed"?x.red(t):x.cyan(t)}function Kt(t,e,r={}){return new Promise((n,o)=>{let s=e.findIndex(y=>!y.disabled);if(s===-1){o(new Error("no selectable options"));return}let i=r.defaultIndex!==void 0&&!e[r.defaultIndex]?.disabled?r.defaultIndex:s,a=y=>{process.stderr.write(y)},c=process.stdin,l=c.isRaw;c.setRawMode?.(!0),c.resume(),a(`${x.bold(x.cyan("?"))} ${x.bold(t)}
1016
- `),a(`${x.dim(" (\u2191/\u2193 to move, enter to select, ctrl+c to abort)")}
1017
- `),a(Ke.hideCursor);let u=0,d=()=>{let y=process.stderr.columns??process.stdout.columns??80;u>0&&(a(Ke.cursorUp(u)),a(Ke.clearToEnd));let v=0;for(let E=0;E<e.length;E+=1){let R=e[E],z=E===i,V=z?x.cyan("\u25B6"):" ",J=R.disabled?x.grey(R.label):z?x.bold(x.cyan(R.label)):R.label,He=R.description?` ${x.dim(R.description)}`:"",Xe=` ${V} ${J}${He}`;a(`\r${Xe}
1018
- `),v+=kl(Xe,y)}u=v},b=()=>{c.removeListener("data",f),c.setRawMode?.(l??!1),c.pause(),a(Ke.showCursor)},m=y=>{let v=i;for(let E=0;E<e.length;E+=1)if(v=(v+y+e.length)%e.length,!e[v].disabled){i=v;return}},f=y=>{let v=y.toString("utf8");if(v===""||v==="q"){b(),a(`
1158
+ ${w.dim(` ${t}`)}`}var Lt=t=>{process.stderr.write(t)};function Mi(){return Ye()&&process.stderr.isTTY===!0}function Dg(t,e=15){let r=Math.max(0,Math.min(100,t??0)),n=Math.round(r/100*e);return`${"\u2588".repeat(n)}${w.dim("\u2591".repeat(e-n))}`}async function se(t,e){let r=Mi(),n=0,o;r&&(Lt(Ke.hideCursor),o=setInterval(()=>{Lt(`${Ke.col0}${Ke.clearLine}${w.magenta(Qn[n++%Qn.length])} ${t}`)},80));let s=()=>{o&&clearInterval(o),r&&Lt(`${Ke.col0}${Ke.clearLine}${Ke.showCursor}`)};try{let i=await e();return s(),r&&Lt(`${ut.success(t)}
1159
+ `),i}catch(i){throw s(),r&&Lt(`${ut.error(t)}
1160
+ `),i}}function zl(t){let e=0,r={stage:"queued"},n=!1,o=()=>{let c=w.magenta(Qn[e%Qn.length]),l=w.cyan(r.stage),u=r.runStatus?` ${w.dim(`(${r.runStatus})`)}`:"",d=`${String(Math.round(r.percent??0)).padStart(3)}%`;return`${c} ${t} ${w.dim("\u25B8")} ${l}${u} ${Dg(r.percent)} ${d}`},s=()=>{Lt(`${Ke.col0}${Ke.clearLine}${o()}`),n=!0},i=()=>{n&&Lt(`${Ke.col0}${Ke.clearLine}`),n=!1};Lt(Ke.hideCursor);let a=setInterval(()=>{e+=1,s()},80);return{log(c){i(),Lt(`${c}
1161
+ `),s()},status(c){r=c,s()},done(c){clearInterval(a),i(),Lt(Ke.showCursor);let l=c.stage!=="failed",u=`${t} ${w.dim("\u25B8")} ${d0(c.stage)}${c.runStatus?` (${c.runStatus})`:""}`;Lt(`${l?ut.success(u):ut.error(u)}
1162
+ `)},stop(){clearInterval(a),i(),Lt(Ke.showCursor)}}}function d0(t){return t==="completed"?w.green(t):t==="failed"?w.red(t):w.cyan(t)}function Tt(t,e,r={}){return new Promise((n,o)=>{let s=e.findIndex(y=>!y.disabled);if(s===-1){o(new Error("no selectable options"));return}let i=r.defaultIndex!==void 0&&!e[r.defaultIndex]?.disabled?r.defaultIndex:s,a=y=>{process.stderr.write(y)},c=process.stdin,l=c.isRaw;c.setRawMode?.(!0),c.resume(),a(`${w.bold(w.cyan("?"))} ${w.bold(t)}
1163
+ `),a(`${w.dim(" (\u2191/\u2193 to move, enter to select, ctrl+c to abort)")}
1164
+ `),a(Ke.hideCursor);let u=0,d=()=>{let y=process.stderr.columns??process.stdout.columns??80;u>0&&(a(Ke.cursorUp(u)),a(Ke.clearToEnd));let v=0;for(let E=0;E<e.length;E+=1){let R=e[E],z=E===i,H=z?w.cyan("\u25B6"):" ",Y=R.disabled?w.grey(R.label):z?w.bold(w.cyan(R.label)):R.label,He=R.description?` ${w.dim(R.description)}`:"",Qe=` ${H} ${Y}${He}`;a(`\r${Qe}
1165
+ `),v+=Al(Qe,y)}u=v},b=()=>{c.removeListener("data",f),c.setRawMode?.(l??!1),c.pause(),a(Ke.showCursor)},m=y=>{let v=i;for(let E=0;E<e.length;E+=1)if(v=(v+y+e.length)%e.length,!e[v].disabled){i=v;return}},f=y=>{let v=y.toString("utf8");if(v===""||v==="q"){b(),a(`
1019
1166
  `),o(new Error("aborted"));return}if(v==="\r"||v===`
1020
- `){let R=e[i];if(R.disabled)return;b(),n(R.value);return}if(v==="\x1B[A"||v==="k"){m(-1),d();return}if(v==="\x1B[B"||v==="j"){m(1),d();return}let E=Number(v);Number.isFinite(E)&&E>=1&&E<=e.length&&!e[E-1].disabled&&(i=E-1,d())};c.on("data",f),d()})}function Og(t,e){return`${to(t)}${" ".repeat(Math.max(0,e-t.length))}`}var HT=t=>new Promise(e=>setTimeout(e,t));function Ig(t){let e=t.toRecordType?`${t.toSource}/${t.toRecordType}`:t.toSource,r=t.reason?` reason="${t.reason}"`:"",n=t.fromExternalId?` ext=${t.fromExternalId}`:"",o=t.toMasterTable&&t.toMasterRowId?` master=${t.toMasterTable}/${t.toMasterRowId}`:"";return`[${t.updatedAt}] ${Og(t.state,9)} ${t.conduitId} \u2192 ${e}${n} hop=${t.hop}${o}${r}`}async function Cg(t,e,r={}){let n=r.sink??(u=>{process.stdout.write(`${u}
1021
- `)}),o=r.sleep??HT,s=r.intervalMs??2e3,i=await t.conduitEvents(e,{limit:r.limit??100});if(i.length===0&&!r.follow)return n(`logs: no conduit_event rows for ${e}.`),0;let a=0,c="";for(let u of[...i].reverse())n(Ig(u)),a+=1,u.updatedAt>c&&(c=u.updatedAt);if(!r.follow)return a;let l=r.maxPolls??Number.POSITIVE_INFINITY;for(let u=0;u<l;u+=1){await o(s);let d=await t.conduitEvents(e,{since:c||void 0,limit:200});for(let b of[...d].reverse())n(Ig(b)),a+=1,b.updatedAt>c&&(c=b.updatedAt)}return a}function KT(t){let e=t.externalId??"\u2014",r=t.createdByConduit?` via=${t.createdByConduit}`:"",n=t.lastError?` last_error="${t.lastError}"`:"";return`${t.id} ${Og(t.writeStatus,9)} ${t.sourceSystem}/${e} role=${t.role} master=${t.masterTable}/${t.masterRowId}${r}${n}`}async function zg(t,e={}){let r=e.sink??(o=>{process.stdout.write(`${o}
1022
- `)});if(e.retry){let o=await t.retryBinding(e.retry);return r(`binding: re-enqueued fan-out for ${o.id} \u2192 ${o.sourceSystem} (master ${o.masterTable}/${o.masterRowId}).`),{mode:"retry",id:o.id,retried:o.retried}}let n=await t.bindings({status:e.status,limit:e.limit});if(n.length===0)return r(e.status?`binding: no bindings with write_status='${e.status}'.`:"binding: no bindings."),{mode:"list",count:0};for(let o of n)r(KT(o));return r(`
1023
- binding: ${n.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:n.length}}Rl();function jg(t,e={}){return t.learningIngestError?{level:"warn",message:`warning: learning ingest was not queued (${t.learningIngestError}). The version is live, but the findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT read. Re-deploy to retry.`}:t.learningIngestTaskId?t.learningSourceRev===null?{level:"warn",message:"warning: this app has no pushed source, so the ingest has nothing to read. The findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT ingested \u2014 deploy uploads the built bundle, `apps push` records the markdown. Run `turbobase apps push <app> .`, then deploy again."}:typeof t.learningSourceRev=="number"?e.localDocsModifiedAt&&t.learningSourceAt&&e.localDocsModifiedAt.getTime()>Date.parse(t.learningSourceAt)?{level:"warn",message:`warning: learning ingest queued (task ${t.learningIngestTaskId}), but it reads source rev ${t.learningSourceRev} and your standing markdown has changed since that push. Those findings will NOT be ingested. Run \`turbobase apps push <app> .\`, then deploy again.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}) \u2014 reading source rev ${t.learningSourceRev}.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}).`}:null}var Pl=".github/workflows/turbobase-release-deploy.yml",YT=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
1167
+ `){let R=e[i];if(R.disabled)return;b(),n(R.value);return}if(v==="\x1B[A"||v==="k"){m(-1),d();return}if(v==="\x1B[B"||v==="j"){m(1),d();return}let E=Number(v);Number.isFinite(E)&&E>=1&&E<=e.length&&!e[E-1].disabled&&(i=E-1,d())};c.on("data",f),d()})}function Ug(t,e){return`${eo(t)}${" ".repeat(Math.max(0,e-t.length))}`}var p0=t=>new Promise(e=>setTimeout(e,t));function Mg(t){let e=t.toRecordType?`${t.toSource}/${t.toRecordType}`:t.toSource,r=t.reason?` reason="${t.reason}"`:"",n=t.fromExternalId?` ext=${t.fromExternalId}`:"",o=t.toMasterTable&&t.toMasterRowId?` master=${t.toMasterTable}/${t.toMasterRowId}`:"";return`[${t.updatedAt}] ${Ug(t.state,9)} ${t.conduitId} \u2192 ${e}${n} hop=${t.hop}${o}${r}`}async function Zg(t,e,r={}){let n=r.sink??(u=>{process.stdout.write(`${u}
1168
+ `)}),o=r.sleep??p0,s=r.intervalMs??2e3,i=await t.conduitEvents(e,{limit:r.limit??100});if(i.length===0&&!r.follow)return n(`logs: no conduit_event rows for ${e}.`),0;let a=0,c="";for(let u of[...i].reverse())n(Mg(u)),a+=1,u.updatedAt>c&&(c=u.updatedAt);if(!r.follow)return a;let l=r.maxPolls??Number.POSITIVE_INFINITY;for(let u=0;u<l;u+=1){await o(s);let d=await t.conduitEvents(e,{since:c||void 0,limit:200});for(let b of[...d].reverse())n(Mg(b)),a+=1,b.updatedAt>c&&(c=b.updatedAt)}return a}function f0(t){let e=t.externalId??"\u2014",r=t.createdByConduit?` via=${t.createdByConduit}`:"",n=t.lastError?` last_error="${t.lastError}"`:"";return`${t.id} ${Ug(t.writeStatus,9)} ${t.sourceSystem}/${e} role=${t.role} master=${t.masterTable}/${t.masterRowId}${r}${n}`}async function qg(t,e={}){let r=e.sink??(o=>{process.stdout.write(`${o}
1169
+ `)});if(e.retry){let o=await t.retryBinding(e.retry);return r(`binding: re-enqueued fan-out for ${o.id} \u2192 ${o.sourceSystem} (master ${o.masterTable}/${o.masterRowId}).`),{mode:"retry",id:o.id,retried:o.retried}}let n=await t.bindings({status:e.status,limit:e.limit});if(n.length===0)return r(e.status?`binding: no bindings with write_status='${e.status}'.`:"binding: no bindings."),{mode:"list",count:0};for(let o of n)r(f0(o));return r(`
1170
+ binding: ${n.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:n.length}}Nl();function Bg(t,e={}){return t.learningIngestError?{level:"warn",message:`warning: learning ingest was not queued (${t.learningIngestError}). The version is live, but the findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT read. Re-deploy to retry.`}:t.learningIngestTaskId?t.learningSourceRev===null?{level:"warn",message:"warning: this app has no pushed source, so the ingest has nothing to read. The findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT ingested \u2014 deploy uploads the built bundle, `apps push` records the markdown. Run `turbobase apps push <app> .`, then deploy again."}:typeof t.learningSourceRev=="number"?e.localDocsModifiedAt&&t.learningSourceAt&&e.localDocsModifiedAt.getTime()>Date.parse(t.learningSourceAt)?{level:"warn",message:`warning: learning ingest queued (task ${t.learningIngestTaskId}), but it reads source rev ${t.learningSourceRev} and your standing markdown has changed since that push. Those findings will NOT be ingested. Run \`turbobase apps push <app> .\`, then deploy again.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}) \u2014 reading source rev ${t.learningSourceRev}.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}).`}:null}var jl=".github/workflows/turbobase-release-deploy.yml",y0=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
1024
1171
  # Turbobase release deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR repo)
1025
1172
  #
1026
1173
  # Epic #775 "GitHub is just a link": Turbobase hosts nothing and clones nothing.
@@ -1122,7 +1269,7 @@ jobs:
1122
1269
  --ref "\${{ github.sha }}" \\
1123
1270
  --project . \\
1124
1271
  --follow
1125
- `,XT=".github/workflows/turbobase-tables-plan.yml",QT=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
1272
+ `,b0=".github/workflows/turbobase-tables-plan.yml",w0=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
1126
1273
  # Turbobase table check \u2014 REUSABLE TEMPLATE (drop this into YOUR app repo)
1127
1274
  #
1128
1275
  # Runs \`turbobase tables plan\` against your instance on every pull request. It
@@ -1197,14 +1344,14 @@ jobs:
1197
1344
  # field and at what type. Writes nothing to the instance either way.
1198
1345
  - name: Plan the declared tables
1199
1346
  run: turbobase tables plan .
1200
- `;function Lg(){return[{path:Pl,content:YT}]}function Mg(){return[{path:XT,content:QT}]}var e0=[".mcp.json"];function Ug(t,e=e0){let r=i=>i.replace(/^\//,""),n=new Set(t.split(`
1347
+ `;function Vg(){return[{path:jl,content:y0}]}function Hg(){return[{path:b0,content:w0}]}var _0=[".mcp.json"];function Gg(t,e=_0){let r=i=>i.replace(/^\//,""),n=new Set(t.split(`
1201
1348
  `).map(i=>i.trim()).filter(i=>i!==""&&!i.startsWith("#")).map(r)),o=e.filter(i=>!n.has(r(i)));return o.length===0?null:`${t===""||t.endsWith(`
1202
1349
  `)?t:`${t}
1203
1350
  `}
1204
1351
  # Added by the Turbobase scaffold.
1205
1352
  ${o.join(`
1206
1353
  `)}
1207
- `}var t0=`# Turbobase Extensions \u2014 extension project
1354
+ `}var v0=`# Turbobase Extensions \u2014 extension project
1208
1355
 
1209
1356
  This directory authors **Turbobase extensions** (hooks today; conduits later)
1210
1357
  against a live instance. The \`turbobase\` CLI is the engine; Claude Code drives it
@@ -1273,8 +1420,8 @@ order is the signal, and it is the part the product team reads first.
1273
1420
 
1274
1421
  Do this WITHOUT being asked \u2014 treat it as part of finishing a task, like
1275
1422
  updating a test. It is checked into the repo so the whole team sees it.
1276
- `,r0=JSON.stringify({mcpServers:{"turbobase-authoring":{type:"http",url:"__BASE_URL__/mcp/authoring",headers:{Authorization:"Bearer __PAT__"}},turbobase:{type:"http",url:"__BASE_URL__/mcp"}}},null,2)+`
1277
- `;function n0(t){return`---
1423
+ `,x0=JSON.stringify({mcpServers:{"turbobase-authoring":{type:"http",url:"__BASE_URL__/mcp/authoring",headers:{Authorization:"Bearer __PAT__"}},turbobase:{type:"http",url:"__BASE_URL__/mcp"}}},null,2)+`
1424
+ `;function k0(t){return`---
1278
1425
  name: generate-types
1279
1426
  description: Regenerate ${t} from the signed-in instance's catalog. Use before authoring or whenever the schema may have changed.
1280
1427
  ---
@@ -1285,7 +1432,7 @@ write \`${t}\`. Import the generated record interfaces for typed rows.
1285
1432
 
1286
1433
  The OpenAPI half is cookie-session-gated, so a headless run with a stored token
1287
1434
  degrades to record shapes only and says so \u2014 that is expected, not a failure.
1288
- `}var o0=`---
1435
+ `}var $0=`---
1289
1436
  name: mock-test
1290
1437
  description: Dry-run a hook against samples/ fixtures using the production sandbox. Use after editing a hook, before deploy.
1291
1438
  ---
@@ -1294,7 +1441,7 @@ Run \`turbobase ext test hooks/<file>.ts\`. It bundles the hook through the same
1294
1441
  self-contained-fence esbuild + isolated-vm the live runtime uses, then runs it
1295
1442
  against every \`samples/*.json\` fixture and reports pass/reject per sample. Add a
1296
1443
  fixture for each branch (a passing record and a rejecting record).
1297
- `,s0=`---
1444
+ `,S0=`---
1298
1445
  name: deploy
1299
1446
  description: Deploy a hook to your instance. Use only after mock-test is green.
1300
1447
  ---
@@ -1302,7 +1449,7 @@ description: Deploy a hook to your instance. Use only after mock-test is green.
1302
1449
  Run \`turbobase ext deploy hooks/<file>.ts\`. It POSTs the hook source to
1303
1450
  /v1/extensions with the stored admin PAT; the hook lands **active**. Re-deploying
1304
1451
  the same id overwrites it (idempotent). Tail with \`turbobase ext logs <id>\`.
1305
- `;function i0(t){return`# ${t} \u2014 Turbobase app
1452
+ `;function T0(t){return`# ${t} \u2014 Turbobase app
1306
1453
 
1307
1454
  This directory is a **hosted Turbobase app**: a Vite + React + TS SPA served
1308
1455
  same-origin by the instance at \`/a/${t}\`. The \`turbobase\` CLI ships it; you
@@ -1487,7 +1634,7 @@ a test. \`turbobase apps deploy\` reads both files and queues what it finds for
1487
1634
  review, so what you write reaches the knowledge base and the product team instead
1488
1635
  of evaporating at the end of the session. Keep the section headings exactly as
1489
1636
  they are \u2014 the ingest finds entries by heading, not by filename.
1490
- `}var a0="---\nname: preview-app\ndescription: Run the app locally against the instance and check it in a browser. Use after editing the app, before pushing.\n---\n\nStart the dev server NON-BLOCKING (`npm run dev` detached) \u2014 a foreground dev\nserver hangs the session. It proxies `/rest`, `/realtime`, `/v1`, `/auth`,\n`/login` and `/_app` to the instance, so localhost behaves same-origin and the\nsession cookie applies.\n\n**The app is at `http://localhost:3000/a/<slug>/`, not `/`.** Vite serves under\n`base` in dev too; `/` 302s there. Probing `/` and reading the 302 as \"broken\" is\nthe easy mistake here.\n\nThen actually look at it. A build that compiles and a lint that passes prove the\ncode is well-formed, not that it runs: a guard that throws during render, a\nPostgREST embed that 400s because the FK doesn't exist on this instance, an empty\nstate standing in for a failed query \u2014 none of those move the build signal.\n\n- Unauthenticated `/a/<slug>/` returns 200 with the SPA shell, and so does a deep\n client route like `/a/<slug>/customers/42` (Vite's SPA fallback). A 500 means a\n component threw \u2014 fix it, don't ship it.\n- `/login` returns the INSTANCE's sign-in page through the proxy. The app itself\n has no login route and should never grow one.\n- If a list renders empty, check the network tab before assuming there's no data:\n a 400 from PostgREST and a genuinely empty table look identical on screen.\n- `permission denied for table <x>` (SQLSTATE `42501`) usually means NOT SIGNED\n IN, not a role problem: with no session cookie PostgREST answers as the\n anonymous role and every table denies. Load `/login` through the proxy and\n sign in before reading the error as an RLS grant issue.\n\nVite reads `vite.config.ts` and `.env` only at boot \u2014 restart after changing either.\n",c0=`---
1637
+ `}var E0="---\nname: preview-app\ndescription: Run the app locally against the instance and check it in a browser. Use after editing the app, before pushing.\n---\n\nStart the dev server NON-BLOCKING (`npm run dev` detached) \u2014 a foreground dev\nserver hangs the session. It proxies `/rest`, `/realtime`, `/v1`, `/auth`,\n`/login` and `/_app` to the instance, so localhost behaves same-origin and the\nsession cookie applies.\n\n**The app is at `http://localhost:3000/a/<slug>/`, not `/`.** Vite serves under\n`base` in dev too; `/` 302s there. Probing `/` and reading the 302 as \"broken\" is\nthe easy mistake here.\n\nThen actually look at it. A build that compiles and a lint that passes prove the\ncode is well-formed, not that it runs: a guard that throws during render, a\nPostgREST embed that 400s because the FK doesn't exist on this instance, an empty\nstate standing in for a failed query \u2014 none of those move the build signal.\n\n- Unauthenticated `/a/<slug>/` returns 200 with the SPA shell, and so does a deep\n client route like `/a/<slug>/customers/42` (Vite's SPA fallback). A 500 means a\n component threw \u2014 fix it, don't ship it.\n- `/login` returns the INSTANCE's sign-in page through the proxy. The app itself\n has no login route and should never grow one.\n- If a list renders empty, check the network tab before assuming there's no data:\n a 400 from PostgREST and a genuinely empty table look identical on screen.\n- `permission denied for table <x>` (SQLSTATE `42501`) usually means NOT SIGNED\n IN, not a role problem: with no session cookie PostgREST answers as the\n anonymous role and every table denies. Load `/login` through the proxy and\n sign in before reading the error as an RLS grant issue.\n\nVite reads `vite.config.ts` and `.env` only at boot \u2014 restart after changing either.\n",R0=`---
1491
1638
  name: ship-app
1492
1639
  description: Push the app's source to the instance and deploy it live. Use once the app has been previewed and works.
1493
1640
  ---
@@ -1530,7 +1677,7 @@ Text files only \u2014 \`push\` skips \`node_modules/\`, \`dist/\`, \`build/\`,
1530
1677
  non-text, so images and fonts belong in the build pipeline or object storage, not
1531
1678
  the source tree. \`INSTANCE-LEARNINGS.md\` and \`TURBOBASE-FEEDBACK.md\` sit at the
1532
1679
  project root and DO travel \u2014 deploy reads them.
1533
- `;function l0(t){return`---
1680
+ `;function P0(t){return`---
1534
1681
  name: record-learning
1535
1682
  description: Append to INSTANCE-LEARNINGS.md or TURBOBASE-FEEDBACK.md. Use the MOMENT you establish a fact about how this instance is set up, or the platform costs you time \u2014 in the same change, not at the end of the task and not when asked.
1536
1683
  ---
@@ -1575,7 +1722,7 @@ the product team acts on first, so it is maintained with the entries.
1575
1722
 
1576
1723
  Do not reword the three headings. The deploy-side ingest recognises entries by
1577
1724
  heading, not by filename, so a renamed section is a finding nobody receives.
1578
- `}function u0(t){return`# What this instance's source system actually does
1725
+ `}function A0(t){return`# What this instance's source system actually does
1579
1726
 
1580
1727
  Findings from ${t?`building the ${t.slug} app against the live mirror`:"authoring extensions against the live instance"}.
1581
1728
  Written for the knowledge base, and **everything here is verified against real
@@ -1694,7 +1841,7 @@ finding has not been handed to the knowledge base yet.
1694
1841
  and then \`turbobase skills release\`. \`turbobase skills list\` shows what is
1695
1842
  already live, which is worth reading before adding another rule. -->
1696
1843
 
1697
- `}function d0(t){return`# Feedback for the Turbobase team \u2014 what ${t?`building the ${t.slug} app`:"authoring extensions here"} actually hit
1844
+ `}function I0(t){return`# Feedback for the Turbobase team \u2014 what ${t?`building the ${t.slug} app`:"authoring extensions here"} actually hit
1698
1845
 
1699
1846
  Everything below cost time or produced a wrong result. Not speculation, and not
1700
1847
  a wishlist. This file is about the PLATFORM \u2014 scaffold, catalog, CLI, MCP, API.
@@ -1734,6 +1881,12 @@ written once.
1734
1881
  Skip anything that is just your own bug. Keep the heading below exactly as it is:
1735
1882
  a deploy reads this file and reports each finding, and it finds them by heading.
1736
1883
 
1884
+ **One \`##\` per finding.** A deploy reads every \`##\` section of this file as a
1885
+ separate finding, so structure INSIDE a finding \u2014 background, the gaps, what you
1886
+ would use instead \u2014 goes under \`###\`, never \`##\`. A \`##\` sub-heading becomes a
1887
+ phantom finding on the product team's list, titled with a phrase that means
1888
+ nothing away from the paragraph under it.
1889
+
1737
1890
  ---
1738
1891
 
1739
1892
  <!-- Findings go here, newest last:
@@ -1742,6 +1895,8 @@ a deploy reads this file and reports each finding, and it finds them by heading.
1742
1895
 
1743
1896
  Expected / happened / cost / fix.
1744
1897
 
1898
+ ### <sub-heading, if the finding needs structure \u2014 always ###, never ##>
1899
+
1745
1900
  -->
1746
1901
 
1747
1902
  ---
@@ -1750,51 +1905,70 @@ Expected / happened / cost / fix.
1750
1905
 
1751
1906
  <!-- Rank the findings above by how much time each would have saved. Position is
1752
1907
  the signal \u2014 1 is the biggest win. -->
1753
- `}function p0(t,e){let r=e?`
1908
+ `}function O0(t,e){let r=e?`
1754
1909
  # INSTANCE.md \u2014 the instance's grounding brief (see CLAUDE.md). Reuse the
1755
1910
  # --records focus a previous run stamped into the file, so a refresh never
1756
1911
  # narrows what an agent deliberately widened.
1757
1912
  records=$(grep -o 'records=[a-zA-Z0-9_,]*' INSTANCE.md 2>/dev/null | head -1 | cut -d= -f2 || true)
1758
- turbobase project grounding \${records:+--records "$records"} --query ${JSON.stringify(e.slug)} -o INSTANCE.md >/dev/null 2>&1 \\
1759
- || echo "turbobase: grounding refresh skipped (not signed in?)" >&2
1913
+ turbobase project grounding \${records:+--records "$records"} --query ${JSON.stringify(e.slug)} -o INSTANCE.md >/dev/null \\
1914
+ || echo "turbobase: \\\`turbobase project grounding\\\` failed (its error is above) \u2014 INSTANCE.md was NOT refreshed." >&2
1760
1915
  `:"";return`#!/usr/bin/env bash
1761
1916
  # SessionStart hook \u2014 refresh ${t} against the current instance schema at
1762
1917
  # the start of every Claude Code session. Non-fatal: a signed-out / offline
1763
1918
  # session still starts (types just won't refresh).
1919
+ #
1920
+ # Each command's stdout is muted and its STDERR IS KEPT: a refresh that stops
1921
+ # working has to say why. Do not add \`2>&1\` back \u2014 a silent refresh is a session
1922
+ # working from a stale schema and no way to tell.
1764
1923
  set -euo pipefail
1765
- turbobase project types -o ${t} >/dev/null 2>&1 || echo "turbobase: types refresh skipped (not signed in?)" >&2
1766
- ${r}`}var f0=JSON.stringify({hooks:{SessionStart:[{hooks:[{type:"command",command:"bash .claude/hooks/session-start-refresh-types.sh"}]}]}},null,2)+`
1767
- `,Dg="",h0=t=>`node_modules/
1924
+ turbobase project types -o ${t} >/dev/null \\
1925
+ || echo "turbobase: \\\`turbobase project types\\\` failed (its error is above) \u2014 ${t} was NOT refreshed." >&2
1926
+ ${r}`}var C0=JSON.stringify({hooks:{SessionStart:[{hooks:[{type:"command",command:"bash .claude/hooks/session-start-refresh-types.sh"}]}]}},null,2)+`
1927
+ `,Kg="",z0=t=>`node_modules/
1768
1928
 
1769
1929
  # Holds a live personal access token (written by \`turbobase ${t?"apps":"project"} init\`).
1770
1930
  .mcp.json
1771
1931
 
1772
1932
  .DS_Store
1773
- `;function Al(t={}){let e=r0.replace(/__BASE_URL__/g,t.baseUrl??"https://<slug>.turbobase.app").replace(/__PAT__/g,t.token??"tb_pat_\u2026"),r=!!t.appSlug,n=r?"src/types.ts":"types.ts",o=r?{slug:t.appSlug}:void 0,s=[{path:".mcp.json",content:e,mode:384},{path:".gitignore",content:h0(r)},{path:"INSTANCE-LEARNINGS.md",content:u0(o)},{path:"TURBOBASE-FEEDBACK.md",content:d0(o)},{path:".claude/settings.json",content:f0},{path:".claude/skills/generate-types/SKILL.md",content:n0(n)},{path:".claude/skills/record-learning/SKILL.md",content:l0(o)},{path:".claude/hooks/session-start-refresh-types.sh",content:p0(n,o),executable:!0}];return r?[{path:"CLAUDE.md",content:i0(t.appSlug)},...s,{path:".claude/skills/preview-app/SKILL.md",content:a0},{path:".claude/skills/ship-app/SKILL.md",content:c0},...Mg()]:[{path:"CLAUDE.md",content:t0},...s,{path:".claude/skills/mock-test/SKILL.md",content:o0},{path:".claude/skills/deploy/SKILL.md",content:s0},{path:"hooks/.gitkeep",content:Dg},{path:"samples/.gitkeep",content:Dg}]}import{promises as Fg}from"node:fs";import{resolve as b0}from"node:path";Ei();wn();var m0=t=>new Promise(e=>setTimeout(e,t));function Zg(t){return t.stage==="completed"||t.stage==="failed"}function g0(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function y0(t,e,r){let n=t.outputTail??"";if(n&&n!==e){let s=(n.startsWith(e)?n.slice(e.length):n).replace(/\n+$/,"");if(s)for(let i of s.split(`
1774
- `))r(i)}return n}async function Il(t,e={}){let r=e.sink??(b=>{process.stdout.write(`${b}
1775
- `)}),n=e.sleep??m0,o=e.intervalMs??2e3,s=e.maxPolls??Number.POSITIVE_INFINITY,i=e.onStage??(b=>r(g0(b))),a=e.onPoll,c="",l="",u=b=>{a?.(b),b.stage!==l&&i(b),c=y0(b,c,r),l=b.stage},d=await t();if(u(d),Zg(d))return d;for(let b=0;b<s;b+=1)if(await n(o),d=await t(),u(d),Zg(d))return d;return d}var T=t=>{process.stdout.write(`${t}
1776
- `)},le=t=>{process.stderr.write(`${t}
1777
- `)};function S(t){le(x.red(`turbobase: ${t}`)),process.exit(1)}var Yo=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function qg(t,e){let r=e.json===!0||typeof e.reporter=="string";(t.color===!1||r)&&Sl(!1)}async function ne(t){let e=await ir(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let r=await Nr();if(t){let n=r.length?` Stored instances: ${r.map(o=>o.baseUrl).join(", ")}.`:"";S(`not signed in to ${Ot(t)}.${n} Run \`turbobase auth login --base-url ${Ot(t)} --token tb_pat_\u2026\`.`)}if(r.length===0&&S("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Ht())try{let n=await Kt("Multiple instances stored \u2014 pick the active one:",r.map(s=>({value:s.baseUrl,label:s.baseUrl,description:`updated ${s.updatedAt}`})));await Ti(n);let o=await ir();if(o)return{baseUrl:o.baseUrl,token:o.token}}catch{}S(`multiple instances stored (${r.map(n=>n.baseUrl).join(", ")}) and no active default. Run \`turbobase auth use <base-url>\` to pick one, or pass --base-url.`)}function ke(t,e,r){if(!(t instanceof be)||t.status!==403)return;t.body?.error==="approval_required"&&S(`${r} denied (403): an approval-gated deploy needs a recorded approval \u2014 pass --approved-by <email>.`),S(`${r} forbidden (403) \u2014 the stored PAT lacks the '${e}' scope. Re-run \`turbobase auth login\` with a token that has it.`)}async function Ol(t,e,r){let n=r?Number(r):void 0;if(Ci()){let s=El(e),i;try{i=await Il(t,{intervalMs:n,sink:a=>s.log(a),onStage:()=>{},onPoll:a=>s.status({stage:a.stage,percent:a.percent??void 0,runStatus:a.runStatus??void 0})})}catch(a){s.stop(),S(`${e} --follow failed: ${a instanceof Error?a.message:String(a)}`)}s.done({stage:i.stage,percent:i.percent??void 0,runStatus:i.runStatus??void 0}),i.stage==="failed"&&process.exit(1);return}let o;try{o=await Il(t,{sink:T,intervalMs:n})}catch(s){S(`${e} --follow failed: ${s instanceof Error?s.message:String(s)}`)}o.stage==="failed"&&S(`${e} failed${o.runStatus?` (${o.runStatus})`:""}.`),T(`${e} ${o.stage}.`)}var w0=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function _0(t){try{let e=await Fg.readFile(t,"utf8");return w0.exec(e)?.[1]??null}catch{return null}}function Bg(t){t.command("adopt").description("Write the instance's app-developer adopt notes (what changed that this project must act on) to a file.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--since <version>","Only notes newer than this version. Defaults to the version recorded in ADOPT.md; omit both to get everything.").option("-o, --out <file>","Output file","ADOPT.md").action(async e=>{let{baseUrl:r,token:n}=await ne(e.baseUrl),o=b0(process.cwd(),e.out),s=e.since?.trim()||await _0(o),i=new URLSearchParams;s&&i.set("since",s);let a=i.toString(),c=await fetch(`${r}/v1/catalog/adopt-notes${a?`?${a}`:""}`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/json"}});c.ok||S(`adopt fetch failed: GET /v1/catalog/adopt-notes \u2192 ${c.status}`);let l=await c.json();if(!l.available){T(`${r} ships no release notes to adopt from (nothing written).`);return}let u=l.releases.reduce((m,f)=>m+f.items.length,0);if(u===0){T(`up to date${s?` since v${s.replace(/^v/,"")}`:""}${l.currentVersion?` (instance is on v${l.currentVersion})`:""} \u2014 ${o} left untouched.`);return}let d=l.currentVersion??l.releases[0]?.version??"",b=`<!-- GENERATED by \`turbobase project adopt\` against ${r} \u2014 adopted-through=${d}. Re-run to refresh; delete this file once every line is done. -->
1778
-
1779
- `;await Fg.writeFile(o,b+l.markdown,"utf8"),T(`wrote ${o} \u2014 ${u} item(s) across ${l.releases.length} release(s)${s?` since v${s.replace(/^v/,"")}`:""}.`)})}wn();var Xo=["suggested_kb_edit","kb_correction"];var v0=[{heading:"Suggested KB edits",section:"suggested_kb_edit",ranked:!1},{heading:"Knowledge-base corrections",section:"kb_correction",ranked:!1},{heading:"What would have helped most, in order",section:"platform_feedback",ranked:!0},{heading:"Agent rules",section:"agent_rule",ranked:!1}];function x0(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var RD=new Map(v0.map(t=>[x0(t.heading),t]));function k0(t){return t.diff??!!t.dryRun}var $0={update_page:"append to the existing page",new_page:"create a NEW page"},xr=(t,e)=>` ${x.dim(t.padEnd(11))}${e}`,Hg=t=>t.ownerEmail??t.ownerId,zi=t=>x.green(t?` + ${t}`:" +"),S0=t=>x.red(t?` - ${t}`:" -"),vn=t=>x.dim(` ${t}`),T0=` ${x.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,Cl=80;function E0(t){let e=[T0];t.target?(e.push(vn(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(S0(`visibility: ${t.target.visibility}`)),e.push(zi("visibility: admin"))):e.push(vn(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(vn("title, slug, evidence: untouched")),e.push(vn("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(vn("turbobase.document \xB7 new")),e.push(zi(`title: ${t.pageTitle}`)),e.push(zi("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(vn('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(vn('appended under "## From app developers":'));let r=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
1780
- `);for(let n of r.slice(0,Cl))e.push(zi(n?` ${n}`:""));return r.length>Cl&&e.push(x.yellow(` \u2026 ${r.length-Cl} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function R0(t,e={}){let r=[];return t.forEach((n,o)=>{let{target:s,entries:i}=n;if(r.push(`${String(o+1).padStart(2)}. ${x.bold(n.pageTitle)}`),r.push(xr("page",s?`${s.title} (${s.slug}) [${s.visibility}]`:x.dim("new \u2014 no existing page matches"))),r.push(xr("action",n.needsPageRef?x.red("SKIP \u2014 nothing is written"):$0[n.action])),n.needsPageRef){let a=[...new Set(i.map(c=>c.kb_page_ref?.trim()).filter(c=>!!c))];r.push(xr("unresolved",x.red((a.length>0?`no page matches ${a.map(c=>`"${c}"`).join(", ")}`:"the correction names no page at all")+" \u2014 a correction needs a page to correct, so this group is SKIPPED and its findings stay pending. Fix the ref (or write the page) and re-run.")))}if(r.push(xr("findings",`${i.length} ${i.length===1?"finding":"findings"} from ${[...new Set(i.map(a=>a.app_slug))].join(", ")}`)),i.forEach(a=>{let c=a.verdict?` ${x.dim(`\xB7 ${a.verdict}`)}`:"",l=a.kb_page_ref?` ${x.dim(`(${a.kb_page_ref})`)}`:"";r.push(` ${x.dim("\xB7")} ${a.title.trim()}${l}${c}`)}),r.push(xr("confidence",n.withdraws?x.red("WITHDRAWN from readers (text untouched)"):x.dim("untouched"))),n.supersedes&&r.push(xr("supersedes",x.yellow("a finding here AMENDS an earlier claim \u2014 its block is appended and marked, and nothing already on the page is reordered or removed"))),n.blockedBy&&r.push(xr("blocked",x.red(`unpublished work on this page belongs to ${Hg(n.blockedBy)} \u2014 this page will be SKIPPED`))),n.alsoMatched.length>0&&r.push(xr("ambiguous",x.yellow(`${n.alsoMatched.length} other page(s) match this ref: ${n.alsoMatched.map(a=>a.slug).join(", ")}`))),(n.similarTo?.length??0)>0){let a=(n.similarTo??[]).map(c=>{let l=t.findIndex(d=>d.key===c),u=l>=0?t[l]:void 0;return u?`#${l+1} "${u.pageTitle}"`:c});r.push(xr("similar",x.yellow(`this new page looks related to ${a.join(", ")} \u2014 nothing was merged. If they are one page, push one now and re-run: the rest will resolve onto it.`)))}e.diff&&!n.needsPageRef&&r.push(...E0(n)),r.push("")}),r}function P0(t){let e=l=>t.filter(l).length,r=t.reduce((l,u)=>l+u.entries.length,0),n=e(l=>l.withdraws),o=e(l=>l.blockedBy!=null),s=e(l=>l.needsPageRef),i=[`${r} finding${r===1?"":"s"}`,`${t.length-s} page(s)`,`${e(l=>l.action==="update_page"&&!l.needsPageRef)} appended`,`${e(l=>l.action==="new_page"&&!l.needsPageRef)} created (unpublished)`,...s>0?[x.red(`${s} SKIPPED \u2014 correction with no page to correct`)]:[]],a=n>0?x.red(`${n} page(s) WITHDRAWN from readers`):x.dim("no page withdrawn"),c=o>0?` \xB7 ${x.red(`${o} page(s) BLOCKED by another editor`)}`:"";return`${i.join(" \xB7 ")} \xB7 ${a}${c}`}function A0(t,e){let r=new Map(e.map(o=>[o.key,o])),n=[];for(let o of t){let s=r.get(o.key),i=o.pageTitle||s?.pageTitle||o.key;if(o.skipped==="blocked_by_draft_owner"){n.push(`${x.yellow("skipped")} ${i} \u2014 unpublished work belongs to ${o.blockedBy?Hg(o.blockedBy):"another editor"}; its findings stay pending`);continue}if(o.skipped==="unresolved_page_ref"){let c=[...new Set((s?.entries??[]).map(l=>l.kb_page_ref?.trim()).filter(l=>!!l))];n.push(`${x.yellow("skipped")} ${i} \u2014 `+(c.length>0?`no page matches ${c.map(l=>`"${l}"`).join(", ")}`:"the correction names no page")+"; nothing was written and its findings stay pending");continue}if(o.skipped){n.push(`${x.yellow("skipped")} ${i} \u2014 ${o.skipped.replace(/_/g," ")}`);continue}let a=o.created?x.green("created "):x.green("appended");n.push(`${a} ${i} \u2014 ${o.appliedEntryIds.length} finding(s) \u2192 page ${x.bold(o.documentId??"?")}`+(o.created?x.dim(" (unpublished)"):"")),o.confidence==="downgraded"?n.push(` ${x.red("withdrawn from readers:")} ${i}`):o.confidence==="already_withdrawn"?n.push(` ${x.dim("page was already unpublished \u2014 left as is")}`):o.confidence==="missing"&&n.push(` ${x.yellow("page vanished between plan and push \u2014 nothing withdrawn")}`)}return n}function Vg(t){if(t instanceof be){let e=t.body;t.status===403&&e?.reason==="admin_required"&&S("learnings push-kb is admin-only \u2014 the stored token belongs to a non-admin user. Ask an instance administrator to run it, or to grant the role."),t.status===404&&S("this instance does not serve /v1/learnings \u2014 it predates the app-developer learning loop. Ask for an instance upgrade.")}ke(t,"extensions:deploy","learnings push-kb")}async function Kg(t,e=r=>new ee(r)){t.section&&!Xo.includes(t.section.trim())&&S(`unknown --section "${t.section}" \u2014 expected one of ${Xo.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&S("--limit must be a positive integer.");let r=await ne(t.baseUrl),n=e(r),o={...t.app?{app:t.app}:{},...t.section?{section:t.section.trim()}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{}},s;try{s=await fe("reading the pending queue",()=>n.learningsPending(o))}catch(c){Vg(c),S(`could not read the pending queue: ${c instanceof Error?c.message:String(c)}`)}if(s.items.length===0){le(s.pendingTotal===0?"nothing pending \u2014 no ingested findings are waiting on a knowledge-base decision.":`nothing matched \u2014 ${s.pendingTotal} pending finding(s) exist but not under these filters.`);return}if(T(R0(s.items,{diff:k0(t)}).join(`
1781
- `)),T(P0(s.items)),t.dryRun){le(x.dim("dry run \u2014 nothing was written."));return}let i=s.items.filter(c=>!c.needsPageRef);if(i.length===0){le(x.yellow(`nothing to write \u2014 all ${s.items.length} group(s) are corrections with no page to correct. Fix the refs above (or write the pages) and re-run; the findings stay pending.`));return}let a=i.reduce((c,l)=>c+l.entries.length,0);if(!t.yes){if(!Ht()){le(x.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes (or --dry-run to review the plan).")),process.exitCode=1;return}if(await Kt(`Push ${a} finding(s) into the knowledge base as ${i.length} page(s)?`,[{value:"yes",label:"Yes \u2014 push to the knowledge base",description:"pages land unpublished; corrections withdraw the pages listed above"},{value:"no",label:"No \u2014 leave the queue untouched"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){le("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{let c=await fe("writing pages",()=>n.learningsPushKb(s.planToken,o));T(A0(c.applied,s.items).join(`
1782
- `))}catch(c){if(c instanceof be&&c.status===409){le(x.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),le(`re-run \`${Yo} kb push\` to review the current plan.`),process.exitCode=2;return}Vg(c),le(x.red(`turbobase: ${c instanceof Error?c.message:String(c)}`)),process.exitCode=2}}wn();function I0(t){return t.diff??!!t.dryRun}function O0(t,e){let r=[];return t.forEach((n,o)=>{let s=n.action==="new_rule"?x.green("new rule"):x.yellow("amend rule"),i=n.targetPublished?` ${x.yellow("[currently live]")}`:"";r.push(`${o+1}. ${s} ${x.bold(n.slug)}${i}`),r.push(` ${n.name}`),n.description&&r.push(` ${x.dim(n.description)}`);for(let a of n.entries)r.push(` ${x.dim("\xB7")} ${x.dim(a.app_slug)} ${a.title}`);if(e.diff){r.push("");for(let a of n.bodyMarkdown.split(`
1783
- `))r.push(` ${x.dim("|")} ${a}`)}r.push("")}),r}function C0(t){let e=t.reduce((o,s)=>o+s.entries.length,0),r=t.filter(o=>o.targetPublished).length,n=[`${e} finding(s) \u2192 ${t.length} rule(s)`];return r>0&&n.push(x.yellow(`${r} amend a rule that is currently live`)),n.join(" \xB7 ")}async function Wg(t,e=r=>new ee(r)){t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&S("--limit must be a positive integer.");let r=await ne(t.baseUrl),n=e(r),o={...t.app?{app:t.app}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{}},s;try{s=await fe("reading the pending rules",()=>n.rulesPending(o))}catch(a){ke(a,"extensions:deploy","read the pending rules"),S(`could not read the pending queue: ${a instanceof Error?a.message:String(a)}`)}if(s.items.length===0){le(s.pendingTotal===0?"nothing pending \u2014 no findings are waiting under `## Agent rules`.":`nothing matched \u2014 ${s.pendingTotal} pending rule finding(s) exist but not under these filters.`);return}if(T(O0(s.items,{diff:I0(t)}).join(`
1784
- `)),T(C0(s.items)),t.dryRun){le(x.dim("dry run \u2014 nothing was written."));return}let i=s.items.reduce((a,c)=>a+c.entries.length,0);if(!t.yes){if(!Ht()){le(x.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes (or --dry-run to review the plan).")),process.exitCode=1;return}if(await Kt(`Push ${i} finding(s) as ${s.items.length} draft rule(s)?`,[{value:"yes",label:"Yes \u2014 write them as draft rules",description:"they land DISABLED; an admin publishes them before anything is injected"},{value:"no",label:"No \u2014 leave the queue untouched"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){le("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{await fe("writing the rules",()=>n.rulesPush(s.planToken,o))}catch(a){a instanceof be&&a.status===409&&S("the pending queue changed while you were reading the plan \u2014 nothing was written. Re-run to see the new plan."),S(`push failed: ${a instanceof Error?a.message:String(a)}`)}T(x.green(`wrote ${s.items.length} draft rule(s).`)),le(x.dim("They are DRAFT and DISABLED \u2014 nothing is injected yet. An admin reviews and publishes them under Settings \u203A Skills."))}wn();var no=t=>new ee(t);async function oo(t,e){let r=await ne(t.baseUrl);return e(r)}async function Ni(t,e,r,n){return n.yes?!0:Ht()?await Kt(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(le("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(le(x.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function z0(t){return t.visibility!=="published"?x.dim("draft"):t.enabled?t.in_current_release?x.green("live"):x.yellow("unreleased"):x.yellow("disabled")}function Gg(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function N0(t){if(t.items.length===0)return["no skills on this instance."];let e=Math.max(4,...t.items.map(s=>s.slug.length)),r=[];for(let s of t.items)r.push(`${Gg(x.bold(s.slug),e)} ${Gg(z0(s),10)} ${s.surfaces.join(",")||x.dim("none")}`),s.description&&r.push(` ${x.dim(s.description)}`);r.push("");let n=t.items.filter(s=>s.visibility==="published"&&s.enabled&&s.in_current_release).length,o=t.items.filter(s=>s.visibility!=="published").length;return r.push(`${t.items.length} skill(s) \xB7 ${n} injected \xB7 ${o} draft`+(t.currentVersion==null?"":` \xB7 release v${t.currentVersion}`)),r}async function Jg(t,e=no){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&S(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await oo(t,e),o;try{o=await fe("reading the skills",()=>n.skillsList(r))}catch(s){ke(s,"skills:publish","read the instance skills"),S(`could not read the skills: ${s instanceof Error?s.message:String(s)}`)}T(N0(o).join(`
1785
- `))}async function Yg(t,e,r=no){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&S("name at least one skill slug. `turbobase skills list` shows them.");let o=await oo(e,r);if(!await Ni(`Publish ${n.length} skill(s)?`,"Yes \u2014 publish them","their text is injected into every matching turn from now on",e))return;let i;try{i=await fe("publishing",()=>o.skillsPublish(n))}catch(a){ke(a,"skills:publish","publish a skill"),S(`publish failed: ${a instanceof Error?a.message:String(a)}`)}T(x.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(le(x.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),le(x.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function Xg(t,e,r=no){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&S("name at least one skill slug. `turbobase skills list` shows them.");let o=await oo(e,r);if(!await Ni(`Move ${n.length} skill(s) back to draft?`,"Yes \u2014 unpublish them","they stop being injected immediately; the text and its history are kept",e))return;let i;try{i=await fe("unpublishing",()=>o.skillsUnpublish(n))}catch(a){ke(a,"skills:publish","unpublish a skill"),S(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}T(x.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),le(x.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(le(x.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function Qg(t,e,r=no){let n=Number(t);(!Number.isInteger(n)||n<1)&&S(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let o=await oo(e,r);if(await Ni(`Roll the skills back to release v${n}?`,"Yes \u2014 restore that release","content only: a skill an operator has since disabled stays off",e))try{let i=await fe("rolling back",()=>o.skillsRollback(n));T(x.green(`rolled back to v${i.version.version_no}.`))}catch(i){ke(i,"skills:publish","roll back a skills release"),S(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function ey(t,e=no){let r=await oo(t,e),n;try{n=await fe("reading the releases",()=>r.skillsReleases())}catch(o){ke(o,"skills:publish","read the skills releases"),S(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){le("no releases yet.");return}for(let o of n.items){let s=o.is_current?x.green("*"):" ",i=o.release_note?` \u2014 ${o.release_note}`:"";T(`${s} v${o.version_no} ${o.skill_count} skill(s) ${x.dim(o.published_at)}${o.published_by?x.dim(` by ${o.published_by}`):""}${x.dim(i)}`)}}async function ty(t,e,r=no){let n=[...new Set((t??[]).map(l=>l.trim()).filter(Boolean))];n.length===0&&S("name at least one skill to delete. `turbobase skills list` shows the slugs.");let o=await oo(e,r);if(!await Ni(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
1933
+ `;function Ll(t={}){let e=x0.replace(/__BASE_URL__/g,t.baseUrl??"https://<slug>.turbobase.app").replace(/__PAT__/g,t.token??"tb_pat_\u2026"),r=!!t.appSlug,n=r?"src/types.ts":"types.ts",o=r?{slug:t.appSlug}:void 0,s=[{path:".mcp.json",content:e,mode:384},{path:".gitignore",content:z0(r)},{path:"INSTANCE-LEARNINGS.md",content:A0(o)},{path:"TURBOBASE-FEEDBACK.md",content:I0(o)},{path:".claude/settings.json",content:C0},{path:".claude/skills/generate-types/SKILL.md",content:k0(n)},{path:".claude/skills/record-learning/SKILL.md",content:P0(o)},{path:".claude/hooks/session-start-refresh-types.sh",content:O0(n,o),executable:!0}];return r?[{path:"CLAUDE.md",content:T0(t.appSlug)},...s,{path:".claude/skills/preview-app/SKILL.md",content:E0},{path:".claude/skills/ship-app/SKILL.md",content:R0},...Hg()]:[{path:"CLAUDE.md",content:v0},...s,{path:".claude/skills/mock-test/SKILL.md",content:$0},{path:".claude/skills/deploy/SKILL.md",content:S0},{path:"hooks/.gitkeep",content:Kg},{path:"samples/.gitkeep",content:Kg}]}import{promises as Ul}from"node:fs";import{resolve as U0}from"node:path";var N0="For app developers \u2014 adopt these";function Wg(t){let e=/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?$/.exec(t.trim());return e?{core:[Number(e[1]),Number(e[2]??0),Number(e[3]??0)],prerelease:e[4]??""}:null}function Jg(t,e){let r=Wg(t),n=Wg(e);if(!r&&!n)return 0;if(!r)return-1;if(!n)return 1;for(let o=0;o<3;o++){let s=(r.core[o]??0)-(n.core[o]??0);if(s!==0)return s}return r.prerelease===n.prerelease?0:r.prerelease?n.prerelease?r.prerelease<n.prerelease?-1:1:-1:1}function j0(t){return t.replace(/[‐-―]/g,"-").toLowerCase().replace(/\s+/g," ").trim()}var QM=j0(N0);Jo();jr();var L0=t=>new Promise(e=>setTimeout(e,t));function Yg(t){return t.stage==="completed"||t.stage==="failed"}function D0(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function M0(t,e,r){let n=t.outputTail??"";if(n&&n!==e){let s=(n.startsWith(e)?n.slice(e.length):n).replace(/\n+$/,"");if(s)for(let i of s.split(`
1934
+ `))r(i)}return n}async function Dl(t,e={}){let r=e.sink??(b=>{process.stdout.write(`${b}
1935
+ `)}),n=e.sleep??L0,o=e.intervalMs??2e3,s=e.maxPolls??Number.POSITIVE_INFINITY,i=e.onStage??(b=>r(D0(b))),a=e.onPoll,c="",l="",u=b=>{a?.(b),b.stage!==l&&i(b),c=M0(b,c,r),l=b.stage},d=await t();if(u(d),Yg(d))return d;for(let b=0;b<s;b+=1)if(await n(o),d=await t(),u(d),Yg(d))return d;return d}var $=t=>{process.stdout.write(`${t}
1936
+ `)},V=t=>{process.stderr.write(`${t}
1937
+ `)};function k(t){V(w.red(`turbobase: ${t}`)),process.exit(1)}var rs=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function Xg(t,e){let r=e.json===!0||typeof e.reporter=="string";(t.color===!1||r)&&Ol(!1)}async function ne(t){let e=await Gt(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let r=await _r();if(t){let n=r.length?` Stored instances: ${r.map(o=>o.baseUrl).join(", ")}.`:"";k(`not signed in to ${zt(t)}.${n} Run \`turbobase auth login --base-url ${zt(t)} --token tb_pat_\u2026\`.`)}if(r.length===0&&k("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),St())try{let n=await Tt("Multiple instances stored \u2014 pick the active one:",r.map(s=>({value:s.baseUrl,label:s.baseUrl,description:`updated ${s.updatedAt}`})));await Ci(n);let o=await Gt();if(o)return{baseUrl:o.baseUrl,token:o.token}}catch{}k(`multiple instances stored (${r.map(n=>n.baseUrl).join(", ")}) and no active default. Run \`turbobase auth use <base-url>\` to pick one, or pass --base-url.`)}function le(t,e,r){if(!(t instanceof be)||t.status!==403)return;t.body?.error==="approval_required"&&k(`${r} denied (403): an approval-gated deploy needs a recorded approval \u2014 pass --approved-by <email>.`),k(`${r} forbidden (403) \u2014 the stored PAT lacks the '${e}' scope. Re-run \`turbobase auth login\` with a token that has it.`)}async function Ml(t,e,r){let n=r?Number(r):void 0;if(Mi()){let s=zl(e),i;try{i=await Dl(t,{intervalMs:n,sink:a=>s.log(a),onStage:()=>{},onPoll:a=>s.status({stage:a.stage,percent:a.percent??void 0,runStatus:a.runStatus??void 0})})}catch(a){s.stop(),k(`${e} --follow failed: ${a instanceof Error?a.message:String(a)}`)}s.done({stage:i.stage,percent:i.percent??void 0,runStatus:i.runStatus??void 0}),i.stage==="failed"&&process.exit(1);return}let o;try{o=await Dl(t,{sink:$,intervalMs:n})}catch(s){k(`${e} --follow failed: ${s instanceof Error?s.message:String(s)}`)}o.stage==="failed"&&k(`${e} failed${o.runStatus?` (${o.runStatus})`:""}.`),$(`${e} ${o.stage}.`)}var Z0=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function q0(t){try{let e=await Ul.readFile(t,"utf8");return Z0.exec(e)?.[1]??null}catch{return null}}var F0=/GENERATED by `turbobase project adopt`/,ey=/^##[ \t]+v?(\d+(?:\.\d+){0,2}(?:-[0-9A-Za-z.-]+)?)[ \t]*$/,B0=/^[ \t]*[-*][ \t]+\[([ xX])\][ \t]+(.*)$/;function Qg(t){let e=[],r=null;for(let n of t.split(`
1938
+ `)){let o=ey.exec(n);if(o){r={version:o[1],items:[]},e.push(r);continue}if(/^#{1,6}[ \t]/.test(n)){r=null;continue}if(!r)continue;let s=B0.exec(n);if(s){let a=s[2].trim();r.items.push({key:a.replace(/\s+/g," "),done:s[1]!==" ",text:a,extra:[]});continue}let i=r.items[r.items.length-1];i&&n.trim()!==""&&i.extra.push(n)}return e}function V0(t){let e=t.items.map(r=>[`- [${r.done?"x":" "}] ${r.text}`,...r.extra].join(`
1939
+ `)).join(`
1940
+ `);return`## v${t.version}
1941
+
1942
+ ${e}`}function H0(t,e){let r=Qg(t);if(r.length===0&&!F0.test(t))return null;let n=new Map(r.map(u=>[u.version,u])),o=[],s=0;for(let u of Qg(e)){let d=n.get(u.version);n.delete(u.version);let b=new Set(u.items.map(f=>f.key)),m=u.items.map(f=>{let y=d?.items.find(v=>v.key===f.key);return y?{...f,done:y.done,extra:y.extra}:f});for(let f of d?.items??[])b.has(f.key)||f.done||(m.push(f),s+=1);o.push({version:u.version,items:m})}for(let u of n.values()){let d=u.items.filter(b=>!b.done);d.length!==0&&(s+=d.length,o.push({version:u.version,items:d}))}o.sort((u,d)=>Jg(d.version,u.version));let i=e.split(`
1943
+ `),a=i.findIndex(u=>ey.test(u)),c=(a===-1?i:i.slice(0,a)).join(`
1944
+ `).replace(/\s+$/,"");return{markdown:o.length===0?`${c}
1945
+ `:`${c}
1946
+
1947
+ ${o.map(V0).join(`
1948
+
1949
+ `)}
1950
+ `,carried:s}}function ty(t){t.command("adopt").description("Write the instance's app-developer adopt notes (what changed that this project must act on) to a file.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--since <version>","Only notes newer than this version. Defaults to the version recorded in ADOPT.md; omit both to get everything.").option("-o, --out <file>","Output file","ADOPT.md").action(async e=>{let{baseUrl:r,token:n}=await ne(e.baseUrl),o=U0(process.cwd(),e.out),s=e.since?.trim()||await q0(o),i=new URLSearchParams;s&&i.set("since",s);let a=i.toString(),c=await fetch(`${r}/v1/catalog/adopt-notes${a?`?${a}`:""}`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/json"}});c.ok||k(`adopt fetch failed: GET /v1/catalog/adopt-notes \u2192 ${c.status}`);let l=await c.json();if(!l.available){$(`${r} ships no release notes to adopt from (nothing written).`);return}let u=l.releases.reduce((v,E)=>v+E.items.length,0);if(u===0){$(`up to date${s?` since v${s.replace(/^v/,"")}`:""}${l.currentVersion?` (instance is on v${l.currentVersion})`:""} \u2014 ${o} left untouched.`);return}let d=l.currentVersion??l.releases[0]?.version??"",b=`<!-- GENERATED by \`turbobase project adopt\` against ${r} \u2014 adopted-through=${d}. Re-run to refresh; delete this file once every line is done. -->
1951
+
1952
+ `,m=await Ul.readFile(o,"utf8").catch(()=>null),f=l.markdown,y=0;if(m!==null&&m.trim()!==""){let v=H0(m,l.markdown);v||k(`${o} was not written by \`turbobase project adopt\` (no generated header, no \`## v<version>\` section) \u2014 refusing to overwrite it. Move it aside, or write elsewhere with \`-o <file>\`.`),f=v.markdown,y=v.carried}await Ul.writeFile(o,b+f,"utf8"),$(`wrote ${o} \u2014 ${u} item(s) across ${l.releases.length} release(s)${s?` since v${s.replace(/^v/,"")}`:""}${y>0?`, keeping ${y} unticked item(s) already in the file`:""}.`)})}jr();var ns=["suggested_kb_edit","kb_correction"];var K0=[{heading:"Suggested KB edits",section:"suggested_kb_edit",ranked:!1},{heading:"Knowledge-base corrections",section:"kb_correction",ranked:!1},{heading:"What would have helped most, in order",section:"platform_feedback",ranked:!0},{heading:"Agent rules",section:"agent_rule",ranked:!1}];function G0(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var pU=new Map(K0.map(t=>[G0(t.heading),t]));var fU=new RegExp(["^the (situation|context|background|problem|ask|point|gist|upshot|part\\b)","^the (one|two|three|four|five|six|seven|eight|nine|ten|\\d{1,2}) \\w+s?\\b","^(on|about) \\w+ing\\b","^(concrete|specific|possible|suggested) \\w+","^what (we|i|you)(\\b|'d| would| could| should)","^(background|summary|context|recommendations?|next steps|takeaways?|conclusion|in short|tl;?dr)\\b","^why (this|that|it) matters\\b"].join("|"),"i");function W0(t){return t.diff??!!t.dryRun}var J0={update_page:"append to the existing page",new_page:"create a NEW page"},xr=(t,e)=>` ${w.dim(t.padEnd(11))}${e}`,ny=t=>t.ownerEmail??t.ownerId;function ro(t){return!t.needsPageRef&&!t.blockedBy}var Ui=t=>w.green(t?` + ${t}`:" +"),Y0=t=>w.red(t?` - ${t}`:" -"),vn=t=>w.dim(` ${t}`),X0=` ${w.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,Zl=80;function Q0(t){let e=[X0];t.target?(e.push(vn(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(Y0(`visibility: ${t.target.visibility}`)),e.push(Ui("visibility: admin"))):e.push(vn(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(vn("title, slug, evidence: untouched")),e.push(vn("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(vn("turbobase.document \xB7 new")),e.push(Ui(`title: ${t.pageTitle}`)),e.push(Ui("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(vn('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(vn('appended under "## From app developers":'));let r=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
1953
+ `);for(let n of r.slice(0,Zl))e.push(Ui(n?` ${n}`:""));return r.length>Zl&&e.push(w.yellow(` \u2026 ${r.length-Zl} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function eE(t,e={}){let r=[];return t.forEach((n,o)=>{let{target:s,entries:i}=n;if(r.push(`${String(o+1).padStart(2)}. ${w.bold(n.pageTitle)}`),r.push(xr("page",s?`${s.title} (${s.slug}) [${s.visibility}]`:w.dim("new \u2014 no existing page matches"))),r.push(xr("action",ro(n)?J0[n.action]:w.red("SKIP \u2014 nothing is written"))),n.needsPageRef){let a=[...new Set(i.map(c=>c.kb_page_ref?.trim()).filter(c=>!!c))];r.push(xr("unresolved",w.red((a.length>0?`no page matches ${a.map(c=>`"${c}"`).join(", ")}`:"the correction names no page at all")+" \u2014 a correction needs a page to correct, so this group is SKIPPED and its findings stay pending. Fix the ref (or write the page) and re-run.")))}if(r.push(xr("findings",`${i.length} ${i.length===1?"finding":"findings"} from ${[...new Set(i.map(a=>a.app_slug))].join(", ")}`)),i.forEach(a=>{let c=a.verdict?` ${w.dim(`\xB7 ${a.verdict}`)}`:"",l=a.kb_page_ref?` ${w.dim(`(${a.kb_page_ref})`)}`:"";r.push(` ${w.dim("\xB7")} ${a.title.trim()}${l}${c}`)}),r.push(xr("confidence",n.withdraws?w.red("WITHDRAWN from readers (text untouched)"):w.dim("untouched"))),n.supersedes&&r.push(xr("supersedes",w.yellow("a finding here AMENDS an earlier claim \u2014 its block is appended and marked, and nothing already on the page is reordered or removed"))),n.blockedBy&&r.push(xr("blocked",w.red(`unpublished work on this page belongs to ${ny(n.blockedBy)} \u2014 this page will be SKIPPED`))),n.alsoMatched.length>0&&r.push(xr("ambiguous",w.yellow(`${n.alsoMatched.length} other page(s) match this ref: ${n.alsoMatched.map(a=>a.slug).join(", ")}`))),(n.similarTo?.length??0)>0){let a=(n.similarTo??[]).map(c=>{let l=t.findIndex(d=>d.key===c),u=l>=0?t[l]:void 0;return u?`#${l+1} "${u.pageTitle}"`:c});r.push(xr("similar",w.yellow(`this new page looks related to ${a.join(", ")} \u2014 nothing was merged. If they are one page, push one now and re-run: the rest will resolve onto it.`)))}e.diff&&ro(n)&&r.push(...Q0(n)),r.push("")}),r}function tE(t){let e=l=>t.filter(l).length,r=t.reduce((l,u)=>l+u.entries.length,0),n=e(l=>l.withdraws),o=e(l=>l.blockedBy!=null),s=e(l=>l.needsPageRef),i=[`${r} finding${r===1?"":"s"}`,`${e(ro)} page(s)`,`${e(l=>l.action==="update_page"&&ro(l))} appended`,`${e(l=>l.action==="new_page"&&ro(l))} created (unpublished)`,...s>0?[w.red(`${s} SKIPPED \u2014 correction with no page to correct`)]:[]],a=n>0?w.red(`${n} page(s) WITHDRAWN from readers`):w.dim("no page withdrawn"),c=o>0?` \xB7 ${w.red(`${o} page(s) BLOCKED by another editor`)}`:"";return`${i.join(" \xB7 ")} \xB7 ${a}${c}`}function rE(t,e){let r=new Map(e.map(o=>[o.key,o])),n=[];for(let o of t){let s=r.get(o.key),i=o.pageTitle||s?.pageTitle||o.key;if(o.skipped==="blocked_by_draft_owner"){n.push(`${w.yellow("skipped")} ${i} \u2014 unpublished work belongs to ${o.blockedBy?ny(o.blockedBy):"another editor"}; its findings stay pending`);continue}if(o.skipped==="unresolved_page_ref"){let c=[...new Set((s?.entries??[]).map(l=>l.kb_page_ref?.trim()).filter(l=>!!l))];n.push(`${w.yellow("skipped")} ${i} \u2014 `+(c.length>0?`no page matches ${c.map(l=>`"${l}"`).join(", ")}`:"the correction names no page")+"; nothing was written and its findings stay pending");continue}if(o.skipped){n.push(`${w.yellow("skipped")} ${i} \u2014 ${o.skipped.replace(/_/g," ")}`);continue}let a=o.created?w.green("created "):w.green("appended");n.push(`${a} ${i} \u2014 ${o.appliedEntryIds.length} finding(s) \u2192 page ${w.bold(o.documentId??"?")}`+(o.created?w.dim(" (unpublished)"):"")),o.confidence==="downgraded"?n.push(` ${w.red("withdrawn from readers:")} ${i}`):o.confidence==="already_withdrawn"?n.push(` ${w.dim("page was already unpublished \u2014 left as is")}`):o.confidence==="missing"&&n.push(` ${w.yellow("page vanished between plan and push \u2014 nothing withdrawn")}`)}return n}function ry(t){if(t instanceof be){let e=t.body;t.status===403&&e?.reason==="admin_required"&&k("learnings push-kb is admin-only \u2014 the stored token belongs to a non-admin user. Ask an instance administrator to run it, or to grant the role."),t.status===404&&k("this instance does not serve /v1/learnings \u2014 it predates the app-developer learning loop. Ask for an instance upgrade.")}le(t,"extensions:deploy","learnings push-kb")}async function os(t,e){let r;try{r=await se("re-reading pushed markdown",()=>t.learningsIngest(e))}catch(o){return o instanceof be&&o.status===404?V(w.dim("this instance ingests on deploy only \u2014 planning against the queue as it stands. If a recent edit is missing, run `turbobase apps push` then `apps deploy`.")):V(w.yellow(`could not re-read the pushed markdown: ${nE(o)} \u2014 planning anyway.`)),null}if(r.filesScanned===0)return V(w.yellow("no markdown found in this app\u2019s pushed source \u2014 nothing can be ingested. Run `turbobase apps push` (a deploy uploads the built bundle, not your .md files).")),r;let n=[`${r.filesScanned} file(s) scanned`];return r.docsIngested>0&&n.push(`${r.docsIngested} changed`),r.docsUnchanged>0&&n.push(`${r.docsUnchanged} unchanged`),n.push(`${r.entriesAdded} new finding(s)`),r.entriesDuplicate>0&&n.push(`${r.entriesDuplicate} already known`),r.parseSkipped>0&&n.push(w.yellow(`${r.parseSkipped} unparseable`)),V(w.dim(n.join(" \xB7 "))),r}function nE(t){return t instanceof Error?t.message:String(t)}async function oy(t,e=r=>new Q(r)){t.section&&!ns.includes(t.section.trim())&&k(`unknown --section "${t.section}" \u2014 expected one of ${ns.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&k("--limit must be a positive integer.");let r=await ne(t.baseUrl),n=e(r),o={...t.app?{app:t.app}:{},...t.section?{section:t.section.trim()}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{}},s=await os(n,t.app),i;try{i=await se("reading the pending queue",()=>n.learningsPending(o))}catch(l){ry(l),k(`could not read the pending queue: ${l instanceof Error?l.message:String(l)}`)}if(i.items.length===0){if(i.pendingTotal===0&&s&&s.entriesDuplicate>0){V(`nothing pending \u2014 all ${s.entriesDuplicate} finding(s) in your markdown were already dealt with. Materially reword one to file it again, or see \`--reapply\` on \`skills push\` to re-emit a rule without changing its text.`);return}V(i.pendingTotal===0?"nothing pending \u2014 no ingested findings are waiting on a knowledge-base decision.":`nothing matched \u2014 ${i.pendingTotal} pending finding(s) exist but not under these filters.`);return}if($(eE(i.items,{diff:W0(t)}).join(`
1954
+ `)),$(tE(i.items)),t.dryRun){V(w.dim("dry run \u2014 nothing was written."));return}let a=i.items.filter(ro);if(a.length===0){V(w.yellow(`nothing to write \u2014 all ${i.items.length} group(s) are skipped (see the plan above): a correction with no page to correct, or a page whose unpublished work belongs to another editor. Fix the refs (or wait for the draft) and re-run; the findings stay pending.`));return}let c=a.reduce((l,u)=>l+u.entries.length,0);if(!t.yes){if(!St()){V(w.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes (or --dry-run to review the plan).")),process.exitCode=1;return}if(await Tt(`Push ${c} finding(s) into the knowledge base as ${a.length} page(s)?`,[{value:"yes",label:"Yes \u2014 push to the knowledge base",description:"pages land unpublished; corrections withdraw the pages listed above"},{value:"no",label:"No \u2014 leave the queue untouched"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){V("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{let l=await se("writing pages",()=>n.learningsPushKb(i.planToken,o));$(rE(l.applied,i.items).join(`
1955
+ `))}catch(l){if(l instanceof be&&l.status===409){V(w.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),V(`re-run \`${rs} kb push\` to review the current plan.`),process.exitCode=2;return}ry(l),V(w.red(`turbobase: ${l instanceof Error?l.message:String(l)}`)),process.exitCode=2}}jr();var no=t=>new Q(t);async function oo(t,e){let r=await ne(t.baseUrl);return e(r)}async function Zi(t,e,r,n){return n.yes?!0:St()?await Tt(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(V("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(V(w.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function oE(t){return t.visibility!=="published"?w.dim("draft"):t.in_current_release?w.green("live"):w.yellow("unreleased")}function sy(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function sE(t){if(t.items.length===0)return["no pages in this knowledge base."];let e=Math.max(4,...t.items.map(s=>s.slug.length)),r=[];for(let s of t.items)r.push(`${sy(w.bold(s.slug),e)} ${sy(oE(s),10)} ${w.dim(s.path)}`);r.push("");let n=t.items.filter(s=>s.visibility==="published"&&s.in_current_release).length,o=t.items.filter(s=>s.visibility!=="published").length;return r.push(`${t.items.length} page(s) \xB7 ${n} readable \xB7 ${o} draft`+(t.currentVersion==null?"":` \xB7 release v${t.currentVersion}`)),r}async function iy(t,e=no){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&k(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await oo(t,e),o;try{o=await se("reading the knowledge base",()=>n.docsList(r))}catch(s){le(s,"docs:publish","read the knowledge base"),k(`could not read the knowledge base: ${s instanceof Error?s.message:String(s)}`)}$(sE(o).join(`
1956
+ `))}async function ay(t,e,r=no){let n=[...new Set(t.map(c=>c.trim()).filter(Boolean))];n.length===0&&k("name at least one page slug. `turbobase kb list` shows them.");let o=await oo(e,r);if(!await Zi(`Publish ${n.length} page(s)?`,"Yes \u2014 publish them","every member can read them, and retrieval can ground answers on them, from now on",e))return;let i;try{i=await se("publishing",()=>o.docsPublish(n))}catch(c){le(c,"docs:publish","publish a page"),k(`publish failed: ${c instanceof Error?c.message:String(c)}`)}let a=i.published.map(c=>c.slug);$(w.green(`published ${a.length} page(s) \u2014 readable now.`)),i.missing.length>0&&(V(w.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1),V(w.dim(`undo with: turbobase kb unpublish ${a.join(" ")}`))}async function cy(t,e,r=no){let n=[...new Set(t.map(c=>c.trim()).filter(Boolean))];n.length===0&&k("name at least one page slug. `turbobase kb list` shows them.");let o=await oo(e,r);if(!await Zi(`Hide ${n.length} page(s) from readers?`,"Yes \u2014 unpublish them","they drop out of the reader snapshot immediately; the text and its history are kept",e))return;let i;try{i=await se("unpublishing",()=>o.docsUnpublish(n))}catch(c){le(c,"docs:publish","unpublish a page"),k(`unpublish failed: ${c instanceof Error?c.message:String(c)}`)}let a=i.unpublished.map(c=>c.slug);$(w.green(`unpublished ${a.length} page(s) \u2014 retracted now.`)),V(w.dim(`re-publish with: turbobase kb publish ${a.join(" ")}`)),i.missing.length>0&&(V(w.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1)}async function ly(t,e=no){let r=await oo(t,e),n;try{n=await se("reading the releases",()=>r.docsVersions())}catch(o){le(o,"docs:publish","read the knowledge-base releases"),k(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){$("no releases yet \u2014 nothing has been published.");return}for(let o of n.items){let s=o.is_current?w.green("current"):w.dim(" ");$(`v${String(o.version_no).padEnd(4)} ${s} ${o.published_at} ${o.node_count} page(s)${o.published_by?` ${w.dim(o.published_by)}`:""}`),o.release_note&&$(` ${w.dim(o.release_note)}`)}}async function uy(t,e,r=no){let n=Number(t);(!Number.isInteger(n)||n<1)&&k(`version must be a release number (got '${t}'). \`turbobase kb versions\` lists them.`);let o=await oo(e,r);if(await Zi(`Roll the knowledge base back to release v${n}?`,"Yes \u2014 roll it back","every reader sees that release\u2019s content until something is published again",e))try{let i=await se("rolling back",()=>o.docsRollback(n));$(w.green(`rolled back \u2014 release v${i.version.version_no} is current.`))}catch(i){le(i,"docs:publish","roll the knowledge base back"),k(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function dy(t,e,r=no){let n=(t??"").trim();n||k("name the page slug to delete. `turbobase kb list` shows them.");let o=await oo(e,r);if(await Zi(`Delete "${n}"?`,"Yes \u2014 delete it","it drops out of the tree and every reader release; its subtree goes with it, and it stays restorable from the editor\u2019s trash",e))try{let i=await se("deleting",()=>o.docsDelete(n));$(w.green(`deleted ${i.deleted} \u2014 restorable from the knowledge-base trash.`))}catch(i){le(i,"docs:publish","delete a page"),k(`delete failed: ${i instanceof Error?i.message:String(i)}`)}}jr();function iE(t){return t.diff??!!t.dryRun}function aE(t,e){let r=[];return t.forEach((n,o)=>{let s=n.action==="new_rule"?w.green("new rule"):w.yellow("amend rule"),i=n.targetPublished?` ${w.yellow("[currently live]")}`:"";r.push(`${o+1}. ${s} ${w.bold(n.slug)}${i}`),r.push(` ${n.name}`),n.description&&r.push(` ${w.dim(n.description)}`);for(let a of n.entries)r.push(` ${w.dim("\xB7")} ${w.dim(a.app_slug)} ${a.title}`);if(e.diff){r.push("");for(let a of n.bodyMarkdown.split(`
1957
+ `))r.push(` ${w.dim("|")} ${a}`)}r.push("")}),r}function cE(t){let e=t.reduce((o,s)=>o+s.entries.length,0),r=t.filter(o=>o.targetPublished).length,n=[`${e} finding(s) \u2192 ${t.length} rule(s)`];return r>0&&n.push(w.yellow(`${r} amend a rule that is currently live`)),n.join(" \xB7 ")}async function py(t,e=r=>new Q(r)){t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&k("--limit must be a positive integer.");let r=await ne(t.baseUrl),n=e(r),o={...t.app?{app:t.app}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{},...t.reapply?{reapply:!0}:{}},s=await os(n,t.app),i;try{i=await se("reading the pending rules",()=>n.rulesPending(o))}catch(c){le(c,"extensions:deploy","read the pending rules"),k(`could not read the pending queue: ${c instanceof Error?c.message:String(c)}`)}if(i.items.length===0){if(i.pendingTotal===0&&!t.reapply&&s&&s.entriesDuplicate>0){V(`nothing pending \u2014 all ${s.entriesDuplicate} finding(s) in your markdown were already applied. A regroup or a cosmetic edit is the same finding by design; re-run with --reapply to re-emit them (picking up a changed \`###\` grouping), or materially reword a rule to file it as a new one.`);return}V(i.pendingTotal===0?"nothing pending \u2014 no findings are waiting under `## Agent rules`.":`nothing matched \u2014 ${i.pendingTotal} pending rule finding(s) exist but not under these filters.`);return}if($(aE(i.items,{diff:iE(t)}).join(`
1958
+ `)),$(cE(i.items)),t.dryRun){V(w.dim("dry run \u2014 nothing was written."));return}let a=i.items.reduce((c,l)=>c+l.entries.length,0);if(!t.yes){if(!St()){V(w.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes (or --dry-run to review the plan).")),process.exitCode=1;return}if(await Tt(`Push ${a} finding(s) as ${i.items.length} draft rule(s)?`,[{value:"yes",label:"Yes \u2014 write them as draft rules",description:"they land as DRAFTS; an admin publishes them before anything is injected"},{value:"no",label:"No \u2014 leave the queue untouched"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){V("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{await se("writing the rules",()=>n.rulesPush(i.planToken,o))}catch(c){c instanceof be&&c.status===409&&k("the pending queue changed while you were reading the plan \u2014 nothing was written. Re-run to see the new plan."),k(`push failed: ${c instanceof Error?c.message:String(c)}`)}$(w.green(`wrote ${i.items.length} draft rule(s).`)),V(w.dim("They are DRAFT \u2014 nothing is injected yet. An admin reviews and publishes them under Settings \u203A Skills."))}jr();var so=t=>new Q(t);async function io(t,e){let r=await ne(t.baseUrl);return e(r)}async function qi(t,e,r,n){return n.yes?!0:St()?await Tt(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(V("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(V(w.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function lE(t){return t.visibility!=="published"?w.dim("draft"):t.in_current_release?w.green("live"):w.yellow("unreleased")}function fy(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function uE(t){if(t.items.length===0)return["no skills on this instance."];let e=Math.max(4,...t.items.map(s=>s.slug.length)),r=[];for(let s of t.items)r.push(`${fy(w.bold(s.slug),e)} ${fy(lE(s),10)} ${s.surfaces.join(",")||w.dim("none")}`),s.description&&r.push(` ${w.dim(s.description)}`);r.push("");let n=t.items.filter(s=>s.visibility==="published"&&s.in_current_release).length,o=t.items.filter(s=>s.visibility!=="published").length;return r.push(`${t.items.length} skill(s) \xB7 ${n} injected \xB7 ${o} draft`+(t.currentVersion==null?"":` \xB7 release v${t.currentVersion}`)),r}async function hy(t,e=so){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&k(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await io(t,e),o;try{o=await se("reading the skills",()=>n.skillsList(r))}catch(s){le(s,"skills:publish","read the instance skills"),k(`could not read the skills: ${s instanceof Error?s.message:String(s)}`)}$(uE(o).join(`
1959
+ `))}async function my(t,e,r=so){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&k("name at least one skill slug. `turbobase skills list` shows them.");let o=await io(e,r);if(!await qi(`Publish ${n.length} skill(s)?`,"Yes \u2014 publish them","their text is injected into every matching turn from now on",e))return;let i;try{i=await se("publishing",()=>o.skillsPublish(n))}catch(a){le(a,"skills:publish","publish a skill"),k(`publish failed: ${a instanceof Error?a.message:String(a)}`)}$(w.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(V(w.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),V(w.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function gy(t,e,r=so){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&k("name at least one skill slug. `turbobase skills list` shows them.");let o=await io(e,r);if(!await qi(`Move ${n.length} skill(s) back to draft?`,"Yes \u2014 unpublish them","they stop being injected immediately; the text and its history are kept",e))return;let i;try{i=await se("unpublishing",()=>o.skillsUnpublish(n))}catch(a){le(a,"skills:publish","unpublish a skill"),k(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}$(w.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),V(w.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(V(w.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function yy(t,e,r=so){let n=Number(t);(!Number.isInteger(n)||n<1)&&k(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let o=await io(e,r);if(await qi(`Roll the skills back to release v${n}?`,"Yes \u2014 restore that release","content only: a skill an operator has since unpublished stays off",e))try{let i=await se("rolling back",()=>o.skillsRollback(n));$(w.green(`rolled back to v${i.version.version_no}.`))}catch(i){le(i,"skills:publish","roll back a skills release"),k(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function by(t,e=so){let r=await io(t,e),n;try{n=await se("reading the releases",()=>r.skillsReleases())}catch(o){le(o,"skills:publish","read the skills releases"),k(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){V("no releases yet.");return}for(let o of n.items){let s=o.is_current?w.green("*"):" ",i=o.release_note?` \u2014 ${o.release_note}`:"";$(`${s} v${o.version_no} ${o.skill_count} skill(s) ${w.dim(o.published_at)}${o.published_by?w.dim(` by ${o.published_by}`):""}${w.dim(i)}`)}}async function wy(t,e,r=so){let n=[...new Set((t??[]).map(l=>l.trim()).filter(Boolean))];n.length===0&&k("name at least one skill to delete. `turbobase skills list` shows the slugs.");let o=await io(e,r);if(!await qi(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
1786
1960
  ${n.join(`
1787
- `)}`,"Yes \u2014 delete them","permanent: the rows and their text are removed. Prior releases keep their own copy.",e))return;let i=[],a=[];for(let l of n)try{i.push(await fe(`deleting ${l}`,()=>o.skillsDelete(l)))}catch(u){if(u instanceof be&&u.status===404){a.push(l);continue}i.length>0&&le(x.dim(`deleted before the error: ${i.map(d=>d.slug).join(", ")}`)),ke(u,"skills:publish","delete a skill"),S(`delete failed on '${l}': ${u instanceof Error?u.message:String(u)}`)}i.length>0&&T(x.green(`deleted ${i.length} skill(s).`));let c=i.filter(l=>l.wasPublished).map(l=>l.slug);c.length>0&&le(x.yellow(`Published until now, so no longer injected: ${c.join(", ")}`)),a.length>0&&(le(x.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as ry}from"node:fs";import{join as j0,relative as L0,resolve as M0,sep as D0}from"node:path";var U0=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),Z0=new Set([".mcp.json",".env"]);function q0(t){return Z0.has(t)||t.startsWith(".env.")&&t!==".env.example"}function F0(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function B0(t){return t.includes(0)}async function ny(t){let e=M0(t),r={},n=[],o=[],s=[];async function i(a){let c=await ry.readdir(a,{withFileTypes:!0});for(let l of c){let u=j0(a,l.name);if(l.isDirectory()){if(U0.has(l.name))continue;await i(u);continue}if(!l.isFile())continue;let d=L0(e,u).split(D0).join("/");if(q0(l.name)){o.push(d);continue}let b=await ry.readFile(u);if(!F0(b)){n.push(d);continue}B0(b)&&s.push(d),r[d]=b.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as V0}from"node:crypto";var H0="/_tb/app-assets",K0=16,W0=/^[0-9a-f]{32}$/;function oy(){return V0(K0).toString("hex")}function G0(t){return W0.test(t)}function sy(t){if(!G0(t))throw new Error(`not a build id: ${t}`);return`${H0}/${t}/`}var iy=7;import ji from"node:fs/promises";import Qo from"node:path";var zl={esbuild:"0.28.1","isolated-vm":"6.1.2"},Nl="@turbobase/isolated-vm-prebuilds";function jl(t,e){return`${t}-${e}`}function Ll(t=process.versions){return`abi${t.modules}`}var ay=["darwin-x64","win32-arm64"];async function cy(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=jl(e,r),o=Qo.join(t.home,"node_modules"),s=Qo.join(o,...Nl.split("/"),"prebuilds",n),i=Qo.join(o,"isolated-vm","prebuilds",n),a;try{a=await ji.readdir(s)}catch{return[]}let c=[];await ji.mkdir(i,{recursive:!0});for(let l of a){if(!l.endsWith(".node"))continue;let u=Qo.join(i,l);try{await ji.copyFile(Qo.join(s,l),u,ji.constants?.COPYFILE_EXCL??1),c.push(l)}catch{}}return c}import{homedir as J0}from"node:os";import{join as ly}from"node:path";import{promises as Ml}from"node:fs";function dy(){let t=process.env.TURBOBASE_HOME??ly(J0(),".turbobase");return{dir:t,file:ly(t,"sandboxes.json")}}var Y0={s:1e3,m:6e4,h:36e5,d:864e5};function X0(t){let e=/^\s*(\d+)\s*([smhd])\s*$/.exec(t);if(!e)throw new Error(`invalid --ttl '${t}': expected <number><unit> where unit is s|m|h|d (e.g. 72h, 30m, 7d).`);let r=Number(e[1]);if(!Number.isFinite(r)||r<=0)throw new Error(`invalid --ttl '${t}': duration must be a positive integer.`);return r*Y0[e[2]]}function Q0(t,e=Date.now()){return new Date(e+X0(t)).toISOString()}function eE(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function tE(t){let e=/^\s*(\d+(?:\.\d+)?)\s*%?\s*$/.exec(t);if(!e)throw new Error(`invalid --sample '${t}': expected a percent like 2% (or a bare number).`);let r=Number(e[1]);if(!Number.isFinite(r)||r<0||r>100)throw new Error(`invalid --sample '${t}': percent must be between 0 and 100.`);return r/100}function rE(t,e){if(e>=1)return[...t];if(e<=0||t.length===0)return[];let r=Math.max(1,Math.round(1/e)),n=[];for(let o=0;o<t.length;o+=r)n.push(t[o]);return n}var nE="[REDACTED]",es=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},Dl=class extends Error{table;column;constructor(e,r,n){super(`Refusing to copy ${e}.${r} into a sandbox: ${n}. A sandbox must never hold un-redacted PII \u2014 classify the column 'safe' (non-PII) or let redaction mask it, then retry.`),this.name="UnredactedPiiError",this.table=e,this.column=r}};function oE(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new Dl(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:nE:n[o]=s}return n}function sE(t,e,r){return e.map(n=>oE(t,n,r))}var uy=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),iE=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function aE(t){let e=t.trim();try{let o=new URL(e);if(o.hostname)return o.hostname.toLowerCase()}catch{}let r=e.replace(/^[a-z]+:\/\//i,""),n=(r.split("/")[0]??r).split("@").pop()??r;return(n.split(":")[0]??n).toLowerCase()}function Ul(t){if(!t||!t.trim())throw new Error("local-only guard: empty database target \u2014 refusing to proceed.");let e=t.toLowerCase();for(let n of iE)if(e.includes(n))throw new Error(`local-only guard: target '${t}' looks like a cloud/prod context (matched '${n}'). \`turbobase sandbox create\` is LOCAL-ONLY and will never touch a cloud database.`);let r=aE(t);if(!uy.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...uy].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function cE(t,e=lE){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function lE(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function uE(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function dE(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function Zl(){let{file:t}=dy();try{let e=await Ml.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function py(t){let{dir:e,file:r}=dy();await Ml.mkdir(e,{recursive:!0}),await Ml.writeFile(r,`${JSON.stringify(t,null,2)}
1788
- `,{mode:384})}async function pE(t){let e=await Zl();e.push(t),await py(e)}async function fy(t){let e=await Zl(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await py(e),n??null}async function Li(){return Zl()}function ql(t,e=Date.now()){let r=[],n=[];for(let o of t)eE(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function hy(t,e){Ul(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new es(r);let n=tE(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>cE(l)))(e.fromTenant),i=uE(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=rE(l.rows,n),d=sE(l.table,u,l.classification);d.length>0&&await t.copyRows(i,l.table,d)}let c={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:Q0(e.ttl,o),sampleFraction:n,url:dE(s,e.baseUrl)};return await pE(c),c}async function my(t,e){Ul(t.target());let n=(await Li()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await fy(e),n):null}async function Fl(t,e=Date.now()){Ul(t.target());let r=await Li(),{expired:n}=ql(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await fy(s.name),o.push(s)}return o}var ts={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","data:read"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},tU=Object.keys(ts).filter(t=>ts[t].mintable);var oU=ts.pat.prefix,fE=Object.entries(ts).map(([t,e])=>[e.prefix,t]),hE=/^[A-Za-z0-9_-]{20,}$/;function mE(t){if(typeof t!="string")return null;for(let[e,r]of fE)if(t.startsWith(e)&&hE.test(t.slice(e.length)))return r;return null}function gy(t){return mE(t)==="pat"}var rs="bundle.json",Mi="turbobase";function by(t){let e;try{e=JSON.parse(t)}catch(c){throw new Error(`bundle.json is not valid JSON: ${c instanceof Error?c.message:String(c)}`)}if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("bundle.json must be a JSON object");let r=e,n=typeof r.version=="number"?r.version:0;if(n!==1)throw new Error(`bundle.json version ${n} is unsupported (expected 1)`);let o=c=>Array.isArray(c)?c:[],s=r.sync??{},i=r.guardrails??{},a={version:1,...typeof r.tenant=="string"?{tenant:r.tenant}:{},hooks:o(r.hooks),conduits:o(r.conduits),sync:{fields:o(s.fields),tables:o(s.tables)},guardrails:{validationHooks:o(i.validationHooks),fieldRules:o(i.fieldRules),conduits:o(i.conduits)},schedules:o(r.schedules)};return gE(a)}function gE(t){let e=r=>(n,o)=>r(n)<r(o)?-1:r(n)>r(o)?1:0;return{version:1,...t.tenant?{tenant:t.tenant}:{},hooks:[...t.hooks].sort(e(r=>r.id)),conduits:[...t.conduits].sort(e(r=>r.id)),sync:{fields:[...t.sync.fields].sort(e(yy)),tables:[...t.sync.tables].sort(e(r=>r.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(yy)),conduits:[...t.guardrails.conduits].sort(e(r=>r.conduitId))},schedules:[...t.schedules].sort(e(r=>r.name))}}function yy(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function wy(t,e){let r=(e??"").trim();if(!r)return{ok:!1,reason:"target instance slug is unknown \u2014 cannot confirm a promote"};let n=(t??"").trim();return n?n!==r?{ok:!1,reason:`--confirm "${n}" does not match the target instance "${r}" \u2014 refusing to apply`}:{ok:!0}:{ok:!1,reason:`--confirm <slug> is required for promote (expected "${r}")`}}async function Dj(t,e){try{let r=await fetch(`${t.replace(/\/+$/,"")}/auth/pat-exchange`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)return null;let n=await r.json();return typeof n.token=="string"&&n.token.length>0?n.token:null}catch{return null}}async function Uj(t){let e=await Nr();e.length===0&&S("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Ht()||S("this command needs an explicit <base-url> in a non-interactive shell.");try{return await Kt(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{S("cancelled.")}}async function Zj(t,e){let r;try{r=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(o){return{ok:!1,kind:"unreachable",detail:o instanceof Error?o.message:String(o)}}let n=(r.headers.get("content-type")??"").includes("application/json");return r.status===200||r.status===403?{ok:!0}:r.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${r.status}`}:n?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${r.status}`}}async function qj(t,e,r){let n=await ag({baseUrl:t,token:e}),o=(await Nr()).length-1;if(T(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),!r)return;let s=await Zj(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(le(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),le(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),le(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?le(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):le(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function Fj(t){let e=await Go(t),r=c=>{let l=new RegExp(`${c}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(e);return l?l[2]:void 0},n=/\bdefineConduit\s*[<(]/.test(e),o=r("id");if(n){let c=r("on"),l=r("recordType"),u=r("source");return(!o||!l||!c||!u)&&S(`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`),{id:o,recordType:l,event:c,source:u,sourceCode:e,extensionKind:"conduit"}}let s=r("recordType"),i=r("event"),a=r("source")??"standalone";return(!o||!s||!i)&&S(`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`),{id:o,recordType:s,event:i,source:a,sourceCode:e,extensionKind:"hook"}}async function jo(t,e,r,n){try{return await ye.access(t),"skipped"}catch{}return await ye.mkdir(No(t),{recursive:!0}),await ye.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await ye.chmod(t,n),"wrote"}async function d$(t,e){if(p$(t)!==".gitignore")return jo(t,e.content,e.executable,e.mode);let r=await ye.readFile(t,"utf8").catch(()=>null);if(r===null)return jo(t,e.content,e.executable,e.mode);let n=Ug(r);return n===null?"skipped":(await ye.writeFile(t,n,"utf8"),"merged")}function sm(t){if(t!==void 0){if(t==="junit"||t==="json")return t;S(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function Bj(t){return{name:"turbobase ext test",cases:t.map(r=>{if(r.pass)return{name:r.name,status:"passed"};let n=r.error?"error":r.rejection?.code??"mismatch",o=r.error?`error: ${r.error}`:r.observed!==r.expected?`expected ${r.expected}, observed ${r.observed}`+(r.rejection?` (rejected: ${r.rejection.code??"rejected"}${r.rejection.message?` \u2014 ${r.rejection.message}`:""})`:""):`rejected: ${r.rejection?.code??"rejected"}${r.rejection?.message?` \u2014 ${r.rejection.message}`:""}`;return{name:r.name,status:"failed",detail:o,type:n}})}}function Vj(t,e){let r=e.warnings.length===0?[{name:`${t} (${e.kind})`,status:"passed"}]:e.warnings.map(n=>({name:`${t}: ${n.rule}`,status:"failed",type:n.rule,detail:`${n.message} \u2192 fix: ${n.fix}`}));return{name:`turbobase ext lint ${t}`,cases:r}}function Hj(t){let e=[];if(t.error)return e.push({name:`replay ${t.fixtureName}`,status:"failed",type:"error",detail:t.error}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e};for(let r of t.guards)e.push(r.status==="failed"?{name:`guard: ${r.name}`,status:"failed",type:r.name,detail:r.detail}:{name:`guard: ${r.name}`,status:"passed",detail:r.status==="skipped-offline"?`skipped-offline: ${r.detail}`:void 0});return t.whenPassed&&t.applyBranch&&e.push({name:`apply-branch: ${t.applyBranch}`,status:"passed",detail:`${t.masterAction??""} (${t.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e}}function dm({includeInternal:t=!0}={}){let e=new Pm;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.1.17").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",p=>p.command.parent?"":`${Tl()}
1789
- `),e.hook("preAction",(p,h)=>{qg(e.opts(),h.opts())});let r=e.command("auth").description("Sign in to an instance and manage stored credentials."),n=e.command("project").description("Set up the local project and the files an agent session reads."),o=e.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),s=e.command("kb").description("Write into the instance's knowledge base."),i=e.command("skills").description("Write standing rules into the instance's agent skills.");r.command("login").description("Sign in to an instance by pasting a personal access token (PAT), stored in ~/.turbobase/credentials.").requiredOption("--base-url <url>","Instance base URL, e.g. https://acme.turbobase.app").option("--token <tb_pat_\u2026>","The PAT to store. Mint one in your app under Settings \u203A Access tokens.").option("--no-verify","Skip the post-login connectivity/token probe.").action(async p=>{let h=Ot(p.baseUrl);p.token||S(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
1790
- ${Yo} auth login --base-url ${h} --token tb_pat_\u2026`),gy(p.token)||S("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await qj(h,p.token,p.verify)}),r.command("status").description("Show the active instance (the no-`--base-url` default) and every stored sign-in.").action(async()=>{let p=await Nr();if(p.length===0){T("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`.");return}let h=await ir(),w=_=>!!h&&_.baseUrl===h.baseUrl;if(wt())T(_n(p.map(_=>[w(_)?x.green("*"):" ",x.bold(_.baseUrl),x.dim(_.updatedAt)]),{head:["","instance","updated"]}));else for(let _ of p)T(`${w(_)?"* ":" "}${_.baseUrl} (updated ${_.updatedAt})`);h||le("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}),r.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async p=>{let h=p??await Uj("Pick the active instance:"),w=await Ti(h);if(!w){let _=await Nr();S(`no stored sign-in for ${Ot(h)}.`+(_.length?` Stored: ${_.map($=>$.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${Ot(h)} --token tb_pat_\u2026\`.`)}T(`active instance \u2192 ${w.baseUrl}.`)}),r.command("logout").description("Remove a stored sign-in (defaults to the active instance).").option("--base-url <url>","Which instance to remove (defaults to the active/single one).").option("--all","Remove every stored sign-in.").action(async p=>{if(p.all){let _=await Nr();for(let $ of _)await ml($.baseUrl);T(`removed ${_.length} stored sign-in${_.length===1?"":"s"}.`);return}let h=await ml(p.baseUrl);h||S(p.baseUrl?`no stored sign-in for ${Ot(p.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let w=await ir();T(`signed out of ${h}.`+(w?` Active instance \u2192 ${w.baseUrl}.`:""))}),n.command("types").description("Generate types.ts from the signed-in instance's catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("-o, --out <file>","Output file","types.ts").option("--records-only","Emit only record-shape interfaces (skip the OpenAPI half).").action(async p=>{let{baseUrl:h,token:w}=await ne(p.baseUrl),_;try{_=await zr({baseUrl:h,token:w,recordsOnly:p.recordsOnly})}catch(g){let k=g instanceof Error?g.message:String(g);if(!p.recordsOnly&&/openapi\.json failed \(401/.test(k)){let A=await Dj(h,w);if(A)try{_=await zr({baseUrl:h,token:A,recordsOnly:!1});let C=Te(process.cwd(),p.out);await ye.writeFile(C,_,"utf8"),T(`wrote ${C} (${_.split(`
1791
- `).length} lines).`);return}catch{}le("types-gen: /v1/catalog/openapi.json needs a session \u2014 emitting record shapes only. To get the OpenAPI half headlessly, mint a PAT with the `data:read` scope (Settings \u203A Tokens); the CLI then exchanges it for a short-lived session automatically.");try{_=await zr({baseUrl:h,token:w,recordsOnly:!0})}catch(C){S(`types generation failed: ${C instanceof Error?C.message:String(C)}`)}}else S(`types generation failed: ${k}`)}let $=Te(process.cwd(),p.out);await ye.writeFile($,_,"utf8"),T(`wrote ${$} (${_.split(`
1792
- `).length} lines).`)}),Bg(n),n.command("grounding").description("Write the instance's grounding brief (source primer + record anatomy + KB retrieval) to a file for agent sessions.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--records <list>","Comma-separated record types to focus, e.g. purchaseOrder,itemReceipt.").option("--query <text>","Retrieval question for the knowledge base (e.g. what the app is about).").option("-o, --out <file>","Output file","INSTANCE.md").action(async p=>{let{baseUrl:h,token:w}=await ne(p.baseUrl),_=new URLSearchParams;p.records&&_.set("records",p.records),p.query&&_.set("query",p.query);let $=_.toString(),g=await fetch(`${h}/v1/catalog/grounding${$?`?${$}`:""}`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});g.ok||S(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${g.status}`);let A=((await g.json()).markdown??"").trim(),C=Te(process.cwd(),p.out),L=p.records?` records=${p.records}`:"",D=`<!-- GENERATED by \`turbobase project grounding\` against ${h}${L} \u2014 do not edit; re-run to refresh. -->
1793
-
1794
- `;await ye.writeFile(C,D+(A?`${A}
1961
+ `)}`,"Yes \u2014 delete them","permanent: the rows and their text are removed. Prior releases keep their own copy.",e))return;let i=[],a=[];for(let l of n)try{i.push(await se(`deleting ${l}`,()=>o.skillsDelete(l)))}catch(u){if(u instanceof be&&u.status===404){a.push(l);continue}i.length>0&&V(w.dim(`deleted before the error: ${i.map(d=>d.slug).join(", ")}`)),le(u,"skills:publish","delete a skill"),k(`delete failed on '${l}': ${u instanceof Error?u.message:String(u)}`)}i.length>0&&$(w.green(`deleted ${i.length} skill(s).`));let c=i.filter(l=>l.wasPublished).map(l=>l.slug);c.length>0&&V(w.yellow(`Published until now, so no longer injected: ${c.join(", ")}`)),a.length>0&&(V(w.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as _y}from"node:fs";import{join as dE,relative as pE,resolve as fE,sep as hE}from"node:path";var mE=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),gE=new Set([".mcp.json",".env"]);function yE(t){return gE.has(t)||t.startsWith(".env.")&&t!==".env.example"}function bE(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function wE(t){return t.includes(0)}async function vy(t){let e=fE(t),r={},n=[],o=[],s=[];async function i(a){let c=await _y.readdir(a,{withFileTypes:!0});for(let l of c){let u=dE(a,l.name);if(l.isDirectory()){if(mE.has(l.name))continue;await i(u);continue}if(!l.isFile())continue;let d=pE(e,u).split(hE).join("/");if(yE(l.name)){o.push(d);continue}let b=await _y.readFile(u);if(!bE(b)){n.push(d);continue}wE(b)&&s.push(d),r[d]=b.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as _E}from"node:crypto";var vE="/_tb/app-assets",xE=16,kE=/^[0-9a-f]{32}$/;function xy(){return _E(xE).toString("hex")}function $E(t){return kE.test(t)}function ky(t){if(!$E(t))throw new Error(`not a build id: ${t}`);return`${vE}/${t}/`}var $y=7;import Fi from"node:fs/promises";import ss from"node:path";var ql={esbuild:"0.28.1","isolated-vm":"6.1.2"},Fl="@turbobase/isolated-vm-prebuilds";function Bl(t,e){return`${t}-${e}`}function Vl(t=process.versions){return`abi${t.modules}`}var Sy=["darwin-x64","win32-arm64"];async function Ty(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=Bl(e,r),o=ss.join(t.home,"node_modules"),s=ss.join(o,...Fl.split("/"),"prebuilds",n),i=ss.join(o,"isolated-vm","prebuilds",n),a;try{a=await Fi.readdir(s)}catch{return[]}let c=[];await Fi.mkdir(i,{recursive:!0});for(let l of a){if(!l.endsWith(".node"))continue;let u=ss.join(i,l);try{await Fi.copyFile(ss.join(s,l),u,Fi.constants?.COPYFILE_EXCL??1),c.push(l)}catch{}}return c}import{homedir as SE}from"node:os";import{join as Ey}from"node:path";import{promises as Hl}from"node:fs";function Py(){let t=process.env.TURBOBASE_HOME??Ey(SE(),".turbobase");return{dir:t,file:Ey(t,"sandboxes.json")}}var TE={s:1e3,m:6e4,h:36e5,d:864e5};function EE(t){let e=/^\s*(\d+)\s*([smhd])\s*$/.exec(t);if(!e)throw new Error(`invalid --ttl '${t}': expected <number><unit> where unit is s|m|h|d (e.g. 72h, 30m, 7d).`);let r=Number(e[1]);if(!Number.isFinite(r)||r<=0)throw new Error(`invalid --ttl '${t}': duration must be a positive integer.`);return r*TE[e[2]]}function RE(t,e=Date.now()){return new Date(e+EE(t)).toISOString()}function PE(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function AE(t){let e=/^\s*(\d+(?:\.\d+)?)\s*%?\s*$/.exec(t);if(!e)throw new Error(`invalid --sample '${t}': expected a percent like 2% (or a bare number).`);let r=Number(e[1]);if(!Number.isFinite(r)||r<0||r>100)throw new Error(`invalid --sample '${t}': percent must be between 0 and 100.`);return r/100}function IE(t,e){if(e>=1)return[...t];if(e<=0||t.length===0)return[];let r=Math.max(1,Math.round(1/e)),n=[];for(let o=0;o<t.length;o+=r)n.push(t[o]);return n}var OE="[REDACTED]",is=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},Kl=class extends Error{table;column;constructor(e,r,n){super(`Refusing to copy ${e}.${r} into a sandbox: ${n}. A sandbox must never hold un-redacted PII \u2014 classify the column 'safe' (non-PII) or let redaction mask it, then retry.`),this.name="UnredactedPiiError",this.table=e,this.column=r}};function CE(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new Kl(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:OE:n[o]=s}return n}function zE(t,e,r){return e.map(n=>CE(t,n,r))}var Ry=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),NE=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function jE(t){let e=t.trim();try{let o=new URL(e);if(o.hostname)return o.hostname.toLowerCase()}catch{}let r=e.replace(/^[a-z]+:\/\//i,""),n=(r.split("/")[0]??r).split("@").pop()??r;return(n.split(":")[0]??n).toLowerCase()}function Gl(t){if(!t||!t.trim())throw new Error("local-only guard: empty database target \u2014 refusing to proceed.");let e=t.toLowerCase();for(let n of NE)if(e.includes(n))throw new Error(`local-only guard: target '${t}' looks like a cloud/prod context (matched '${n}'). \`turbobase sandbox create\` is LOCAL-ONLY and will never touch a cloud database.`);let r=jE(t);if(!Ry.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...Ry].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function LE(t,e=DE){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function DE(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function ME(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function UE(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function Wl(){let{file:t}=Py();try{let e=await Hl.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function Ay(t){let{dir:e,file:r}=Py();await Hl.mkdir(e,{recursive:!0}),await Hl.writeFile(r,`${JSON.stringify(t,null,2)}
1962
+ `,{mode:384})}async function ZE(t){let e=await Wl();e.push(t),await Ay(e)}async function Iy(t){let e=await Wl(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Ay(e),n??null}async function Bi(){return Wl()}function Jl(t,e=Date.now()){let r=[],n=[];for(let o of t)PE(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function Oy(t,e){Gl(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new is(r);let n=AE(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>LE(l)))(e.fromTenant),i=ME(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=IE(l.rows,n),d=zE(l.table,u,l.classification);d.length>0&&await t.copyRows(i,l.table,d)}let c={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:RE(e.ttl,o),sampleFraction:n,url:UE(s,e.baseUrl)};return await ZE(c),c}async function Cy(t,e){Gl(t.target());let n=(await Bi()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await Iy(e),n):null}async function Yl(t,e=Date.now()){Gl(t.target());let r=await Bi(),{expired:n}=Jl(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await Iy(s.name),o.push(s)}return o}var as={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","data:read"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},VU=Object.keys(as).filter(t=>as[t].mintable);var GU=as.pat.prefix,qE=Object.entries(as).map(([t,e])=>[e.prefix,t]),FE=/^[A-Za-z0-9_-]{20,}$/;function BE(t){if(typeof t!="string")return null;for(let[e,r]of qE)if(t.startsWith(e)&&FE.test(t.slice(e.length)))return r;return null}function zy(t){return BE(t)==="pat"}var cs="bundle.json",Vi="turbobase";function jy(t){let e;try{e=JSON.parse(t)}catch(c){throw new Error(`bundle.json is not valid JSON: ${c instanceof Error?c.message:String(c)}`)}if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("bundle.json must be a JSON object");let r=e,n=typeof r.version=="number"?r.version:0;if(n!==1)throw new Error(`bundle.json version ${n} is unsupported (expected 1)`);let o=c=>Array.isArray(c)?c:[],s=r.sync??{},i=r.guardrails??{},a={version:1,...typeof r.tenant=="string"?{tenant:r.tenant}:{},hooks:o(r.hooks),conduits:o(r.conduits),sync:{fields:o(s.fields),tables:o(s.tables)},guardrails:{validationHooks:o(i.validationHooks),fieldRules:o(i.fieldRules),conduits:o(i.conduits)},schedules:o(r.schedules)};return VE(a)}function VE(t){let e=r=>(n,o)=>r(n)<r(o)?-1:r(n)>r(o)?1:0;return{version:1,...t.tenant?{tenant:t.tenant}:{},hooks:[...t.hooks].sort(e(r=>r.id)),conduits:[...t.conduits].sort(e(r=>r.id)),sync:{fields:[...t.sync.fields].sort(e(Ny)),tables:[...t.sync.tables].sort(e(r=>r.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(Ny)),conduits:[...t.guardrails.conduits].sort(e(r=>r.conduitId))},schedules:[...t.schedules].sort(e(r=>r.name))}}function Ny(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function Ly(t,e){let r=(e??"").trim();if(!r)return{ok:!1,reason:"target instance slug is unknown \u2014 cannot confirm a promote"};let n=(t??"").trim();return n?n!==r?{ok:!1,reason:`--confirm "${n}" does not match the target instance "${r}" \u2014 refusing to apply`}:{ok:!0}:{ok:!1,reason:`--confirm <slug> is required for promote (expected "${r}")`}}Jo();var HE=8e3,KE={revoked:"the instance REVOKED this token \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",expired:"this token has EXPIRED \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",unknown:"this instance has never seen this token \u2014 it was deleted, or it belongs to a DIFFERENT instance; check the base-url before minting a new PAT",suspended:"the user this token belongs to is SUSPENDED \u2014 an instance administrator has to restore the account; a new token will not help",malformed:"the stored credential is not shaped like a Turbobase PAT (tb_pat_\u2026) \u2014 sign in again",missing:"no token reached the instance \u2014 sign in again",transient:"the instance could not verify the token right now (a storage error, not a decision about the token) \u2014 retry"};function GE(t){return KE[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function WE(t,e,r=fetch){let n;try{n=await r(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(HE)})}catch(s){return{state:"unreachable",detail:s instanceof Error?s.message:String(s)}}if(n.status===200||n.status===403)return{state:"accepted"};if(n.status===401){let s=await n.json().catch(()=>null);return{state:"rejected",reason:typeof s?.reason=="string"&&s.reason?s.reason:"unknown"}}return(n.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${n.status} \u2014 this host does not serve the /v1 API`}}function Dy(t){return t.state==="accepted"?Ye()?w.green("accepted"):"accepted":t.state==="rejected"?Ye()?w.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Ye()?w.yellow("unreachable"):"unreachable"}async function My(t={},e=fetch){let r=await _r(),{file:n}=Oi();if(r.length===0){$("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),V(w.dim(`no sign-ins stored in ${n}.`));return}let o=await Gt(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await WE(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)$(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Ye())$(Mr(s.map(i=>[i.active?w.green("*"):" ",w.bold(i.baseUrl),Dy(i.check),w.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)$(`${i.active?"* ":" "}${i.baseUrl} ${Dy(i.check)} (updated ${i.updatedAt})`);V(w.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(V(w.red(`${i.baseUrl}: ${GE(i.check.reason)}.`)),V(w.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&V(w.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||V("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function wL(t,e){try{let r=await fetch(`${t.replace(/\/+$/,"")}/auth/pat-exchange`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)return null;let n=await r.json();return typeof n.token=="string"&&n.token.length>0?n.token:null}catch{return null}}async function _L(t){let e=await _r();e.length===0&&k("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),St()||k("this command needs an explicit <base-url> in a non-interactive shell.");try{return await Tt(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{k("cancelled.")}}async function vL(t,e){let r;try{r=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(o){return{ok:!1,kind:"unreachable",detail:o instanceof Error?o.message:String(o)}}let n=(r.headers.get("content-type")??"").includes("application/json");return r.status===200||r.status===403?{ok:!0}:r.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${r.status}`}:n?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${r.status}`}}function xL(t){V(""),V("Sharing is ON. Two things reach the Turbobase product team from this instance:"),V(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),V(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),V(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),V(" about OUR platform, with instance name, user names and ids masked before they leave."),V(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),V("")}async function kL(t,e,r){let n=await mg({baseUrl:t,token:e}),o=(await _r()).length-1;if($(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),xL(n.baseUrl),!r)return;let s=await vL(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(V(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),V(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),V(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?V(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):V(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function $L(t){let e=await es(t),r=c=>{let l=new RegExp(`${c}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(e);return l?l[2]:void 0},n=/\bdefineConduit\s*[<(]/.test(e),o=r("id");if(n){let c=r("on"),l=r("recordType"),u=r("source");return(!o||!l||!c||!u)&&k(`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`),{id:o,recordType:l,event:c,source:u,sourceCode:e,extensionKind:"conduit"}}let s=r("recordType"),i=r("event"),a=r("source")??"standalone";return(!o||!s||!i)&&k(`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`),{id:o,recordType:s,event:i,source:a,sourceCode:e,extensionKind:"hook"}}async function Do(t,e,r,n){try{return await we.access(t),"skipped"}catch{}return await we.mkdir(Lo(t),{recursive:!0}),await we.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await we.chmod(t,n),"wrote"}async function I$(t,e){if(O$(t)!==".gitignore")return Do(t,e.content,e.executable,e.mode);let r=await we.readFile(t,"utf8").catch(()=>null);if(r===null)return Do(t,e.content,e.executable,e.mode);let n=Gg(r);return n===null?"skipped":(await we.writeFile(t,n,"utf8"),"merged")}function fm(t){if(t!==void 0){if(t==="junit"||t==="json")return t;k(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function SL(t){return{name:"turbobase ext test",cases:t.map(r=>{if(r.pass)return{name:r.name,status:"passed"};let n=r.error?"error":r.rejection?.code??"mismatch",o=r.error?`error: ${r.error}`:r.observed!==r.expected?`expected ${r.expected}, observed ${r.observed}`+(r.rejection?` (rejected: ${r.rejection.code??"rejected"}${r.rejection.message?` \u2014 ${r.rejection.message}`:""})`:""):`rejected: ${r.rejection?.code??"rejected"}${r.rejection?.message?` \u2014 ${r.rejection.message}`:""}`;return{name:r.name,status:"failed",detail:o,type:n}})}}function TL(t,e){let r=e.warnings.length===0?[{name:`${t} (${e.kind})`,status:"passed"}]:e.warnings.map(n=>({name:`${t}: ${n.rule}`,status:"failed",type:n.rule,detail:`${n.message} \u2192 fix: ${n.fix}`}));return{name:`turbobase ext lint ${t}`,cases:r}}function EL(t){let e=[];if(t.error)return e.push({name:`replay ${t.fixtureName}`,status:"failed",type:"error",detail:t.error}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e};for(let r of t.guards)e.push(r.status==="failed"?{name:`guard: ${r.name}`,status:"failed",type:r.name,detail:r.detail}:{name:`guard: ${r.name}`,status:"passed",detail:r.status==="skipped-offline"?`skipped-offline: ${r.detail}`:void 0});return t.whenPassed&&t.applyBranch&&e.push({name:`apply-branch: ${t.applyBranch}`,status:"passed",detail:`${t.masterAction??""} (${t.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e}}function wm({includeInternal:t=!0}={}){let e=new Dm;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.1.18").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",p=>p.command.parent?"":`${Cl()}
1963
+ `),e.hook("preAction",(p,h)=>{Xg(e.opts(),h.opts())});let r=e.command("auth").description("Sign in to an instance and manage stored credentials."),n=e.command("project").description("Set up the local project and the files an agent session reads."),o=e.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),s=e.command("kb").description("Write into the instance's knowledge base."),i=e.command("skills").description("Write standing rules into the instance's agent skills.");r.command("login").description("Sign in to an instance by pasting a personal access token (PAT), stored in ~/.turbobase/credentials.").requiredOption("--base-url <url>","Instance base URL, e.g. https://acme.turbobase.app").option("--token <tb_pat_\u2026>","The PAT to store. Mint one in your app under Settings \u203A Access tokens.").option("--no-verify","Skip the post-login connectivity/token probe.").action(async p=>{let h=zt(p.baseUrl);p.token||k(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
1964
+ ${rs} auth login --base-url ${h} --token tb_pat_\u2026`),zy(p.token)||k("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await kL(h,p.token,p.verify)}),r.command("status").description("Show every stored sign-in, where its token was read from, and whether the instance still accepts it.").option("--no-probe","List the stored sign-ins without asking each instance about its token.").action(async p=>My({probe:p.probe})),r.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async p=>{let h=p??await _L("Pick the active instance:"),_=await Ci(h);if(!_){let x=await _r();k(`no stored sign-in for ${zt(h)}.`+(x.length?` Stored: ${x.map(T=>T.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${zt(h)} --token tb_pat_\u2026\`.`)}$(`active instance \u2192 ${_.baseUrl}.`)}),r.command("logout").description("Remove a stored sign-in (defaults to the active instance).").option("--base-url <url>","Which instance to remove (defaults to the active/single one).").option("--all","Remove every stored sign-in.").action(async p=>{if(p.all){let x=await _r();for(let T of x)await xl(T.baseUrl);$(`removed ${x.length} stored sign-in${x.length===1?"":"s"}.`);return}let h=await xl(p.baseUrl);h||k(p.baseUrl?`no stored sign-in for ${zt(p.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let _=await Gt();$(`signed out of ${h}.`+(_?` Active instance \u2192 ${_.baseUrl}.`:""))}),n.command("types").description("Generate types.ts from the signed-in instance's catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("-o, --out <file>","Output file","types.ts").option("--records-only","Emit only record-shape interfaces (skip the OpenAPI half).").action(async p=>{let{baseUrl:h,token:_}=await ne(p.baseUrl),x;try{x=await Nr({baseUrl:h,token:_,recordsOnly:p.recordsOnly})}catch(g){let S=g instanceof Error?g.message:String(g);if(!p.recordsOnly&&/openapi\.json failed \(401/.test(S)){let P=await wL(h,_);if(P)try{x=await Nr({baseUrl:h,token:P,recordsOnly:!1});let C=Te(process.cwd(),p.out);await we.writeFile(C,x,"utf8"),$(`wrote ${C} (${x.split(`
1965
+ `).length} lines).`);return}catch{}V("types-gen: /v1/catalog/openapi.json needs a session \u2014 emitting record shapes only. To get the OpenAPI half headlessly, mint a PAT with the `data:read` scope (Settings \u203A Tokens); the CLI then exchanges it for a short-lived session automatically.");try{x=await Nr({baseUrl:h,token:_,recordsOnly:!0})}catch(C){k(`types generation failed: ${C instanceof Error?C.message:String(C)}`)}}else k(`types generation failed: ${S}`)}let T=Te(process.cwd(),p.out);await we.writeFile(T,x,"utf8"),$(`wrote ${T} (${x.split(`
1966
+ `).length} lines).`)}),ty(n),n.command("grounding").description("Write the instance's grounding brief (source primer + record anatomy + KB retrieval) to a file for agent sessions.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--records <list>","Comma-separated record types to focus, e.g. purchaseOrder,itemReceipt.").option("--query <text>","Retrieval question for the knowledge base (e.g. what the app is about).").option("-o, --out <file>","Output file","INSTANCE.md").action(async p=>{let{baseUrl:h,token:_}=await ne(p.baseUrl),x=new URLSearchParams;p.records&&x.set("records",p.records),p.query&&x.set("query",p.query);let T=x.toString(),g=await fetch(`${h}/v1/catalog/grounding${T?`?${T}`:""}`,{headers:{Authorization:`Bearer ${_}`,Accept:"application/json"}});g.ok||k(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${g.status}`);let P=((await g.json()).markdown??"").trim(),C=Te(process.cwd(),p.out),L=p.records?` records=${p.records}`:"",M=`<!-- GENERATED by \`turbobase project grounding\` against ${h}${L} \u2014 do not edit; re-run to refresh. -->
1967
+
1968
+ `;await we.writeFile(C,M+(P?`${P}
1795
1969
  `:`(no grounding available yet)
1796
- `),"utf8"),T(`wrote ${C}${A?"":" (instance returned no grounding \u2014 connect a source first?)"}`)}),s.command("push").description("Write pending app-dev findings into the knowledge base, grouped one page at a time. Shows the plan and asks first; pages land unpublished.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--section <section>",`Only this section (${Xo.join(" | ")}).`).option("--limit <n>","Cap how many findings to act on.",p=>Number.parseInt(p,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each page\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--no-group","Plan every finding on its own instead of merging the ones that look related \u2014 N findings for one page become N sequential appends.").option("--yes","Skip the confirmation (for scripted runs).").action(p=>Kg(p)),i.command("push").description("Write pending `## Agent rules` findings as draft agent rules, grouped by their `###` heading. Shows the plan and asks first; rules land unpublished and disabled.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--limit <n>","Cap how many findings to act on.",p=>Number.parseInt(p,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each rule\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--no-group","Ignore `###` headings \u2014 write one rule per finding.").option("--yes","Skip the confirmation (for scripted runs).").action(p=>Wg(p)),i.command("list").description("List the instance\u2019s agent skills and whether each is actually injected.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only skills in this state.").action(p=>Jg(p)),i.command("publish").argument("<slug...>","Skill slugs to approve (see `turbobase skills list`).").description("Publish skills \u2014 live by the time this returns. Sets visibility and cuts a release scoped to these skills.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((p,h)=>Yg(p,h)),i.command("unpublish").argument("<slug...>","Skill slugs to move back to draft.").description("Move skills back to draft. Retracts them from every prompt immediately \u2014 no release needed \u2014 and keeps the text.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((p,h)=>Xg(p,h)),i.command("releases").description("List the skill releases, newest first \u2014 the rollback targets.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(p=>ey(p)),i.command("rollback").argument("<version>","Release number to restore (see `turbobase skills releases`).").description("Re-point the current skill release at an earlier one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((p,h)=>Qg(p,h)),i.command("delete").argument("<slug...>","Skill slugs to delete (see `turbobase skills list`).").description("Delete skills. Permanent; prior releases keep their own copy of the text. Takes several slugs so cleaning up a bad push is one command.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((p,h)=>ty(p,h));let a=o.command("new").description("Scaffold a new extension file.");a.command("hook").description("Scaffold a hook file under hooks/.").requiredOption("--record <type>","Record type the hook targets, e.g. salesOrder").option("--event <event>","Lifecycle event","before_save").option("--template <name>","require-field | enforce-format | blank","require-field").option("--field <name>","Field name (for require-field / enforce-format)").option("--regex <pattern>","Pattern (for enforce-format)").option("--source <source>","Source id (netsuite, stripe, \u2026)").option("--id <id>","Override the generated hook id").action(async p=>{let h;try{h=ro("hook",{recordType:p.record,event:p.event,template:p.template,field:p.field,regex:p.regex,source:p.source,id:p.id})}catch($){S($ instanceof Error?$.message:String($))}let w=Te(process.cwd(),h.relativePath);await jo(w,h.content)==="skipped"&&S(`refusing to overwrite existing file: ${w}`),T(`wrote ${w}`)}),a.command("conduit").description("Scaffold a conduit file under conduits/ (cross-source bridge).").requiredOption("--source <source>","Origin source the record arrives from, e.g. shopify").requiredOption("--record <type>","Canonical record type the conduit triggers on, e.g. order").requiredOption("--to <source>","Target source the conduit bridges into, e.g. netsuite").option("--to-record <type>","Target record type (defaults to the trigger record type)").option("--event <event>","Cross-source lifecycle event","after_canonicalize_inbound").option("--id <id>","Override the generated conduit id").action(async p=>{let h;try{h=ro("conduit",{recordType:p.record,source:p.source,to:p.to,toRecordType:p.toRecord,event:p.event,id:p.id})}catch($){S($ instanceof Error?$.message:String($))}let w=Te(process.cwd(),h.relativePath);await jo(w,h.content)==="skipped"&&S(`refusing to overwrite existing file: ${w}`),T(`wrote ${w}`)}),o.command("test").argument("<file>","The extension file to dry-run").description("Dry-run an extension against samples/ fixtures (production sandbox parity).").option("--samples <dir>","Samples directory","samples").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").option("--ci","CI mode \u2014 alias for the non-zero-on-failure exit (always on for `test`).").action(async(p,h)=>{let w=sm(h.reporter),_=await Go(Te(process.cwd(),p)),$=Te(process.cwd(),h.samples),g=await Wo($);g.length===0&&!w&&T(`no samples found under ${$} \u2014 add JSON fixtures to dry-run against.`);let k;try{k=await Ai(_,g.map(L=>L.fixture))}catch(L){S(`bundle failed: ${L instanceof Error?L.message:String(L)}`)}if(w){let L=Bj(k);T(Oi(L,w)),L.cases.some(D=>D.status==="failed")&&process.exit(1);return}let A=0;for(let L of k){let D=L.pass?x.green("PASS"):x.red("FAIL");L.pass||(A+=1);let oe=L.error?` (error: ${L.error})`:L.observed!==L.expected?` (expected ${L.expected}, observed ${L.observed})`:L.rejection?` (rejected: ${L.rejection.code??"rejected"})`:"";T(` ${D} ${L.name}${oe}`)}let C=`${k.length-A}/${k.length} sample(s) passed.`;T(`
1797
- ${A===0?x.green(C):x.yellow(C)}`),A>0&&process.exit(1)}),o.command("deploy").argument("[file]","The extension file to deploy (single-file mode; omit with --to).").description("Deploy one extension (POST /v1/extensions) or the whole bundle (--to \u2192 /v1/config/apply).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--to <env>","Deploy the WHOLE bundle (turbobase/bundle.json) to this env (sandbox|prod).").action(async(p,h)=>{if(h.to){let k=await im(),{baseUrl:A,token:C}=await ne(h.baseUrl),L=new ee({baseUrl:A,token:C});try{let D=await fe(`applying bundle to ${h.to}`,()=>L.configApply(k));T(`applied bundle to ${h.to}: +${D.applied.add} ~${D.applied.change} -${D.applied.destroy}`+(D.backfillsQueued.length?` (${D.backfillsQueued.length} backfill(s) queued)`:""))}catch(D){D instanceof be&&D.status===403&&S("apply forbidden (403) \u2014 the stored PAT is not for an admin."),S(`bundle apply failed: ${D instanceof Error?D.message:String(D)}`)}return}p||S("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:w,token:_}=await ne(h.baseUrl),$=await Fj(Te(process.cwd(),p)),g=new ee({baseUrl:w,token:_});try{let k=await fe(`deploying ${p$(p)}`,()=>g.deploy($));wt()?T(Lr("Deployed",[`${x.bold(k.id)} ${to(k.status)} ${x.dim(k.outcome)}`])):T(`deployed ${k.id} \u2192 status=${k.status} (${k.outcome}).`)}catch(k){k instanceof be&&k.status===403&&S("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),S(`deploy failed: ${k instanceof Error?k.message:String(k)}`)}});let c=e.command("apps").description("Manage hosted apps served in your Turbobase app.");c.command("deploy").description("Build the app (if needed) and deploy it \u2014 cuts a new live version at /a/<slug>.").argument("<app>","App slug or id.").argument("[dir]","Source or built directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--no-build","Upload the directory as-is; it is already a built bundle.").option("--no-install","Skip `npm install` (assume deps are present).").option("--no-pull","Do not pull generated source even when the dir has no package.json.").option("--entry <file>","SPA entrypoint served for unknown routes.","index.html").option("--create","Create the app first if it does not exist yet.").option("--proposal <id>","Widget proposal this ship realizes (defaults to .turbobase/proposal.json).").option("--preview","Deploy to a preview URL instead of going live. Nothing about /a/<slug> changes until you `apps promote` it.").option("--label <text>","Label for the preview, so several open previews are tellable apart.").action(async(p,h,w)=>{let _=Te(process.cwd(),h??".");await ye.mkdir(_,{recursive:!0});let $=w.proposal??await y(_),{baseUrl:g,token:k}=await ne(w.baseUrl),A=new ee({baseUrl:g,token:k}),C=!1;try{C=(await A.appsList()).some(pe=>pe.slug===p||pe.id===p)}catch(pe){ke(pe,"extensions:deploy","deploy"),S(`could not reach ${g}: ${pe instanceof Error?pe.message:String(pe)}`)}if(!C){w.create||S(`no app "${p}" on ${g} \u2014 create it with \`turbobase apps create ${p}\`, or pass --create.`);let pe=await fe(`creating app ${p}`,()=>u(g,k,{slug:p},{tolerateExisting:!0}));pe.existed||T(`created ${pe.slug??p}.`)}let L=pe=>ye.stat(Rt(_,pe)).then(()=>!0).catch(()=>!1),D=p,oe=_,U=w.build!==!1;if(U&&!await L("package.json"))if(await L("index.html"))T("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),U=!1;else if(w.pull===!1)S(`${_} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let pe=await fe(`pulling ${p}`,()=>d(g,k,p));D=pe.slug??p,await b(_,pe.files,!0),T(`pulled generated source (rev ${pe.rev}).`)}let me;if(U){let pe=oy();if(me={buildId:pe,assetBase:sy(pe)},w.install!==!1&&!await L("node_modules")){T("installing dependencies\u2026");try{await E(["install"],_)}catch(Pt){S(`npm install failed: ${Pt instanceof Error?Pt.message:String(Pt)}`)}}T("building\u2026");try{await E(["run","build"],_,{TURBOBASE_ASSET_BASE:me.assetBase})}catch(Pt){S(`build failed: ${Pt instanceof Error?Pt.message:String(Pt)}`)}await L("dist")||S(`no dist/ after build in ${_} \u2014 check the app's build script.`),oe=Rt(_,"dist")}w.preview&&!me&&S(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${D}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let se=await J(g,k,D,oe,w.entry,$,me,w.preview?{label:w.label}:void 0);if(w.preview){let pe=se.previewUrl??"(no url returned)",Pt=se.expiresAt?new Date(se.expiresAt).toLocaleDateString():`${iy} days`;wt()?T(Lr("Preview deployed",[`${x.bold(D)} ${x.green(`v${se.version??"?"}`)} ${x.dim("not live")}`,`${x.bold(pe)}`,x.dim(`expires ${Pt}`)])):T(`preview ${D} v${se.version??"?"} \u2192 ${pe} (expires ${Pt}; /a/${D} unchanged).`),T(`next: turbobase apps promote ${D} ${se.previewId??"<preview-id>"} # make it live`),T(` turbobase apps preview discard ${se.previewId??"<preview-id>"}`);return}wt()?T(Lr("Deployed",[`${x.bold(D)} ${x.green(`v${se.version??"?"}`)} ${x.dim(se.url??`/a/${D}`)}`])):T(`deployed ${D} \u2192 v${se.version??"?"} (${se.url??`/a/${D}`}).`),await He(se,_)}),c.command("promote").description("Make a preview the live version at /a/<slug>. Promotes the exact reviewed bytes \u2014 no rebuild.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to promote (from `apps preview list`).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,h,w)=>{let{baseUrl:_,token:$}=await ne(w.baseUrl),g=await fe(`promoting ${h}`,()=>z(_,$,p,"promote",{previewId:h}));wt()?T(Lr("Promoted",[`${x.bold(p)} ${x.green(`v${g.version??"?"}`)} ${x.dim(g.url??`/a/${p}`)}`])):T(`promoted ${p} \u2192 v${g.version??"?"} is now live at ${g.url??`/a/${p}`}.`),await He(g)});let l=c.command("preview").description("Inspect and manage an app's open previews.");l.command("list").description("List an app's open previews (newest first).").argument("<app>","App slug or id.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,h)=>{let{baseUrl:w,token:_}=await ne(h.baseUrl),$=await V(w,_,p);if($.previews.length===0){T(`no open previews for ${p}.`);return}for(let g of $.previews){let k=g.label?` ${g.label}`:"",A=g.expiresAt?new Date(g.expiresAt).toLocaleDateString():"?";T(`v${g.version} ${g.previewId}${k} ${g.url} (expires ${A})`)}}),l.command("discard").description("Close a preview. The URL stops resolving; the version stays in deploy history.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to discard.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,h,w)=>{let{baseUrl:_,token:$}=await ne(w.baseUrl);await fe(`discarding ${h}`,()=>z(_,$,p,"discard",{previewId:h})),T(`discarded ${h}.`)}),c.command("create").description("Create a new hosted app (a bare app row) so a build can be shipped to it.").argument("<slug>","URL slug the app is served under: /a/<slug>.").option("--name <name>","Display name (defaults to the slug).").option("--description <text>","Optional description.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,h)=>{let{baseUrl:w,token:_}=await ne(h.baseUrl),$=await fe(`creating ${p}`,()=>u(w,_,{slug:p,name:h.name,description:h.description})),g=$.slug??p;wt()?T(Lr("Created",[`${x.bold(g)} ${x.dim($.url??`/a/${g}`)}`])):T(`created ${g} (${$.url??`/a/${g}`}).`),T(`next: turbobase apps push ${g} . # store the source`),T(` turbobase apps deploy ${g} # build + go live`)});async function u(p,h,w,_={}){let $=`${p.replace(/\/+$/,"")}/v1/apps`,g;try{g=await fetch($,{method:"POST",headers:{Authorization:`Bearer ${h}`,"content-type":"application/json"},body:JSON.stringify({slug:w.slug,name:w.name??w.slug,description:w.description})})}catch(k){S(`create request failed: ${k instanceof Error?k.message:String(k)}`)}if(g.status===401&&S("create unauthorized (401) \u2014 re-run `turbobase auth login`."),g.status===403&&S("create forbidden (403) \u2014 the PAT is not for an admin."),g.status===409){if(_.tolerateExisting)return{slug:w.slug,existed:!0};S(`an app with slug "${w.slug}" already exists.`)}return g.ok||S(`create failed: HTTP ${g.status} ${(await g.text().catch(()=>"")).slice(0,200)}`),await g.json().catch(()=>({}))}async function d(p,h,w){let _=`${p.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(w)}/pull`,$;try{$=await fetch(_,{headers:{Authorization:`Bearer ${h}`}})}catch(g){S(`pull request failed: ${g instanceof Error?g.message:String(g)}`)}return $.status===401&&S("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),$.status===403&&S("pull forbidden (403) \u2014 the PAT is not for an admin."),$.status===404&&S(`no generated source for "${w}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),$.ok||S(`pull failed: HTTP ${$.status} ${(await $.text().catch(()=>"")).slice(0,200)}`),await $.json()}async function b(p,h,w){let _=Te(p),$=0;for(let[g,k]of Object.entries(h)){let A=Te(_,g);A!==_&&!A.startsWith(_+lm)&&S(`refusing to write outside ${_}: ${g}`),w||await ye.stat(A).then(()=>!0).catch(()=>!1)&&S(`${A} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await ye.mkdir(No(A),{recursive:!0}),await ye.writeFile(A,k,"utf8"),$+=1}return $}function m(p){let h=p.indexOf(","),w=p.startsWith("data:")?h>=0?p.slice(h+1):"":p;if(!w)return null;try{let _=Buffer.from(w,"base64");return _.length>0?new Uint8Array(_):null}catch{return null}}async function f(p,h,w){let _=Te(p),$=async(k,A)=>{let C=Te(_,k);C!==_&&!C.startsWith(_+lm)&&S(`refusing to write outside ${_}: ${k}`),w||await ye.stat(C).then(()=>!0).catch(()=>!1)&&S(`${C} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await ye.mkdir(No(C),{recursive:!0}),await ye.writeFile(C,A)},g=`# ${h.title||"App change request"}
1970
+ `),"utf8"),$(`wrote ${C}${P?"":" (instance returned no grounding \u2014 connect a source first?)"}`)}),s.command("push").description("Write pending app-dev findings into the knowledge base, grouped one page at a time. Shows the plan and asks first; pages land unpublished.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--section <section>",`Only this section (${ns.join(" | ")}).`).option("--limit <n>","Cap how many findings to act on.",p=>Number.parseInt(p,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each page\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--no-group","Plan every finding on its own instead of merging the ones that look related \u2014 N findings for one page become N sequential appends.").option("--yes","Skip the confirmation (for scripted runs).").action(p=>oy(p)),s.command("list").description("List the knowledge base\u2019s pages and whether each is actually readable.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only pages in this state.").action(p=>iy(p)),s.command("publish").argument("<slug...>","Page slugs to publish (see `turbobase kb list`).").description("Publish pages: makes them reader-visible AND cuts a release scoped to them, so they are live when this returns.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((p,h)=>ay(p,h)),s.command("unpublish").argument("<slug...>","Page slugs to retract.").description("Hide pages from readers immediately. The text and its history are kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((p,h)=>cy(p,h)),s.command("versions").description("List knowledge-base releases, newest first, marking the current one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(p=>ly(p)),s.command("rollback").argument("<version>","Release number to restore (see `turbobase kb versions`).").description("Re-point the current knowledge-base release at an earlier one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((p,h)=>uy(p,h)),s.command("delete").argument("<slug>","Page slug to delete (see `turbobase kb list`).").description("Delete a page and its subtree. SOFT \u2014 restorable from the editor\u2019s trash, unlike `skills delete`.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((p,h)=>dy(p,h)),i.command("push").description("Write pending `## Agent rules` findings as draft agent rules, grouped by their `###` heading. Shows the plan and asks first; rules land unpublished and disabled.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--limit <n>","Cap how many findings to act on.",p=>Number.parseInt(p,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each rule\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--no-group","Ignore `###` headings \u2014 write one rule per finding.").option("--reapply","Also re-emit findings already applied \u2014 picks up a corrected `###` grouping or reworded body. Rules stay draft.").option("--yes","Skip the confirmation (for scripted runs).").action(p=>py(p)),i.command("list").description("List the instance\u2019s agent skills and whether each is actually injected.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only skills in this state.").action(p=>hy(p)),i.command("publish").argument("<slug...>","Skill slugs to approve (see `turbobase skills list`).").description("Publish skills \u2014 live by the time this returns. Sets visibility and cuts a release scoped to these skills.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((p,h)=>my(p,h)),i.command("unpublish").argument("<slug...>","Skill slugs to move back to draft.").description("Move skills back to draft. Retracts them from every prompt immediately \u2014 no release needed \u2014 and keeps the text.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((p,h)=>gy(p,h)),i.command("releases").description("List the skill releases, newest first \u2014 the rollback targets.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(p=>by(p)),i.command("rollback").argument("<version>","Release number to restore (see `turbobase skills releases`).").description("Re-point the current skill release at an earlier one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((p,h)=>yy(p,h)),i.command("delete").argument("<slug...>","Skill slugs to delete (see `turbobase skills list`).").description("Delete skills. Permanent; prior releases keep their own copy of the text. Takes several slugs so cleaning up a bad push is one command.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((p,h)=>wy(p,h));let a=o.command("new").description("Scaffold a new extension file.");a.command("hook").description("Scaffold a hook file under hooks/.").requiredOption("--record <type>","Record type the hook targets, e.g. salesOrder").option("--event <event>","Lifecycle event","before_save").option("--template <name>","require-field | enforce-format | blank","require-field").option("--field <name>","Field name (for require-field / enforce-format)").option("--regex <pattern>","Pattern (for enforce-format)").option("--source <source>","Source id (netsuite, stripe, \u2026)").option("--id <id>","Override the generated hook id").action(async p=>{let h;try{h=to("hook",{recordType:p.record,event:p.event,template:p.template,field:p.field,regex:p.regex,source:p.source,id:p.id})}catch(T){k(T instanceof Error?T.message:String(T))}let _=Te(process.cwd(),h.relativePath);await Do(_,h.content)==="skipped"&&k(`refusing to overwrite existing file: ${_}`),$(`wrote ${_}`)}),a.command("conduit").description("Scaffold a conduit file under conduits/ (cross-source bridge).").requiredOption("--source <source>","Origin source the record arrives from, e.g. shopify").requiredOption("--record <type>","Canonical record type the conduit triggers on, e.g. order").requiredOption("--to <source>","Target source the conduit bridges into, e.g. netsuite").option("--to-record <type>","Target record type (defaults to the trigger record type)").option("--event <event>","Cross-source lifecycle event","after_canonicalize_inbound").option("--id <id>","Override the generated conduit id").action(async p=>{let h;try{h=to("conduit",{recordType:p.record,source:p.source,to:p.to,toRecordType:p.toRecord,event:p.event,id:p.id})}catch(T){k(T instanceof Error?T.message:String(T))}let _=Te(process.cwd(),h.relativePath);await Do(_,h.content)==="skipped"&&k(`refusing to overwrite existing file: ${_}`),$(`wrote ${_}`)}),o.command("test").argument("<file>","The extension file to dry-run").description("Dry-run an extension against samples/ fixtures (production sandbox parity).").option("--samples <dir>","Samples directory","samples").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").option("--ci","CI mode \u2014 alias for the non-zero-on-failure exit (always on for `test`).").action(async(p,h)=>{let _=fm(h.reporter),x=await es(Te(process.cwd(),p)),T=Te(process.cwd(),h.samples),g=await Qo(T);g.length===0&&!_&&$(`no samples found under ${T} \u2014 add JSON fixtures to dry-run against.`);let S;try{S=await ji(x,g.map(L=>L.fixture))}catch(L){k(`bundle failed: ${L instanceof Error?L.message:String(L)}`)}if(_){let L=SL(S);$(Di(L,_)),L.cases.some(M=>M.status==="failed")&&process.exit(1);return}let P=0;for(let L of S){let M=L.pass?w.green("PASS"):w.red("FAIL");L.pass||(P+=1);let ae=L.error?` (error: ${L.error})`:L.observed!==L.expected?` (expected ${L.expected}, observed ${L.observed})`:L.rejection?` (rejected: ${L.rejection.code??"rejected"})`:"";$(` ${M} ${L.name}${ae}`)}let C=`${S.length-P}/${S.length} sample(s) passed.`;$(`
1971
+ ${P===0?w.green(C):w.yellow(C)}`),P>0&&process.exit(1)}),o.command("deploy").argument("[file]","The extension file to deploy (single-file mode; omit with --to).").description("Deploy one extension (POST /v1/extensions) or the whole bundle (--to \u2192 /v1/config/apply).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--to <env>","Deploy the WHOLE bundle (turbobase/bundle.json) to this env (sandbox|prod).").action(async(p,h)=>{if(h.to){let S=await hm(),{baseUrl:P,token:C}=await ne(h.baseUrl),L=new Q({baseUrl:P,token:C});try{let M=await se(`applying bundle to ${h.to}`,()=>L.configApply(S));$(`applied bundle to ${h.to}: +${M.applied.add} ~${M.applied.change} -${M.applied.destroy}`+(M.backfillsQueued.length?` (${M.backfillsQueued.length} backfill(s) queued)`:""))}catch(M){M instanceof be&&M.status===403&&k("apply forbidden (403) \u2014 the stored PAT is not for an admin."),k(`bundle apply failed: ${M instanceof Error?M.message:String(M)}`)}return}p||k("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:_,token:x}=await ne(h.baseUrl),T=await $L(Te(process.cwd(),p)),g=new Q({baseUrl:_,token:x});try{let S=await se(`deploying ${O$(p)}`,()=>g.deploy(T));Ye()?$(Dr("Deployed",[`${w.bold(S.id)} ${eo(S.status)} ${w.dim(S.outcome)}`])):$(`deployed ${S.id} \u2192 status=${S.status} (${S.outcome}).`)}catch(S){S instanceof be&&S.status===403&&k("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),k(`deploy failed: ${S instanceof Error?S.message:String(S)}`)}});let c=e.command("apps").description("Manage hosted apps served in your Turbobase app.");c.command("deploy").description("Build the app (if needed) and deploy it \u2014 cuts a new live version at /a/<slug>.").argument("<app>","App slug or id.").argument("[dir]","Source or built directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--no-build","Upload the directory as-is; it is already a built bundle.").option("--no-install","Skip `npm install` (assume deps are present).").option("--no-pull","Do not pull generated source even when the dir has no package.json.").option("--entry <file>","SPA entrypoint served for unknown routes.","index.html").option("--create","Create the app first if it does not exist yet.").option("--proposal <id>","Widget proposal this ship realizes (defaults to .turbobase/proposal.json).").option("--preview","Deploy to a preview URL instead of going live. Nothing about /a/<slug> changes until you `apps promote` it.").option("--label <text>","Label for the preview, so several open previews are tellable apart.").action(async(p,h,_)=>{let x=Te(process.cwd(),h??".");await we.mkdir(x,{recursive:!0});let T=_.proposal??await y(x),{baseUrl:g,token:S}=await ne(_.baseUrl),P=new Q({baseUrl:g,token:S}),C=!1;try{C=(await P.appsList()).some(oe=>oe.slug===p||oe.id===p)}catch(oe){le(oe,"extensions:deploy","deploy"),k(`could not reach ${g}: ${oe instanceof Error?oe.message:String(oe)}`)}if(!C){_.create||k(`no app "${p}" on ${g} \u2014 create it with \`turbobase apps create ${p}\`, or pass --create.`);let oe=await se(`creating app ${p}`,()=>u(g,S,{slug:p},{tolerateExisting:!0}));oe.existed||$(`created ${oe.slug??p}.`)}let L=oe=>we.stat(At(x,oe)).then(()=>!0).catch(()=>!1),M=p,ae=x,U=_.build!==!1;if(U&&!await L("package.json"))if(await L("index.html"))$("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),U=!1;else if(_.pull===!1)k(`${x} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let oe=await se(`pulling ${p}`,()=>d(g,S,p));M=oe.slug??p,await b(x,oe.files,!0),$(`pulled generated source (rev ${oe.rev}).`)}let he;if(U){let oe=xy();if(he={buildId:oe,assetBase:ky(oe)},_.install!==!1&&!await L("node_modules")){$("installing dependencies\u2026");try{await E(["install"],x)}catch(It){k(`npm install failed: ${It instanceof Error?It.message:String(It)}`)}}$("building\u2026");try{await E(["run","build"],x,{TURBOBASE_ASSET_BASE:he.assetBase})}catch(It){k(`build failed: ${It instanceof Error?It.message:String(It)}`)}await L("dist")||k(`no dist/ after build in ${x} \u2014 check the app's build script.`),ae=At(x,"dist")}_.preview&&!he&&k(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${M}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let me=await Y(g,S,M,ae,_.entry,T,he,_.preview?{label:_.label}:void 0);if(_.preview){let oe=me.previewUrl??"(no url returned)",It=me.expiresAt?new Date(me.expiresAt).toLocaleDateString():`${$y} days`;Ye()?$(Dr("Preview deployed",[`${w.bold(M)} ${w.green(`v${me.version??"?"}`)} ${w.dim("not live")}`,`${w.bold(oe)}`,w.dim(`expires ${It}`)])):$(`preview ${M} v${me.version??"?"} \u2192 ${oe} (expires ${It}; /a/${M} unchanged).`),$(`next: turbobase apps promote ${M} ${me.previewId??"<preview-id>"} # make it live`),$(` turbobase apps preview discard ${me.previewId??"<preview-id>"}`);return}Ye()?$(Dr("Deployed",[`${w.bold(M)} ${w.green(`v${me.version??"?"}`)} ${w.dim(me.url??`/a/${M}`)}`])):$(`deployed ${M} \u2192 v${me.version??"?"} (${me.url??`/a/${M}`}).`),await He(me,x)}),c.command("promote").description("Make a preview the live version at /a/<slug>. Promotes the exact reviewed bytes \u2014 no rebuild.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to promote (from `apps preview list`).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,h,_)=>{let{baseUrl:x,token:T}=await ne(_.baseUrl),g=await se(`promoting ${h}`,()=>z(x,T,p,"promote",{previewId:h}));Ye()?$(Dr("Promoted",[`${w.bold(p)} ${w.green(`v${g.version??"?"}`)} ${w.dim(g.url??`/a/${p}`)}`])):$(`promoted ${p} \u2192 v${g.version??"?"} is now live at ${g.url??`/a/${p}`}.`),await He(g)});let l=c.command("preview").description("Inspect and manage an app's open previews.");l.command("list").description("List an app's open previews (newest first).").argument("<app>","App slug or id.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,h)=>{let{baseUrl:_,token:x}=await ne(h.baseUrl),T=await H(_,x,p);if(T.previews.length===0){$(`no open previews for ${p}.`);return}for(let g of T.previews){let S=g.label?` ${g.label}`:"",P=g.expiresAt?new Date(g.expiresAt).toLocaleDateString():"?";$(`v${g.version} ${g.previewId}${S} ${g.url} (expires ${P})`)}}),l.command("discard").description("Close a preview. The URL stops resolving; the version stays in deploy history.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to discard.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,h,_)=>{let{baseUrl:x,token:T}=await ne(_.baseUrl);await se(`discarding ${h}`,()=>z(x,T,p,"discard",{previewId:h})),$(`discarded ${h}.`)}),c.command("create").description("Create a new hosted app (a bare app row) so a build can be shipped to it.").argument("<slug>","URL slug the app is served under: /a/<slug>.").option("--name <name>","Display name (defaults to the slug).").option("--description <text>","Optional description.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,h)=>{let{baseUrl:_,token:x}=await ne(h.baseUrl),T=await se(`creating ${p}`,()=>u(_,x,{slug:p,name:h.name,description:h.description})),g=T.slug??p;Ye()?$(Dr("Created",[`${w.bold(g)} ${w.dim(T.url??`/a/${g}`)}`])):$(`created ${g} (${T.url??`/a/${g}`}).`),$(`next: turbobase apps push ${g} . # store the source`),$(` turbobase apps deploy ${g} # build + go live`)});async function u(p,h,_,x={}){let T=`${p.replace(/\/+$/,"")}/v1/apps`,g;try{g=await fetch(T,{method:"POST",headers:{Authorization:`Bearer ${h}`,"content-type":"application/json"},body:JSON.stringify({slug:_.slug,name:_.name??_.slug,description:_.description})})}catch(S){k(`create request failed: ${S instanceof Error?S.message:String(S)}`)}if(g.status===401&&k("create unauthorized (401) \u2014 re-run `turbobase auth login`."),g.status===403&&k("create forbidden (403) \u2014 the PAT is not for an admin."),g.status===409){if(x.tolerateExisting)return{slug:_.slug,existed:!0};k(`an app with slug "${_.slug}" already exists.`)}return g.ok||k(`create failed: HTTP ${g.status} ${(await g.text().catch(()=>"")).slice(0,200)}`),await g.json().catch(()=>({}))}async function d(p,h,_){let x=`${p.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(_)}/pull`,T;try{T=await fetch(x,{headers:{Authorization:`Bearer ${h}`}})}catch(g){k(`pull request failed: ${g instanceof Error?g.message:String(g)}`)}return T.status===401&&k("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),T.status===403&&k("pull forbidden (403) \u2014 the PAT is not for an admin."),T.status===404&&k(`no generated source for "${_}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),T.ok||k(`pull failed: HTTP ${T.status} ${(await T.text().catch(()=>"")).slice(0,200)}`),await T.json()}async function b(p,h,_){let x=Te(p),T=0;for(let[g,S]of Object.entries(h)){let P=Te(x,g);P!==x&&!P.startsWith(x+ym)&&k(`refusing to write outside ${x}: ${g}`),_||await we.stat(P).then(()=>!0).catch(()=>!1)&&k(`${P} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await we.mkdir(Lo(P),{recursive:!0}),await we.writeFile(P,S,"utf8"),T+=1}return T}function m(p){let h=p.indexOf(","),_=p.startsWith("data:")?h>=0?p.slice(h+1):"":p;if(!_)return null;try{let x=Buffer.from(_,"base64");return x.length>0?new Uint8Array(x):null}catch{return null}}async function f(p,h,_){let x=Te(p),T=async(S,P)=>{let C=Te(x,S);C!==x&&!C.startsWith(x+ym)&&k(`refusing to write outside ${x}: ${S}`),_||await we.stat(C).then(()=>!0).catch(()=>!1)&&k(`${C} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await we.mkdir(Lo(C),{recursive:!0}),await we.writeFile(C,P)},g=`# ${h.title||"App change request"}
1798
1972
 
1799
1973
  > Widget proposal \`${h.proposalId}\` \u2014 build this change, then ship it with
1800
1974
  > \`turbobase apps deploy ${h.appSlug}\`. The deploy stamps this proposal complete.
@@ -1804,34 +1978,34 @@ ${h.bodyMarkdown||"_No description provided._"}
1804
1978
  ## Screen context
1805
1979
 
1806
1980
  `+(h.screenshot?"A screenshot of the screen this request was filed from is saved beside this file as `proposal-screenshot.png`.\n":`No screenshot was captured with this request.
1807
- `);if(await $("PROPOSAL.md",g),h.screenshot){let k=m(h.screenshot);k&&await $("proposal-screenshot.png",k)}await $(Rt(".turbobase","proposal.json"),`${JSON.stringify({proposalId:h.proposalId},null,2)}
1808
- `)}async function y(p){try{let h=await ye.readFile(Rt(p,".turbobase","proposal.json"),"utf8"),w=JSON.parse(h);return typeof w.proposalId=="string"&&w.proposalId?w.proposalId:void 0}catch{return}}async function v(p,h,w,_,$,g){let k=new ee({baseUrl:p,token:h});try{return await k.appsPush(w,_,{note:$,proposalId:g})}catch(A){if(A instanceof be){let C=A.body;if(A.status===401&&S("push unauthorized (401) \u2014 re-run `turbobase auth login`."),A.status===403&&C?.error==="admin_required"&&S("push forbidden (403) \u2014 the PAT is not for an admin."),A.status===403&&ke(A,"extensions:deploy","push app source"),A.status===404&&S(`no app "${w}" on this instance \u2014 create it with \`turbobase apps create ${w}\`.`),A.status===413&&(C?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&S("push rejected: the request body exceeded the instance limit."),S(`push rejected: ${C?.error??"too large"} (limit ${C?.limit??"?"}).`)),A.status===400){let L=C?.path?` in ${C.path}`:"",D=C?.reason?` (${C.reason})`:"";S(`push rejected: ${C?.error??"bad request"}${D}${L}.`)}}S(`push failed: ${A instanceof Error?A.message:String(A)}`)}}function E(p,h,w){return new Promise((_,$)=>{let g=um("npm",p,{cwd:h,stdio:"inherit",...w?{env:{...process.env,...w}}:{}});g.on("error",$),g.on("exit",k=>k===0?_():$(new Error(`npm ${p.join(" ")} exited ${k??"?"}`)))})}async function R(p,h,w,_){let $=`${p.replace(/\/+$/,"")}${w}`,g;try{g=await fetch($,{method:_.method,headers:{Authorization:`Bearer ${h}`,..._.body?{"content-type":"application/json"}:{}},..._.body?{body:JSON.stringify(_.body)}:{}})}catch(k){S(`request failed: ${k instanceof Error?k.message:String(k)}`)}if(g.status===401&&S("unauthorized (401) \u2014 re-run `turbobase auth login`."),g.status===403&&S("forbidden (403) \u2014 the PAT is not for an admin."),!g.ok){let k=await g.text().catch(()=>""),A=k.slice(0,300);try{let C=JSON.parse(k);A=C.message??C.error??A}catch{}S(`failed: HTTP ${g.status} ${A}`)}return await g.json().catch(()=>({}))}async function z(p,h,w,_,$){return await R(p,h,`/v1/apps/${encodeURIComponent(w)}/preview/${_}`,{method:"POST",body:$})}async function V(p,h,w){return{previews:(await R(p,h,`/v1/apps/${encodeURIComponent(w)}/previews`,{method:"GET"})).previews??[]}}async function J(p,h,w,_,$,g,k,A){let C;try{C=await fe(`zipping ${_}`,()=>$g(_))}catch(U){S(`could not zip ${_}: ${U instanceof Error?U.message:String(U)}`)}C.fileCount===0&&S(`${_} is empty \u2014 the build produced nothing.`);let L={Authorization:`Bearer ${h}`,"Content-Type":"application/zip"};$&&(L["x-app-entry"]=$),g&&(L["x-proposal-id"]=g),k&&(L["x-app-build-id"]=k.buildId,L["x-app-asset-base"]=k.assetBase),A&&(L["x-app-channel"]="preview",A.label&&(L["x-app-preview-label"]=encodeURIComponent(A.label)));let D=`${p.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(w)}/deploy`,oe;try{oe=await fe(`deploying ${w} (${C.fileCount} file${C.fileCount===1?"":"s"})`,()=>fetch(D,{method:"POST",headers:L,body:new Uint8Array(C.buffer)}))}catch(U){S(`deploy request failed: ${U instanceof Error?U.message:String(U)}`)}if(oe.status===401&&S("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),oe.status===403&&S("deploy forbidden (403) \u2014 the PAT is not for an admin."),oe.status===404&&S(`no app "${w}" on ${p} \u2014 create it with \`turbobase apps create ${w}\`.`),!oe.ok){let U=await oe.text().catch(()=>""),me=U.slice(0,300);try{let se=JSON.parse(U);me=se.message??se.error??me}catch{}S(`deploy failed: HTTP ${oe.status} ${me}`)}return await oe.json().catch(()=>({}))}async function He(p,h){let w=jg(p,{localDocsModifiedAt:await Xe(h)});w&&T(w.level==="warn"?x.yellow(w.message):x.dim(w.message))}async function Xe(p){if(!p)return null;let h=null;for(let w of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let _=await ye.stat(Rt(p,w));(h===null||_.mtimeMs>h)&&(h=_.mtimeMs)}catch{}return h===null?null:new Date(h)}c.command("pull").description("Write an app's generated source tree to disk (from the proposal that generated it).").argument("[app]","App slug or id. Omit when using --proposal (the app is derived from it).").argument("[dir]","Directory to write into (default ./<slug>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--force","Overwrite existing files.").option("--proposal <id>","Pull the app behind a widget proposal + its request context.").action(async(p,h,w)=>{let{baseUrl:_,token:$}=await ne(w.baseUrl);if(w.proposal){let C=new ee({baseUrl:_,token:$}),L;try{L=await fe(`fetching proposal ${w.proposal}`,()=>C.appPullContext(w.proposal))}catch(se){ke(se,"extensions:deploy","pull proposal"),se instanceof be&&se.status===404&&S(`no widget proposal "${w.proposal}" on ${_}.`),S(`could not fetch proposal ${w.proposal}: ${se instanceof Error?se.message:String(se)}`)}let D=await fe(`pulling ${L.appSlug}`,()=>d(_,$,L.appSlug)),oe=h??p,U=Te(process.cwd(),oe??L.appSlug);await ye.mkdir(U,{recursive:!0});let me=await b(U,D.files,!!w.force);await f(U,L,!!w.force),T(`pulled ${me} file${me===1?"":"s"} \u2192 ${U} (rev ${D.rev}), linked to proposal ${L.proposalId}.`),T(`next: cd ${Ic(process.cwd(),U)||"."} && turbobase apps deploy ${L.appSlug}`);return}p||S("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let g=await fe(`pulling ${p}`,()=>d(_,$,p)),k=Te(process.cwd(),h??g.slug??p);await ye.mkdir(k,{recursive:!0});let A=await b(k,g.files,!!w.force);T(`pulled ${A} file${A===1?"":"s"} \u2192 ${k} (rev ${g.rev}).`),T(`next: cd ${Ic(process.cwd(),k)||"."} && turbobase apps deploy ${g.slug}`)}),c.command("init").description("Scaffold a new app project locally, wired to your instance and to Claude Code.").argument("<app>","App slug \u2014 also the /a/<slug> mount path the build is pinned to.").argument("[dir]","Directory to scaffold into (default ./<app>).").option("--title <text>","Display title used in index.html and the starter component.").option("--base-url <url>","Instance to wire the project to (defaults to the active instance).").option("--no-claude","Skip the Claude Code wiring (CLAUDE.md, .mcp.json, .claude/).").option("--force","Overwrite existing files.").action(async(p,h,w)=>{let _=Te(process.cwd(),h??p),$=await ir(w.baseUrl).catch(()=>null),{scaffoldAppFiles:g,starterApp:k}=await Promise.resolve().then(()=>(zy(),Cy)),A=w.title??p,C=g({slug:p,title:A,appTsx:k(A),instanceOrigin:$?.baseUrl});await ye.mkdir(_,{recursive:!0});let L=await b(_,C,!!w.force);if(T(`scaffolded ${L} file${L===1?"":"s"} \u2192 ${_}`),w.claude!==!1){let oe=Al({baseUrl:$?.baseUrl,token:$?.token,appSlug:p}),U=0;for(let me of oe){let se=await d$(Rt(_,me.path),me);(se==="wrote"||se==="merged")&&(U+=1)}T(`wired Claude Code: ${U} file${U===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),$||le("not signed in \u2014 .mcp.json and the dev proxy carry placeholders. Run `turbobase auth login`, then `turbobase apps init` again (existing files are kept).")}let D=Ic(process.cwd(),_)||".";T(`next: cd ${D} && npm install && npm run dev`),T(` turbobase apps create ${p}`),T(` turbobase apps push ${p} .`),T(` turbobase apps deploy ${p} .`)}),c.command("list").description("List the hosted apps on your instance.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async p=>{let{baseUrl:h,token:w}=await ne(p.baseUrl),_=new ee({baseUrl:h,token:w}),$;try{$=await _.appsList()}catch(g){ke(g,"extensions:deploy","list apps"),S(`list apps failed: ${g instanceof Error?g.message:String(g)}`)}if(p.json)return T(JSON.stringify($,null,2));if($.length===0)return T("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");T(_n($.map(g=>[g.slug,g.name,g.deployed?"yes":"no",g.sourceRev===null?"\u2014":`rev ${g.sourceRev}`,g.audience]),{head:["SLUG","NAME","LIVE","SOURCE","AUDIENCE"]}))}),c.command("push").description("Record the local source tree as the app's newest source revision (does NOT deploy).").argument("<app>","App slug or id.").argument("[dir]","Source directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--note <text>","Short note stored with the revision.").option("--proposal <id>","Widget proposal this rev works (defaults to .turbobase/proposal.json).").action(async(p,h,w)=>{let _=Te(process.cwd(),h??".");await ye.stat(_).then(se=>se.isDirectory()).catch(()=>!1)||S(`${_} is not a directory.`);let{baseUrl:g,token:k}=await ne(w.baseUrl),A=w.proposal??await y(_),{files:C,skipped:L,secrets:D,unstorable:oe}=await ny(_),U=Object.keys(C).length;if(U===0&&S(`no source files found under ${_} (build output and node_modules are skipped).`),oe.length>0){for(let se of oe)le(`${se} contains a NUL byte (U+0000), which cannot be stored.`);S(`push aborted: ${oe.length} ${oe.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let se of L)le(x.dim(`skipped binary file ${se}`));for(let se of D)le(x.dim(`skipped ${se} (holds credentials \u2014 never pushed)`));let me=await fe(`pushing ${U} file${U===1?"":"s"}`,()=>v(g,k,p,C,w.note,A));T(`pushed ${me.files} file${me.files===1?"":"s"} \u2192 ${me.slug} rev ${me.rev} (source only, nothing deployed).`),T(`next: turbobase apps deploy ${me.slug}`)}),o.command("plan").description("Diff the local bundle (turbobase/bundle.json) against a target env (no writes).").option("--from <env>","Source env the bundle was authored against (advisory).").option("--to <env>","Target env to diff against (sandbox|prod).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async p=>{let h=await im(),{baseUrl:w,token:_}=await ne(p.baseUrl),$=new ee({baseUrl:w,token:_}),g;try{g=await fe(`planning against ${p.to??w}`,()=>$.configPlan(h))}catch(k){S(`plan failed: ${k instanceof Error?k.message:String(k)}`)}Wj(g,p.to??w)}),o.command("promote").description("Promote the bundle from one env to another behind a confirm-slug gate (fail-closed).").requiredOption("--from <env>","Source env (e.g. sandbox).").requiredOption("--to <env>","Target env (e.g. prod).").requiredOption("--confirm <slug>","Type the EXACT target instance slug to confirm (fail-closed).").option("--base-url <url>","Target instance base URL (defaults to the active instance).").action(async p=>{let h=await im(),{baseUrl:w,token:_}=await ne(p.baseUrl),$=h.tenant??Gj(w),g=wy(p.confirm,$);g.ok||S(`promote refused (fail-closed): ${g.reason}`);let k=new ee({baseUrl:w,token:_});try{let A=await fe(`promoting ${p.from} \u2192 ${p.to} (${$})`,()=>k.configApply(h));if(wt()){let C=[`${x.bold(`${p.from} \u2192 ${p.to}`)} ${x.dim($??"")}`,`${jr.add(String(A.applied.add))} ${jr.change(String(A.applied.change))} ${jr.destroy(String(A.applied.destroy))}`];A.backfillsQueued.length&&C.push(x.dim(`${A.backfillsQueued.length} backfill(s) queued`)),T(Lr("Promoted",C))}else T(`promoted ${p.from} \u2192 ${p.to} (${$}): +${A.applied.add} ~${A.applied.change} -${A.applied.destroy}`+(A.backfillsQueued.length?` (${A.backfillsQueued.length} backfill(s) queued)`:""))}catch(A){A instanceof be&&A.status===403&&S("promote forbidden (403) \u2014 the stored PAT is not for an admin."),S(`promote failed: ${A instanceof Error?A.message:String(A)}`)}});let Rr=async(p,h)=>{let{baseUrl:w,token:_}=await ne(h.baseUrl),$=new ee({baseUrl:w,token:_}),g=h.limit?Number(h.limit):void 0;if(h.follow){try{await Cg($,p,{follow:!0,limit:g,intervalMs:h.intervalMs?Number(h.intervalMs):void 0,sink:T})}catch(k){S(`logs --follow failed: ${k instanceof Error?k.message:String(k)}`)}return}try{let k=await $.logs(p,g);k.length===0&&T(`no logs for ${p}.`);for(let A of k)T(` [${A.level}] ${A.ts??""} ${A.message}`)}catch(k){S(`logs failed: ${k instanceof Error?k.message:String(k)}`)}};o.command("logs").argument("<id>","Extension id (default) or conduit id (with --follow)").description("Read an extension's logs; with --follow, stream a conduit's run ledger.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--limit <n>","Max log lines").option("--follow","Stream the conduit_event run ledger for the given conduit id.").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(Rr),o.command("lint").argument("<file>","The hook or conduit definition file to lint").description("Statically lint a hook/conduit for semantic foot-guns (offline).").option("--ci","Exit non-zero when any warning fires (else exit 0).").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").action(async(p,h)=>{let w=sm(h.reporter),_=Te(process.cwd(),p),$=await Go(_),g=Tg($);w?T(Oi(Vj(p,g),w)):T(Eg(p,g,{warn:x.yellow,ok:x.green,dim:x.dim})),h.ci&&g.warnings.length>0&&process.exit(1)}),o.command("replay").argument("<file>","The conduit file to replay").description("Dry-run a conduit through dispatch\u2192transform\u2192apply (offline against a fixture).").option("--fixture <file>","JSON conduit-trigger fixture to replay against.").option("--against <target>","Replay against a running sandbox (online; deferred without a local DB).").option("--trace","Emit the per-stage trace (guards, atlas, apply-branch, bindings).").option("--reporter <fmt>","Emit machine-readable output: junit | json (one case per stage).").action(async(p,h)=>{let w=sm(h.reporter),_=await bg(Te(process.cwd(),p));if(h.against){h.against!=="sandbox"&&S(`unknown --against target '${h.against}' (only 'sandbox' is supported).`);try{await gg(xl(_))}catch(k){S(k instanceof Error?k.message:String(k))}return}h.fixture||S("replay needs a --fixture <file> (offline) or --against sandbox (online).");let $;try{$=await yg(Te(process.cwd(),h.fixture))}catch(k){S(`could not read fixture ${h.fixture}: ${k instanceof Error?k.message:String(k)}`)}let g=await mg(_,$,h.fixture);if(w){let k=Hj(g);T(Oi(k,w)),k.cases.some(A=>A.status==="failed")&&process.exit(1);return}T(wg(g,!!h.trace)),g.error&&process.exit(1)}),o.command("binding").description("List conduit source bindings (--status divergent) or re-enqueue one (--retry <id>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <status>","Filter by write_status (ok|pending|blocked|divergent|muted).").option("--retry <id>","Re-enqueue the fan-out write for this binding id (admin-only).").option("--limit <n>","Max rows listed").action(async p=>{let{baseUrl:h,token:w}=await ne(p.baseUrl),_=new ee({baseUrl:h,token:w});try{await zg(_,{status:p.status,retry:p.retry,limit:p.limit?Number(p.limit):void 0,sink:T})}catch($){$ instanceof be&&$.status===403&&S("forbidden (403) \u2014 binding --retry requires an admin PAT."),$ instanceof be&&$.status===409&&S("binding is not retryable (only divergent/blocked bindings can be retried)."),S(`ext binding failed: ${$ instanceof Error?$.message:String($)}`)}}),o.command("install").argument("<spec>","Extension name, optionally name@version").description("Install an extension from the marketplace into your instance's extension store.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--connection <id>",'Bind this connection id (required when the extension declares a { type:"connection" } input).').action(async(p,h)=>{let w=p.lastIndexOf("@"),_=w>0?p.slice(0,w):p,$=w>0?p.slice(w+1):void 0,g=gl();g||S(`marketplace not configured \u2014 set ${Xn} and ${Ri}.
1809
- Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let k=yl(g.registryUrl);k&&S(k);let{baseUrl:A,token:C}=await ne(h.baseUrl),L=new Ho(g),D;try{D=await fe(`fetching ${p}`,()=>L.fetchBundle(_,$))}catch(pe){S(`marketplace fetch failed for ${p}: ${pe instanceof Error?pe.message:String(pe)}`)}let oe=vi(D.manifest),U=null;if(oe.length>0){if(!h.connection){let pe=oe.map(Pt=>Pt.source_system).join(", ");S(`${D.name}@${D.version} declares a connection input (source: ${pe}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}U=h.connection}let me=Kj(D.bundle,D.name,D.kind),se=new ee({baseUrl:A,token:C});try{let pe=await fe(`installing ${D.name}@${D.version}`,()=>se.deploy({...me,provenance:"marketplace",...U?{connectionId:U}:{}}));T(`installed ${D.name}@${D.version} \u2192 ${pe.id} (status=${pe.status}, ${pe.outcome})`+(U?` bound to connection ${U}.`:"."))}catch(pe){pe instanceof be&&pe.status===403&&S("install forbidden (403) \u2014 the stored PAT is not for an admin."),S(`install failed: ${pe instanceof Error?pe.message:String(pe)}`)}}),o.command("publish").description("Publish an authored extension to the public marketplace (publisher allowlist required).").argument("<file>","The extension file to publish (defineHook/defineConduit source).").requiredOption("--name <name>","Marketplace package name (lowercase, e.g. acme-recipes).").requiredOption("--pkg-version <version>","Semver-ish package version (e.g. 1.0.0).").option("--manifest <file>","Path to a JSON manifest (declared inputs[], capabilities).").action(async(p,h)=>{let w=gl();w||S(`marketplace not configured \u2014 set ${Xn} and ${Ri}.
1810
- Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let _=yl(w.registryUrl);_&&S(_);let $=Te(process.cwd(),p),g=await Go($),k=/\bdefineConduit\s*[<(]/.test(g)?"conduit":"hook",A={};if(h.manifest){let D=Te(process.cwd(),h.manifest),oe;try{oe=await ye.readFile(D,"utf8")}catch{S(`manifest not found at ${h.manifest}.`)}let U;try{U=JSON.parse(oe)}catch{S(`manifest is not valid JSON: ${h.manifest}.`)}(typeof U!="object"||U===null||Array.isArray(U))&&S("manifest must be a JSON object."),A=U}try{tl(A,g)}catch(D){D instanceof Cr&&S(D.message),S(`manifest validation failed: ${D instanceof Error?D.message:String(D)}`)}let C=new Ho(w);try{await fe(`publishing ${h.name}@${h.pkgVersion}`,()=>C.publish({name:h.name,version:h.pkgVersion,kind:k,bundle:g,manifest:A}))}catch(D){D instanceof be&&D.status===403&&S("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),D instanceof be&&D.status===409&&S(`version already published \u2014 ${h.name}@${h.pkgVersion} exists. Bump the version.`),S(`publish failed: ${D instanceof Error?D.message:String(D)}`)}let L=vi(A);T(`published ${h.name}@${h.pkgVersion} (kind=${k}) to the marketplace.`),L.length>0&&T(` declares ${L.length} connection input(s): ${L.map(D=>D.source_system).join(", ")} \u2014 bound at install.`)}),n.command("init").description("Scaffold a Claude-Code extension project in the current dir.").option("--base-url <url>","Instance to wire .mcp.json to (defaults to the active instance).").action(async p=>{let h=await ir(p.baseUrl).catch(()=>null),w=Al({baseUrl:h?.baseUrl,token:h?.token}),_=0,$=0,g=0;for(let k of w){let A=Te(process.cwd(),k.path),C=await d$(A,k);C==="wrote"?(_+=1,T(` wrote ${k.path}`)):C==="merged"?(g+=1,T(` merged ${k.path} (added the .mcp.json rule)`)):($+=1,T(` skipped ${k.path} (exists)`))}T(`
1811
- project init: ${_} written, ${g} merged, ${$} skipped.`)}),n.command("ci").description(`Write the reusable release-deploy GitHub Action to ${Pl} (non-destructive).`).action(async()=>{let p=Lg(),h=0,w=0;for(let _ of p){let $=Te(process.cwd(),_.path);await jo($,_.content,_.executable)==="wrote"?(h+=1,T(` wrote ${_.path}`)):(w+=1,T(` skipped ${_.path} (exists)`))}T(`
1812
- project ci: ${h} written, ${w} skipped.`),h>0&&(T(`
1813
- Next: mint a releases:write PAT in your Turbobase app (Settings \u203A Access tokens),`),T("store it as the GitHub Actions secret TURBOBASE_RELEASE_PAT, and set the repo"),T("variable TURBOBASE_BASE_URL \u2014 the workflow header has the step-by-step."))}),n.command("samples").description("Generate samples/<recordType>.json fixtures from the live instance catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Output directory for the fixtures","samples").option("--event <event>","Lifecycle event to stamp on each fixture","before_save").option("--force","Overwrite existing fixture files (default: skip files that exist).").action(async p=>{let{baseUrl:h,token:w}=await ne(p.baseUrl),_=new ee({baseUrl:h,token:w}),$;try{$=await _.catalogRecords()}catch(L){L instanceof be&&(L.status===401||L.status===403)&&S("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),S(`catalog fetch failed: ${L instanceof Error?L.message:String(L)}`)}if($.length===0){T("no records in the instance catalog \u2014 nothing to generate.");return}let g=Te(process.cwd(),p.out),k=vg($,{event:p.event}),A=0,C=0;for(let{recordType:L,fixture:D}of k){let oe=Rt(g,`${L}.json`),U=`${JSON.stringify(D,null,2)}
1814
- `;p.force?(await ye.mkdir(No(oe),{recursive:!0}),await ye.writeFile(oe,U,{mode:420}),A+=1,T(` wrote ${p.out}/${L}.json`)):await jo(oe,U)==="wrote"?(A+=1,T(` wrote ${p.out}/${L}.json`)):(C+=1,T(` skipped ${p.out}/${L}.json (exists \u2014 use --force to overwrite)`))}T(`
1815
- samples init: ${A} written, ${C} skipped.`)});let rr=e.command("guardrails").description("Control PG\u2192source write-back with DENY rules (staged write rollout)."),tn=p=>[p.name,p.enabled?x.green("on"):x.dim("off"),p.source,p.record,p.when||x.dim("(always)"),p.note??""];rr.command("list").description("List every write guardrail on your instance.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async p=>{let{baseUrl:h,token:w}=await ne(p.baseUrl),_=new ee({baseUrl:h,token:w}),$;try{$=await _.guardrailsList()}catch(g){ke(g,"extensions:deploy","list guardrails"),S(`list guardrails failed: ${g instanceof Error?g.message:String(g)}`)}if(p.json)return T(JSON.stringify($,null,2));if($.length===0)return T(`no write guardrails \u2014 every record the admin entitlement allows is writable.
1816
- `+x.dim("create one with `turbobase guardrails create <name> --source <s> --when '\u2026'`"));T(_n($.map(tn),{head:["NAME","STATE","SOURCE","RECORD","WHEN","NOTE"]}))}),rr.command("create <name>").description("Create a DENY rule. Blocks PG\u2192source writes that match it.").option("--source <system>","Adapter id to scope to, or '*' for every source.","*").option("--record <type>","Record type to scope to, or '*' for every record.","*").option("--when <expr>","Condition, e.g. 'recordType not_in customer,invoice' or 'record.amount gt 10000'. Omit to deny unconditionally.").option("--message <text>","What a blocked writer is told.").option("--note <text>","Why this rule exists \u2014 for whoever reads `list` later.").option("--disabled","Create the rule parked, so it takes effect only when enabled.").option("--confirm-freeze-all","Required for an unconditional '*'/'*' rule.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,h)=>{let{baseUrl:w,token:_}=await ne(h.baseUrl),$=new ee({baseUrl:w,token:_}),g;try{g=await $.guardrailCreate({name:p,source:h.source,record:h.record,...h.when?{when:h.when}:{},...h.message?{message:h.message}:{},...h.note?{note:h.note}:{},...h.disabled?{enabled:!1}:{},...h.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(k){ke(k,"extensions:deploy","create a guardrail"),S(`create guardrail failed: ${k instanceof Error?k.message:String(k)}`)}T(`${x.green("\u2713")} guardrail ${x.bold(g.name)} created${g.enabled?"":x.dim(" (parked \u2014 enable it to take effect)")}`),T(x.dim(` denies ${g.source}/${g.record}${g.when?` where ${g.when}`:" (always)"}`)),T(x.dim(` verify with: turbobase guardrails test --source ${g.source==="*"?"<source>":g.source} --record <record>`))}),rr.command("edit <name>").description("Change a rule \u2014 most often widening its exception set as records are proven.").option("--when <expr>","New condition. Pass '' to make it unconditional.").option("--message <text>","What a blocked writer is told.").option("--note <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,h)=>{h.when===void 0&&h.message===void 0&&h.note===void 0&&S("edit: nothing to change \u2014 pass --when, --message or --note.");let{baseUrl:w,token:_}=await ne(h.baseUrl),$=new ee({baseUrl:w,token:_}),g;try{g=await $.guardrailUpdate(p,{...h.when!==void 0?{when:h.when}:{},...h.message!==void 0?{message:h.message}:{},...h.note!==void 0?{note:h.note}:{}})}catch(k){ke(k,"extensions:deploy","edit a guardrail"),S(`edit guardrail failed: ${k instanceof Error?k.message:String(k)}`)}T(`${x.green("\u2713")} guardrail ${x.bold(g.name)} updated`),T(x.dim(` denies ${g.source}/${g.record}${g.when?` where ${g.when}`:" (always)"}`))});for(let[p,h,w]of[["enable",!0,"enabled"],["disable",!1,"disabled"]])rr.command(`${p} <name>`).description(h?"Arm a parked rule.":"Park a rule without deleting it \u2014 the reversible move mid-rollout.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(_,$)=>{let{baseUrl:g,token:k}=await ne($.baseUrl),A=new ee({baseUrl:g,token:k});try{await A.guardrailUpdate(_,{enabled:h})}catch(C){ke(C,"extensions:deploy",`${p} a guardrail`),S(`${p} guardrail failed: ${C instanceof Error?C.message:String(C)}`)}T(`${x.green("\u2713")} guardrail ${x.bold(_)} ${w}`),h||T(x.dim(" writes it was blocking are now permitted (subject to the other rules)."))});rr.command("delete <name>").description("Remove a rule. This OPENS a write path \u2014 prefer `disable` if unsure.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,h)=>{let{baseUrl:w,token:_}=await ne(h.baseUrl),$=new ee({baseUrl:w,token:_});try{await $.guardrailDelete(p)}catch(g){ke(g,"extensions:deploy","delete a guardrail"),S(`delete guardrail failed: ${g instanceof Error?g.message:String(g)}`)}T(`${x.green("\u2713")} guardrail ${x.bold(p)} deleted`)}),rr.command("test").description("Would a write be blocked? Runs the real evaluator; writes nothing.").requiredOption("--source <system>","Adapter id the write targets.").requiredOption("--record <type>","Record type the write targets.").option("--origin <origin>","Write origin to simulate ('user', 'agent').").option("--fields <json>","A candidate row as JSON, so `record.<column>` conditions can be decided.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON.").action(async p=>{let h;if(p.fields)try{h=JSON.parse(p.fields)}catch(k){S(`--fields must be valid JSON: ${k instanceof Error?k.message:String(k)}`)}let{baseUrl:w,token:_}=await ne(p.baseUrl),$=new ee({baseUrl:w,token:_}),g;try{g=await $.guardrailTest({source:p.source,record:p.record,...p.origin?{origin:p.origin}:{},...h?{fields:h}:{}})}catch(k){ke(k,"extensions:deploy","test guardrails"),S(`guardrails test failed: ${k instanceof Error?k.message:String(k)}`)}if(p.json)return T(JSON.stringify(g,null,2));g.allowed?T(`${x.green("\u2713")} ${p.source}/${p.record} \u2014 no guardrail blocks this write`):(T(`${x.red("\u2717")} ${p.source}/${p.record} \u2014 blocked by ${x.bold(g.blockedBy??"?")}`),g.message&&T(x.dim(` ${g.message}`))),g.undecided.length>0&&(T(x.yellow(` ${g.undecided.length} rule(s) need a row to decide: ${g.undecided.join(", ")}`)),T(x.dim(` re-run with --fields '{"\u2026":"\u2026"}' to evaluate them.`))),g.allowed||(process.exitCode=1)});let mr=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),Un=(p,h={})=>{let w=`${x.bold(p.table)} ${x.dim(p.displayName)}`;T(p.exists===!1?`${w} ${x.dim("(new)")}`:w);for(let _ of p.fields){let $=[_.required?"required":null].filter(Boolean).join(", "),g=h.showClaimants&&_.claimedBy?.length?` ${x.dim(`\u2190 ${_.claimedBy.join(", ")}`)}`:"";T(` ${_.column.padEnd(28)} ${_.type}${$?` (${$})`:""}${g}`)}h.showClaimants&&p.claimants.length>1&&T(x.dim(` claimed by ${p.claimants.join(", ")}`))};function Zn(p){if(p instanceof be&&p.status===409){let h=p.body;h?.error==="table_conflict"&&h.message&&(le(h.message),process.exit(1))}S(`tables: ${p instanceof Error?p.message:String(p)}`)}let ai=async p=>{let h=Rt(Te(process.cwd(),p),"public","turbobase.json"),w=await ye.readFile(h,"utf8").catch(()=>null);if(w===null)return null;let _;try{_=JSON.parse(w)}catch(g){S(`${h} is not valid JSON: ${g instanceof Error?g.message:String(g)}`)}let $=_.tables;return $===void 0?{tables:[],manifestPath:h}:(Array.isArray($)||S(`${h}: "tables" must be an array.`),{tables:$,manifestPath:h})};mr.command("list").description("List the custom tables on your instance and who claims each one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async p=>{let{baseUrl:h,token:w}=await ne(p.baseUrl),_=new ee({baseUrl:h,token:w}),$;try{$=await _.tablesList()}catch(g){ke(g,"extensions:deploy","list tables"),S(`list tables failed: ${g instanceof Error?g.message:String(g)}`)}if(p.json)return T(JSON.stringify($,null,2));if($.length===0)return T("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");T(_n($.map(g=>[g.table,g.displayName,String(g.fields.length),g.status,g.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),mr.command("plan").description("Preview what this project's declared tables would do. Writes nothing; exits 1 on a conflict.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: the app slug in .turbobase, else cli).").action(async(p,h)=>{let w=await ai(p??".");if(w||S(`no public/turbobase.json under ${Te(process.cwd(),p??".")}.`),w.tables.length===0)return T(`${w.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:_,token:$}=await ne(h.baseUrl),g=new ee({baseUrl:_,token:$}),k;try{k=await fe("planning tables",()=>g.tablesPlan({claimedBy:h.as,tables:w.tables}))}catch(A){ke(A,"extensions:deploy","plan tables"),Zn(A)}T(`claiming as ${x.bold(k.claimedBy)}`);for(let A of k.tables)Un(A,{showClaimants:!0});T(""),T(x.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),mr.command("apply").description("Apply this project's declared tables to the instance.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: cli).").action(async(p,h)=>{let w=await ai(p??".");if(w||S(`no public/turbobase.json under ${Te(process.cwd(),p??".")}.`),w.tables.length===0)return T(`${w.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:_,token:$}=await ne(h.baseUrl),g=new ee({baseUrl:_,token:$}),k;try{k=await fe("applying tables",()=>g.tablesApply({claimedBy:h.as,tables:w.tables}))}catch(A){ke(A,"extensions:deploy","apply tables"),Zn(A)}for(let A of k.tables)Un(A,{showClaimants:!0});T(`applied ${k.tables.length} table${k.tables.length===1?"":"s"} as ${k.claimedBy}.`)}),mr.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(p,h)=>[...h??[],p],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,h)=>{let w=h.field.map(A=>{let[C,L,D]=A.split(":");return(!C||!L)&&S(`--field "${A}" must be name:type[:required] (e.g. title:text:required).`),D!==void 0&&D!=="required"&&S(`--field "${A}": the third part may only be "required".`),{name:C,type:L,...D==="required"?{required:!0}:{}}}),{baseUrl:_,token:$}=await ne(h.baseUrl),g=new ee({baseUrl:_,token:$}),k;try{k=await fe(`creating cr_${p}`,()=>g.tablesApply({tables:[{slug:p,displayName:h.name??p,fields:w,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(A){ke(A,"extensions:deploy","create a table"),Zn(A)}for(let A of k.tables)Un(A);T(""),T(x.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),mr.command("drop").description("Drop a table and everything in it. Irreversible.").argument("<slug>","Table slug (without the cr_ prefix).").requiredOption("--confirm <slug>","Type the EXACT slug to confirm (fail-closed).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,h)=>{h.confirm!==p&&S(`drop refused: --confirm "${h.confirm}" does not match "${p}".`);let{baseUrl:w,token:_}=await ne(h.baseUrl),$=new ee({baseUrl:w,token:_}),g;try{g=await fe(`dropping cr_${p}`,()=>$.tablesDrop(p,h.confirm))}catch(k){ke(k,"extensions:deploy","drop a table"),S(`drop failed: ${k instanceof Error?k.message:String(k)}`)}if(!g.removed)return T(`no table named "${p}" on this instance \u2014 nothing dropped.`);T(`dropped ${g.table} and every row in it.`)});let Oc=e.command("sandbox").description("Ephemeral local authoring sandboxes.");Oc.command("create").description("Stand up a fresh local sandbox seeded with a sampled+redacted slice of an instance.").requiredOption("--from <instance>","Source instance to clone the data slice from.").option("--ttl <duration>","Time-to-live before reaping (e.g. 72h, 30m, 7d).","72h").option("--sample <pct>","Percent of each table to copy (e.g. 2%).","2%").option("--base-url <url>","Local base URL the sandbox is reachable at.").action(async p=>{process.env.TURBOBASE_SANDBOX="1";let h=am(),w;try{w=await hy(h,{fromTenant:p.from,ttl:p.ttl,sample:p.sample,baseUrl:p.baseUrl})}catch(_){_ instanceof es&&S(_.message),S(`sandbox create failed: ${_ instanceof Error?_.message:String(_)}`)}T(`sandbox ${w.name} ready.`),T(` source: ${w.fromTenant} (sampled ${Math.round(w.sampleFraction*100)}%, redacted)`),T(` url: ${w.url}`),T(` expires: ${w.expiresAt}`)}),Oc.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async p=>{let h=am();await Fl(h).catch(()=>[]);let w;try{w=await my(h,p)}catch(_){S(`sandbox destroy failed: ${_ instanceof Error?_.message:String(_)}`)}w||S(`no sandbox named '${p}'.`),T(`destroyed sandbox ${w.name} (dropped ${w.database}).`)}),Oc.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let p=am(),h=await Fl(p).catch(()=>[]),w=await Li(),{active:_}=ql(w);if(_.length===0)T("no active sandboxes.");else{for(let $ of _)T(` ${$.name} from=${$.fromTenant} expires=${$.expiresAt} ${$.url}`);T(`
1817
- ${_.length} active sandbox(es).`)}h.length>0&&T(`(reaped ${h.length} expired sandbox(es).)`)}),o.command("export").description("Snapshot the live instance into turbobase/bundle.json.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",Mi).action(async p=>{let{baseUrl:h,token:w}=await ne(p.baseUrl),_=new ee({baseUrl:h,token:w}),$;try{$=await fe("exporting instance config",()=>_.configExport())}catch(A){A instanceof be&&(A.status===401||A.status===403)&&S("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),S(`ext export failed: ${A instanceof Error?A.message:String(A)}`)}let g=typeof $.serialized=="string"?$.serialized:`${JSON.stringify($.manifest??$,null,2)}
1818
- `,k=Te(process.cwd(),p.out,rs);await ye.mkdir(No(k),{recursive:!0}),await ye.writeFile(k,g,"utf8"),T(`wrote ${p.out}/${rs} (${g.split(`
1819
- `).length} lines).`)});let pm=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),f$=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],fm=()=>process.env.TURBOBASE_HOME?.trim()||Rt(Mj(),".turbobase"),h$=()=>"1.1.17",ci=async()=>Promise.all(f$.map(async p=>{try{return await import(p.name),{...p,present:!0}}catch{return{...p,present:!1}}}));pm.command("status").description("Report which optional native packages are installed.").action(async()=>{let p=await ci();for(let h of p)T(`${h.present?lt.success("installed"):lt.warn("missing")} ${x.bold(h.name)} \u2014 ${h.needs}`);p.some(h=>!h.present)&&T(`
1820
- run \`${Yo} ext extras install\` to fetch them into ${fm()}.`)}),pm.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let p=await ci();if(p.every(C=>C.present)){T(lt.success("extras already installed \u2014 nothing to do."));return}let h=fm();await ye.mkdir(h,{recursive:!0});let w=p.filter(C=>!C.present).map(C=>C.name),_=jl(process.platform,process.arch),$=async(C,L)=>{let{code:D,stderr:oe}=await ii("npm",["install","--prefix",h,"--no-audit","--no-fund",...C]);D!==0&&S(`extras install failed while installing ${L} (npm exited ${D}).
1821
- ${oe.trim()}
1822
- These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},g=w.filter(C=>C!=="isolated-vm");if(g.length>0){let C=g.map(L=>`${L}@${zl[L]??"latest"}`);T(`installing ${C.join(", ")} \u2192 ${h}/node_modules \u2026`),await $(C,g.join(", "))}if(w.includes("isolated-vm")){let C=`isolated-vm@${zl["isolated-vm"]}`;if(T(`installing ${C} \u2192 ${h}/node_modules \u2026`),await $(["--ignore-scripts",C],"isolated-vm"),ay.includes(_)){let D=`${Nl}@${h$()}`;T(`fetching ${D} (no upstream binary for ${_}) \u2026`);let{code:oe}=await ii("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",D]);oe!==0&&T(lt.warn(`could not fetch ${D} \u2014 falling back to a source build.`))}let L=await cy({home:h});L.length>0&&T(` ${lt.success("prebuilt")} ${L.join(", ")} \u2192 isolated-vm/prebuilds/${_}`)}let k=await ci(),A=k.filter(C=>!C.present).map(C=>C.name);if(A.includes("isolated-vm")){T(lt.warn(`no prebuilt isolated-vm for ${_} / Node ${process.versions.node} (${Ll()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:C}=await ii("npm",["rebuild","--prefix",h,"isolated-vm"]);C===0&&(k=await ci(),A=k.filter(L=>!L.present).map(L=>L.name))}A.length>0&&S(`npm succeeded but ${A.join(", ")} still will not load \u2014 no prebuilt binary for ${_} / Node ${process.versions.node} (${Ll()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),T(lt.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let qn=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return qn.command("deploy").description("Enqueue a server-side release deploy. UPLOADS the SDF project src/ from the checkout (the producer swap) when present; else a solution-only live-fetch deploy. An approved target requires --approved-by.").requiredOption("--target <mode>","Deploy posture: auto (apply now) | approved (needs a recorded approval).").option("--solution <id>","The solution id the release delivers (omit for an upload-only deploy).").option("--project <dir>","SDF project dir whose src/ is uploaded (default: cwd).").option("--git-repo <repo>","Git provenance LINK: source repo (default $GITHUB_REPOSITORY or `git remote get-url origin`).").option("--git-ref <ref>","Git provenance LINK: ref/branch/tag (default $GITHUB_REF).").option("--ref <committish>","Git provenance: the ref/branch/tag/sha the upload was built from; resolved to a commit sha via `git rev-parse` (default $GITHUB_SHA or HEAD).").option("--pr-url <url>","Git provenance LINK: the PR this deploy came from (default $PR_URL).").option("--approved-by <email>","Record the approval (REQUIRED for --target approved).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async p=>{let h=p.target==="approved"?"approved":p.target==="auto"?"auto":null;h||S(`--target must be 'auto' or 'approved' (got '${p.target}').`);let w=await Jj(Te(process.cwd(),p.project??".")),_=Object.keys(w).length;!p.solution&&_===0&&S("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let g=(p.ref?await cm(["rev-parse",p.ref])??p.ref:null)??process.env.GITHUB_SHA??await cm(["rev-parse","HEAD"]),k=p.gitRepo??process.env.GITHUB_REPOSITORY??await cm(["remote","get-url","origin"]),A=p.gitRef??process.env.GITHUB_REF??null,C=p.prUrl??process.env.PR_URL??null,{baseUrl:L,token:D}=await ne(p.baseUrl),oe=new ee({baseUrl:L,token:D}),U;try{U=await oe.releaseDeploy({solutionId:p.solution??null,target:h,approvedBy:p.approvedBy??null,files:_>0?w:null,gitRepo:k,gitRef:A,gitSha:g,prUrl:C})}catch(me){ke(me,"releases:write","release deploy"),me instanceof be&&me.status===404&&S("solution_not_found \u2014 no solution with that id."),S(`release deploy failed: ${me instanceof Error?me.message:String(me)}`)}T(`release ${U.releaseId} enqueued \u2192 taskId=${U.taskId} (target=${h}`+(_>0?`, uploaded ${_} bundle file(s)`:", live-fetch")+")."),p.follow&&await Ol(()=>oe.releaseStatus(U.releaseId),`release ${U.releaseId}`,p.intervalMs)}),qn.command("pull").argument("<id>","The release id").description("Write the SDF project a FAILED release built into <dir>: owned/ (yours, editable) and context/ (the rest of the bundle, read-only). Edit owned/, then `release push`.").requiredOption("--dir <path>","Directory to write the project into (created if absent).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,h)=>{let{baseUrl:w,token:_}=await ne(h.baseUrl),$=new ee({baseUrl:w,token:_}),g;try{g=await $.releaseFiles(p)}catch(C){C instanceof be&&C.status===404&&S(`release ${p} not found.`),C instanceof be&&C.status===409&&S(`no built project was retained for release ${p}. Files are kept for a FAILED attempt only \u2014 a shipped bundle is recoverable from the account.`),ke(C,"releases:write","pull a release"),S(`release pull failed: ${C instanceof Error?C.message:String(C)}`)}let k=Te(process.cwd(),h.dir),A=0;for(let[C,L]of[["owned",g.owned],["context",g.context]])for(let[D,oe]of Object.entries(L)){let U=Rt(k,C,D);await ye.mkdir(No(U),{recursive:!0}),await ye.writeFile(U,oe,"utf8"),A++}await ye.writeFile(Rt(k,".turbobase-release.json"),JSON.stringify({releaseId:g.releaseId,version:g.version,contentDigest:g.contentDigest},null,2),"utf8"),T(`pulled release ${g.releaseId} (${g.status}) \u2192 ${k}
1823
- ${Object.keys(g.owned).length} owned file(s), ${Object.keys(g.context).length} context file(s), ${A} total
1981
+ `);if(await T("PROPOSAL.md",g),h.screenshot){let S=m(h.screenshot);S&&await T("proposal-screenshot.png",S)}await T(At(".turbobase","proposal.json"),`${JSON.stringify({proposalId:h.proposalId},null,2)}
1982
+ `)}async function y(p){try{let h=await we.readFile(At(p,".turbobase","proposal.json"),"utf8"),_=JSON.parse(h);return typeof _.proposalId=="string"&&_.proposalId?_.proposalId:void 0}catch{return}}async function v(p,h,_,x,T,g){let S=new Q({baseUrl:p,token:h});try{return await S.appsPush(_,x,{note:T,proposalId:g})}catch(P){if(P instanceof be){let C=P.body;if(P.status===401&&k("push unauthorized (401) \u2014 re-run `turbobase auth login`."),P.status===403&&C?.error==="admin_required"&&k("push forbidden (403) \u2014 the PAT is not for an admin."),P.status===403&&le(P,"extensions:deploy","push app source"),P.status===404&&k(`no app "${_}" on this instance \u2014 create it with \`turbobase apps create ${_}\`.`),P.status===413&&(C?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&k("push rejected: the request body exceeded the instance limit."),k(`push rejected: ${C?.error??"too large"} (limit ${C?.limit??"?"}).`)),P.status===400){let L=C?.path?` in ${C.path}`:"",M=C?.reason?` (${C.reason})`:"";k(`push rejected: ${C?.error??"bad request"}${M}${L}.`)}}k(`push failed: ${P instanceof Error?P.message:String(P)}`)}}function E(p,h,_){return new Promise((x,T)=>{let g=bm("npm",p,{cwd:h,stdio:"inherit",..._?{env:{...process.env,..._}}:{}});g.on("error",T),g.on("exit",S=>S===0?x():T(new Error(`npm ${p.join(" ")} exited ${S??"?"}`)))})}async function R(p,h,_,x){let T=`${p.replace(/\/+$/,"")}${_}`,g;try{g=await fetch(T,{method:x.method,headers:{Authorization:`Bearer ${h}`,...x.body?{"content-type":"application/json"}:{}},...x.body?{body:JSON.stringify(x.body)}:{}})}catch(S){k(`request failed: ${S instanceof Error?S.message:String(S)}`)}if(g.status===401&&k("unauthorized (401) \u2014 re-run `turbobase auth login`."),g.status===403&&k("forbidden (403) \u2014 the PAT is not for an admin."),!g.ok){let S=await g.text().catch(()=>""),P=S.slice(0,300);try{let C=JSON.parse(S);P=C.message??C.error??P}catch{}k(`failed: HTTP ${g.status} ${P}`)}return await g.json().catch(()=>({}))}async function z(p,h,_,x,T){return await R(p,h,`/v1/apps/${encodeURIComponent(_)}/preview/${x}`,{method:"POST",body:T})}async function H(p,h,_){return{previews:(await R(p,h,`/v1/apps/${encodeURIComponent(_)}/previews`,{method:"GET"})).previews??[]}}async function Y(p,h,_,x,T,g,S,P){let C;try{C=await se(`zipping ${x}`,()=>Og(x))}catch(U){k(`could not zip ${x}: ${U instanceof Error?U.message:String(U)}`)}C.fileCount===0&&k(`${x} is empty \u2014 the build produced nothing.`);let L={Authorization:`Bearer ${h}`,"Content-Type":"application/zip"};T&&(L["x-app-entry"]=T),g&&(L["x-proposal-id"]=g),S&&(L["x-app-build-id"]=S.buildId,L["x-app-asset-base"]=S.assetBase),P&&(L["x-app-channel"]="preview",P.label&&(L["x-app-preview-label"]=encodeURIComponent(P.label)));let M=`${p.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(_)}/deploy`,ae;try{ae=await se(`deploying ${_} (${C.fileCount} file${C.fileCount===1?"":"s"})`,()=>fetch(M,{method:"POST",headers:L,body:new Uint8Array(C.buffer)}))}catch(U){k(`deploy request failed: ${U instanceof Error?U.message:String(U)}`)}if(ae.status===401&&k("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),ae.status===403&&k("deploy forbidden (403) \u2014 the PAT is not for an admin."),ae.status===404&&k(`no app "${_}" on ${p} \u2014 create it with \`turbobase apps create ${_}\`.`),!ae.ok){let U=await ae.text().catch(()=>""),he=U.slice(0,300);try{let me=JSON.parse(U);he=me.message??me.error??he}catch{}k(`deploy failed: HTTP ${ae.status} ${he}`)}return await ae.json().catch(()=>({}))}async function He(p,h){let _=Bg(p,{localDocsModifiedAt:await Qe(h)});_&&$(_.level==="warn"?w.yellow(_.message):w.dim(_.message))}async function Qe(p){if(!p)return null;let h=null;for(let _ of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let x=await we.stat(At(p,_));(h===null||x.mtimeMs>h)&&(h=x.mtimeMs)}catch{}return h===null?null:new Date(h)}c.command("pull").description("Write an app's generated source tree to disk (from the proposal that generated it).").argument("[app]","App slug or id. Omit when using --proposal (the app is derived from it).").argument("[dir]","Directory to write into (default ./<slug>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--force","Overwrite existing files.").option("--proposal <id>","Pull the app behind a widget proposal + its request context.").action(async(p,h,_)=>{let{baseUrl:x,token:T}=await ne(_.baseUrl);if(_.proposal){let C=new Q({baseUrl:x,token:T}),L;try{L=await se(`fetching proposal ${_.proposal}`,()=>C.appPullContext(_.proposal))}catch(me){le(me,"extensions:deploy","pull proposal"),me instanceof be&&me.status===404&&k(`no widget proposal "${_.proposal}" on ${x}.`),k(`could not fetch proposal ${_.proposal}: ${me instanceof Error?me.message:String(me)}`)}let M=await se(`pulling ${L.appSlug}`,()=>d(x,T,L.appSlug)),ae=h??p,U=Te(process.cwd(),ae??L.appSlug);await we.mkdir(U,{recursive:!0});let he=await b(U,M.files,!!_.force);await f(U,L,!!_.force),$(`pulled ${he} file${he===1?"":"s"} \u2192 ${U} (rev ${M.rev}), linked to proposal ${L.proposalId}.`),$(`next: cd ${Dc(process.cwd(),U)||"."} && turbobase apps deploy ${L.appSlug}`);return}p||k("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let g=await se(`pulling ${p}`,()=>d(x,T,p)),S=Te(process.cwd(),h??g.slug??p);await we.mkdir(S,{recursive:!0});let P=await b(S,g.files,!!_.force);$(`pulled ${P} file${P===1?"":"s"} \u2192 ${S} (rev ${g.rev}).`),$(`next: cd ${Dc(process.cwd(),S)||"."} && turbobase apps deploy ${g.slug}`)}),c.command("init").description("Scaffold a new app project locally, wired to your instance and to Claude Code.").argument("<app>","App slug \u2014 also the /a/<slug> mount path the build is pinned to.").argument("[dir]","Directory to scaffold into (default ./<app>).").option("--title <text>","Display title used in index.html and the starter component.").option("--base-url <url>","Instance to wire the project to (defaults to the active instance).").option("--no-claude","Skip the Claude Code wiring (CLAUDE.md, .mcp.json, .claude/).").option("--force","Overwrite existing files.").action(async(p,h,_)=>{let x=Te(process.cwd(),h??p),T=await Gt(_.baseUrl).catch(()=>null),{scaffoldAppFiles:g,starterApp:S}=await Promise.resolve().then(()=>(eb(),Qy)),P=_.title??p,C=g({slug:p,title:P,appTsx:S(P),instanceOrigin:T?.baseUrl});await we.mkdir(x,{recursive:!0});let L=await b(x,C,!!_.force);if($(`scaffolded ${L} file${L===1?"":"s"} \u2192 ${x}`),_.claude!==!1){let ae=Ll({baseUrl:T?.baseUrl,token:T?.token,appSlug:p}),U=0;for(let he of ae){let me=await I$(At(x,he.path),he);(me==="wrote"||me==="merged")&&(U+=1)}$(`wired Claude Code: ${U} file${U===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),T||V("not signed in \u2014 .mcp.json and the dev proxy carry placeholders. Run `turbobase auth login`, then `turbobase apps init` again (existing files are kept).")}let M=Dc(process.cwd(),x)||".";$(`next: cd ${M} && npm install && npm run dev`),$(` turbobase apps create ${p}`),$(` turbobase apps push ${p} .`),$(` turbobase apps deploy ${p} .`)}),c.command("list").description("List the hosted apps on your instance.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async p=>{let{baseUrl:h,token:_}=await ne(p.baseUrl),x=new Q({baseUrl:h,token:_}),T;try{T=await x.appsList()}catch(g){le(g,"extensions:deploy","list apps"),k(`list apps failed: ${g instanceof Error?g.message:String(g)}`)}if(p.json)return $(JSON.stringify(T,null,2));if(T.length===0)return $("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");$(Mr(T.map(g=>[g.slug,g.name,g.deployed?"yes":"no",g.sourceRev===null?"\u2014":`rev ${g.sourceRev}`,g.audience]),{head:["SLUG","NAME","LIVE","SOURCE","AUDIENCE"]}))}),c.command("push").description("Record the local source tree as the app's newest source revision (does NOT deploy).").argument("<app>","App slug or id.").argument("[dir]","Source directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--note <text>","Short note stored with the revision.").option("--proposal <id>","Widget proposal this rev works (defaults to .turbobase/proposal.json).").action(async(p,h,_)=>{let x=Te(process.cwd(),h??".");await we.stat(x).then(oe=>oe.isDirectory()).catch(()=>!1)||k(`${x} is not a directory.`);let{baseUrl:g,token:S}=await ne(_.baseUrl),P=_.proposal??await y(x),{files:C,skipped:L,secrets:M,unstorable:ae}=await vy(x),U=Object.keys(C).length;if(U===0&&k(`no source files found under ${x} (build output and node_modules are skipped).`),ae.length>0){for(let oe of ae)V(`${oe} contains a NUL byte (U+0000), which cannot be stored.`);k(`push aborted: ${ae.length} ${ae.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let oe of L)V(w.dim(`skipped binary file ${oe}`));for(let oe of M)V(w.dim(`skipped ${oe} (holds credentials \u2014 never pushed)`));let he=await se(`pushing ${U} file${U===1?"":"s"}`,()=>v(g,S,p,C,_.note,P));$(`pushed ${he.files} file${he.files===1?"":"s"} \u2192 ${he.slug} rev ${he.rev} (source only, nothing deployed).`);let me=await os(new Q({baseUrl:g,token:S}),he.slug);me&&me.entriesAdded>0&&$(`${me.entriesAdded} new finding(s) queued \u2014 run \`turbobase skills push\` / \`turbobase kb push\` to act on them.`),$(`next: turbobase apps deploy ${he.slug}`)}),o.command("plan").description("Diff the local bundle (turbobase/bundle.json) against a target env (no writes).").option("--from <env>","Source env the bundle was authored against (advisory).").option("--to <env>","Target env to diff against (sandbox|prod).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async p=>{let h=await hm(),{baseUrl:_,token:x}=await ne(p.baseUrl),T=new Q({baseUrl:_,token:x}),g;try{g=await se(`planning against ${p.to??_}`,()=>T.configPlan(h))}catch(S){k(`plan failed: ${S instanceof Error?S.message:String(S)}`)}PL(g,p.to??_)}),o.command("promote").description("Promote the bundle from one env to another behind a confirm-slug gate (fail-closed).").requiredOption("--from <env>","Source env (e.g. sandbox).").requiredOption("--to <env>","Target env (e.g. prod).").requiredOption("--confirm <slug>","Type the EXACT target instance slug to confirm (fail-closed).").option("--base-url <url>","Target instance base URL (defaults to the active instance).").action(async p=>{let h=await hm(),{baseUrl:_,token:x}=await ne(p.baseUrl),T=h.tenant??AL(_),g=Ly(p.confirm,T);g.ok||k(`promote refused (fail-closed): ${g.reason}`);let S=new Q({baseUrl:_,token:x});try{let P=await se(`promoting ${p.from} \u2192 ${p.to} (${T})`,()=>S.configApply(h));if(Ye()){let C=[`${w.bold(`${p.from} \u2192 ${p.to}`)} ${w.dim(T??"")}`,`${Lr.add(String(P.applied.add))} ${Lr.change(String(P.applied.change))} ${Lr.destroy(String(P.applied.destroy))}`];P.backfillsQueued.length&&C.push(w.dim(`${P.backfillsQueued.length} backfill(s) queued`)),$(Dr("Promoted",C))}else $(`promoted ${p.from} \u2192 ${p.to} (${T}): +${P.applied.add} ~${P.applied.change} -${P.applied.destroy}`+(P.backfillsQueued.length?` (${P.backfillsQueued.length} backfill(s) queued)`:""))}catch(P){P instanceof be&&P.status===403&&k("promote forbidden (403) \u2014 the stored PAT is not for an admin."),k(`promote failed: ${P instanceof Error?P.message:String(P)}`)}});let Rr=async(p,h)=>{let{baseUrl:_,token:x}=await ne(h.baseUrl),T=new Q({baseUrl:_,token:x}),g=h.limit?Number(h.limit):void 0;if(h.follow){try{await Zg(T,p,{follow:!0,limit:g,intervalMs:h.intervalMs?Number(h.intervalMs):void 0,sink:$})}catch(S){k(`logs --follow failed: ${S instanceof Error?S.message:String(S)}`)}return}try{let S=await T.logs(p,g);S.length===0&&$(`no logs for ${p}.`);for(let P of S)$(` [${P.level}] ${P.ts??""} ${P.message}`)}catch(S){k(`logs failed: ${S instanceof Error?S.message:String(S)}`)}};o.command("logs").argument("<id>","Extension id (default) or conduit id (with --follow)").description("Read an extension's logs; with --follow, stream a conduit's run ledger.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--limit <n>","Max log lines").option("--follow","Stream the conduit_event run ledger for the given conduit id.").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(Rr),o.command("lint").argument("<file>","The hook or conduit definition file to lint").description("Statically lint a hook/conduit for semantic foot-guns (offline).").option("--ci","Exit non-zero when any warning fires (else exit 0).").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").action(async(p,h)=>{let _=fm(h.reporter),x=Te(process.cwd(),p),T=await es(x),g=zg(T);_?$(Di(TL(p,g),_)):$(Ng(p,g,{warn:w.yellow,ok:w.green,dim:w.dim})),h.ci&&g.warnings.length>0&&process.exit(1)}),o.command("replay").argument("<file>","The conduit file to replay").description("Dry-run a conduit through dispatch\u2192transform\u2192apply (offline against a fixture).").option("--fixture <file>","JSON conduit-trigger fixture to replay against.").option("--against <target>","Replay against a running sandbox (online; deferred without a local DB).").option("--trace","Emit the per-stage trace (guards, atlas, apply-branch, bindings).").option("--reporter <fmt>","Emit machine-readable output: junit | json (one case per stage).").action(async(p,h)=>{let _=fm(h.reporter),x=await Tg(Te(process.cwd(),p));if(h.against){h.against!=="sandbox"&&k(`unknown --against target '${h.against}' (only 'sandbox' is supported).`);try{await $g(Pl(x))}catch(S){k(S instanceof Error?S.message:String(S))}return}h.fixture||k("replay needs a --fixture <file> (offline) or --against sandbox (online).");let T;try{T=await Sg(Te(process.cwd(),h.fixture))}catch(S){k(`could not read fixture ${h.fixture}: ${S instanceof Error?S.message:String(S)}`)}let g=await kg(x,T,h.fixture);if(_){let S=EL(g);$(Di(S,_)),S.cases.some(P=>P.status==="failed")&&process.exit(1);return}$(Eg(g,!!h.trace)),g.error&&process.exit(1)}),o.command("binding").description("List conduit source bindings (--status divergent) or re-enqueue one (--retry <id>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <status>","Filter by write_status (ok|pending|blocked|divergent|muted).").option("--retry <id>","Re-enqueue the fan-out write for this binding id (admin-only).").option("--limit <n>","Max rows listed").action(async p=>{let{baseUrl:h,token:_}=await ne(p.baseUrl),x=new Q({baseUrl:h,token:_});try{await qg(x,{status:p.status,retry:p.retry,limit:p.limit?Number(p.limit):void 0,sink:$})}catch(T){T instanceof be&&T.status===403&&k("forbidden (403) \u2014 binding --retry requires an admin PAT."),T instanceof be&&T.status===409&&k("binding is not retryable (only divergent/blocked bindings can be retried)."),k(`ext binding failed: ${T instanceof Error?T.message:String(T)}`)}}),o.command("install").argument("<spec>","Extension name, optionally name@version").description("Install an extension from the marketplace into your instance's extension store.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--connection <id>",'Bind this connection id (required when the extension declares a { type:"connection" } input).').action(async(p,h)=>{let _=p.lastIndexOf("@"),x=_>0?p.slice(0,_):p,T=_>0?p.slice(_+1):void 0,g=kl();g||k(`marketplace not configured \u2014 set ${Yn} and ${zi}.
1983
+ Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let S=$l(g.registryUrl);S&&k(S);let{baseUrl:P,token:C}=await ne(h.baseUrl),L=new Yo(g),M;try{M=await se(`fetching ${p}`,()=>L.fetchBundle(x,T))}catch(oe){k(`marketplace fetch failed for ${p}: ${oe instanceof Error?oe.message:String(oe)}`)}let ae=Ei(M.manifest),U=null;if(ae.length>0){if(!h.connection){let oe=ae.map(It=>It.source_system).join(", ");k(`${M.name}@${M.version} declares a connection input (source: ${oe}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}U=h.connection}let he=RL(M.bundle,M.name,M.kind),me=new Q({baseUrl:P,token:C});try{let oe=await se(`installing ${M.name}@${M.version}`,()=>me.deploy({...he,provenance:"marketplace",...U?{connectionId:U}:{}}));$(`installed ${M.name}@${M.version} \u2192 ${oe.id} (status=${oe.status}, ${oe.outcome})`+(U?` bound to connection ${U}.`:"."))}catch(oe){oe instanceof be&&oe.status===403&&k("install forbidden (403) \u2014 the stored PAT is not for an admin."),k(`install failed: ${oe instanceof Error?oe.message:String(oe)}`)}}),o.command("publish").description("Publish an authored extension to the public marketplace (publisher allowlist required).").argument("<file>","The extension file to publish (defineHook/defineConduit source).").requiredOption("--name <name>","Marketplace package name (lowercase, e.g. acme-recipes).").requiredOption("--pkg-version <version>","Semver-ish package version (e.g. 1.0.0).").option("--manifest <file>","Path to a JSON manifest (declared inputs[], capabilities).").action(async(p,h)=>{let _=kl();_||k(`marketplace not configured \u2014 set ${Yn} and ${zi}.
1984
+ Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let x=$l(_.registryUrl);x&&k(x);let T=Te(process.cwd(),p),g=await es(T),S=/\bdefineConduit\s*[<(]/.test(g)?"conduit":"hook",P={};if(h.manifest){let M=Te(process.cwd(),h.manifest),ae;try{ae=await we.readFile(M,"utf8")}catch{k(`manifest not found at ${h.manifest}.`)}let U;try{U=JSON.parse(ae)}catch{k(`manifest is not valid JSON: ${h.manifest}.`)}(typeof U!="object"||U===null||Array.isArray(U))&&k("manifest must be a JSON object."),P=U}try{cl(P,g)}catch(M){M instanceof zr&&k(M.message),k(`manifest validation failed: ${M instanceof Error?M.message:String(M)}`)}let C=new Yo(_);try{await se(`publishing ${h.name}@${h.pkgVersion}`,()=>C.publish({name:h.name,version:h.pkgVersion,kind:S,bundle:g,manifest:P}))}catch(M){M instanceof be&&M.status===403&&k("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),M instanceof be&&M.status===409&&k(`version already published \u2014 ${h.name}@${h.pkgVersion} exists. Bump the version.`),k(`publish failed: ${M instanceof Error?M.message:String(M)}`)}let L=Ei(P);$(`published ${h.name}@${h.pkgVersion} (kind=${S}) to the marketplace.`),L.length>0&&$(` declares ${L.length} connection input(s): ${L.map(M=>M.source_system).join(", ")} \u2014 bound at install.`)}),n.command("init").description("Scaffold a Claude-Code extension project in the current dir.").option("--base-url <url>","Instance to wire .mcp.json to (defaults to the active instance).").action(async p=>{let h=await Gt(p.baseUrl).catch(()=>null),_=Ll({baseUrl:h?.baseUrl,token:h?.token}),x=0,T=0,g=0;for(let S of _){let P=Te(process.cwd(),S.path),C=await I$(P,S);C==="wrote"?(x+=1,$(` wrote ${S.path}`)):C==="merged"?(g+=1,$(` merged ${S.path} (added the .mcp.json rule)`)):(T+=1,$(` skipped ${S.path} (exists)`))}$(`
1985
+ project init: ${x} written, ${g} merged, ${T} skipped.`)}),n.command("ci").description(`Write the reusable release-deploy GitHub Action to ${jl} (non-destructive).`).action(async()=>{let p=Vg(),h=0,_=0;for(let x of p){let T=Te(process.cwd(),x.path);await Do(T,x.content,x.executable)==="wrote"?(h+=1,$(` wrote ${x.path}`)):(_+=1,$(` skipped ${x.path} (exists)`))}$(`
1986
+ project ci: ${h} written, ${_} skipped.`),h>0&&($(`
1987
+ Next: mint a releases:write PAT in your Turbobase app (Settings \u203A Access tokens),`),$("store it as the GitHub Actions secret TURBOBASE_RELEASE_PAT, and set the repo"),$("variable TURBOBASE_BASE_URL \u2014 the workflow header has the step-by-step."))}),n.command("samples").description("Generate samples/<recordType>.json fixtures from the live instance catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Output directory for the fixtures","samples").option("--event <event>","Lifecycle event to stamp on each fixture","before_save").option("--force","Overwrite existing fixture files (default: skip files that exist).").action(async p=>{let{baseUrl:h,token:_}=await ne(p.baseUrl),x=new Q({baseUrl:h,token:_}),T;try{T=await x.catalogRecords()}catch(L){L instanceof be&&(L.status===401||L.status===403)&&k("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),k(`catalog fetch failed: ${L instanceof Error?L.message:String(L)}`)}if(T.length===0){$("no records in the instance catalog \u2014 nothing to generate.");return}let g=Te(process.cwd(),p.out),S=Pg(T,{event:p.event}),P=0,C=0;for(let{recordType:L,fixture:M}of S){let ae=At(g,`${L}.json`),U=`${JSON.stringify(M,null,2)}
1988
+ `;p.force?(await we.mkdir(Lo(ae),{recursive:!0}),await we.writeFile(ae,U,{mode:420}),P+=1,$(` wrote ${p.out}/${L}.json`)):await Do(ae,U)==="wrote"?(P+=1,$(` wrote ${p.out}/${L}.json`)):(C+=1,$(` skipped ${p.out}/${L}.json (exists \u2014 use --force to overwrite)`))}$(`
1989
+ samples init: ${P} written, ${C} skipped.`)});let nr=e.command("guardrails").description("Control PG\u2192source write-back with policy rules (staged write rollout)."),nn=p=>[p.name??w.dim(p.id.slice(0,8)),p.status==="active"?w.green("active"):p.status==="proposed"?w.yellow("proposed"):w.dim("inactive"),p.decision==="deny"?w.red(p.decision):p.decision==="require_confirm"?w.yellow(p.decision):w.green(p.decision),String(p.priority),p.source,p.record??p.op,p.actor??w.dim("any"),p.when||w.dim("(always)"),p.reason??""],Mo=["NAME","STATUS","DECISION","PRIO","SOURCE","RECORD","ACTOR","WHEN","REASON"];nr.command("list").description("List every write guardrail on your instance, in evaluation order.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async p=>{let{baseUrl:h,token:_}=await ne(p.baseUrl),x=new Q({baseUrl:h,token:_}),T;try{T=await x.guardrailsList()}catch(g){le(g,"extensions:deploy","list guardrails"),k(`list guardrails failed: ${g instanceof Error?g.message:String(g)}`)}if(p.json)return $(JSON.stringify(T,null,2));if(T.length===0)return $(`no write guardrails \u2014 every record the admin entitlement allows is writable.
1990
+ `+w.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));$(Mr(T.map(nn),{head:Mo})),$(w.dim(" first match wins; lower PRIO is evaluated first."))}),nr.command("create <name>").description("Create a rule gating PG\u2192source writes that match it.").option("--source <system>","Adapter id to scope to, or '*' for every source.","*").option("--record <type>","Record type to scope to, or '*' for every record.","*").option("--op <glob>","Raw op glob, when gating something other than a record write.").option("--target <glob>","Row address glob, e.g. 'salesOrder.12345'.").option("--actor <glob>","Only match this caller, e.g. 'agent:*' to gate AI writes but not human ones.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.","deny").option("--priority <n>","Lower is evaluated first (default 100).",p=>Number(p)).option("--when <expr>","Row predicate, e.g. 'total gt 10000'. Omit to match every row.").option("--reason <text>","Why this rule exists \u2014 shown to a blocked writer and in `list`.").option("--disabled","Create the rule parked, so it takes effect only when activated.").option("--confirm-freeze-all","Required for an unconditional deny across '*'/'*'.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,h)=>{let{baseUrl:_,token:x}=await ne(h.baseUrl),T=new Q({baseUrl:_,token:x}),g;try{g=await T.guardrailCreate({name:p,source:h.source,record:h.record,decision:h.decision,...h.op?{op:h.op}:{},...h.target?{target:h.target}:{},...h.actor?{actor:h.actor}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when?{when:h.when}:{},...h.reason?{reason:h.reason}:{},...h.disabled?{enabled:!1}:{},...h.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(S){le(S,"extensions:deploy","create a guardrail"),k(`create guardrail failed: ${S instanceof Error?S.message:String(S)}`)}$(`${w.green("\u2713")} guardrail ${w.bold(g.name??g.id)} created${g.status==="active"?"":w.dim(` (${g.status} \u2014 activate it to take effect)`)}`),$(w.dim(` ${g.decision} ${g.source}/${g.record??g.op}${g.actor?` actor=${g.actor}`:""}${g.when?` where ${g.when}`:""} @prio ${g.priority}`)),$(w.dim(` verify with: turbobase guardrails test --source ${g.source==="*"?"<source>":g.source} --record <record>`))}),nr.command("edit <name>").description("Change a rule \u2014 its decision, priority, predicate or reason.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.").option("--priority <n>","Lower is evaluated first.",p=>Number(p)).option("--when <expr>","New row predicate. Pass '' to match every row.").option("--reason <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,h)=>{h.decision===void 0&&h.priority===void 0&&h.when===void 0&&h.reason===void 0&&k("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:_,token:x}=await ne(h.baseUrl),T=new Q({baseUrl:_,token:x}),g;try{g=await T.guardrailUpdate(p,{...h.decision!==void 0?{decision:h.decision}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when!==void 0?{when:h.when}:{},...h.reason!==void 0?{reason:h.reason}:{}})}catch(S){le(S,"extensions:deploy","edit a guardrail"),k(`edit guardrail failed: ${S instanceof Error?S.message:String(S)}`)}$(`${w.green("\u2713")} guardrail ${w.bold(g.name??g.id)} updated`),$(w.dim(` ${g.decision} ${g.source}/${g.record??g.op}${g.when?` where ${g.when}`:""} @prio ${g.priority}`))});for(let[p,h,_]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])nr.command(`${p} <name>`).description(h==="active"?"Arm a parked or proposed rule.":"Park a rule without deleting it \u2014 the reversible move mid-rollout.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(x,T)=>{let{baseUrl:g,token:S}=await ne(T.baseUrl),P=new Q({baseUrl:g,token:S});try{await P.guardrailUpdate(x,{status:h})}catch(C){le(C,"extensions:deploy",`${p} a guardrail`),k(`${p} guardrail failed: ${C instanceof Error?C.message:String(C)}`)}$(`${w.green("\u2713")} guardrail ${w.bold(x)} ${_}`),h==="inactive"&&$(w.dim(" writes it was gating now fall through to the other rules."))});nr.command("delete <name>").description("Remove a rule. Prefer `deactivate` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,h)=>{let{baseUrl:_,token:x}=await ne(h.baseUrl),T=new Q({baseUrl:_,token:x});try{await T.guardrailDelete(p)}catch(g){le(g,"extensions:deploy","delete a guardrail"),k(`delete guardrail failed: ${g instanceof Error?g.message:String(g)}`)}$(`${w.green("\u2713")} guardrail ${w.bold(p)} deleted`)}),nr.command("test").description("What happens to this write? Runs the real evaluator; writes nothing.").requiredOption("--source <system>","Adapter id the write targets.").requiredOption("--record <type>","Record type the write targets.").option("--actor <actor>","Caller to simulate, e.g. 'agent:ai' or 'user:<id>'.").option("--external-id <id>","Source-side row id, for target-scoped rules.").option("--fields <json>","A candidate row as JSON, so `when` predicates can be decided.").option("--phase <phase>","boundary | cdc | worker | adapter. Defaults to worker (the last gate).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON.").action(async p=>{let h;if(p.fields)try{h=JSON.parse(p.fields)}catch(P){k(`--fields must be valid JSON: ${P instanceof Error?P.message:String(P)}`)}let{baseUrl:_,token:x}=await ne(p.baseUrl),T=new Q({baseUrl:_,token:x}),g;try{g=await T.guardrailTest({source:p.source,record:p.record,...p.actor?{actor:p.actor}:{},...p.externalId?{externalId:p.externalId}:{},...h?{fields:h}:{},...p.phase?{phase:p.phase}:{}})}catch(P){le(P,"extensions:deploy","test guardrails"),k(`guardrails test failed: ${P instanceof Error?P.message:String(P)}`)}if(p.json)return $(JSON.stringify(g,null,2));let S=`${p.source}/${p.record}`;g.degraded?($(`${w.red("\u2717")} ${S} \u2014 guardrail policy is UNREADABLE; writes fail closed`),$(w.dim(` ${g.reason}`))):g.allowed?$(`${w.green("\u2713")} ${S} \u2014 ${g.decision}`+(g.blockedBy?w.dim(` (rule ${g.blockedBy})`):w.dim(" (no rule matched)"))):($(`${w.red("\u2717")} ${S} \u2014 ${g.decision} by ${w.bold(g.blockedBy??"?")} at the ${g.phase} gate`),g.message&&$(w.dim(` ${g.message}`))),g.decision==="require_confirm"&&$(w.yellow(" this write is HELD for operator approval, not refused.")),g.allowed||(process.exitCode=1)});let Pr=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),Un=(p,h={})=>{let _=`${w.bold(p.table)} ${w.dim(p.displayName)}`;$(p.exists===!1?`${_} ${w.dim("(new)")}`:_);for(let x of p.fields){let T=[x.required?"required":null].filter(Boolean).join(", "),g=h.showClaimants&&x.claimedBy?.length?` ${w.dim(`\u2190 ${x.claimedBy.join(", ")}`)}`:"";$(` ${x.column.padEnd(28)} ${x.type}${T?` (${T})`:""}${g}`)}h.showClaimants&&p.claimants.length>1&&$(w.dim(` claimed by ${p.claimants.join(", ")}`))};function Uo(p){if(p instanceof be&&p.status===409){let h=p.body;h?.error==="table_conflict"&&h.message&&(V(h.message),process.exit(1))}k(`tables: ${p instanceof Error?p.message:String(p)}`)}let _m=async p=>{let h=At(Te(process.cwd(),p),"public","turbobase.json"),_=await we.readFile(h,"utf8").catch(()=>null);if(_===null)return null;let x;try{x=JSON.parse(_)}catch(g){k(`${h} is not valid JSON: ${g instanceof Error?g.message:String(g)}`)}let T=x.tables;return T===void 0?{tables:[],manifestPath:h}:(Array.isArray(T)||k(`${h}: "tables" must be an array.`),{tables:T,manifestPath:h})};Pr.command("list").description("List the custom tables on your instance and who claims each one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async p=>{let{baseUrl:h,token:_}=await ne(p.baseUrl),x=new Q({baseUrl:h,token:_}),T;try{T=await x.tablesList()}catch(g){le(g,"extensions:deploy","list tables"),k(`list tables failed: ${g instanceof Error?g.message:String(g)}`)}if(p.json)return $(JSON.stringify(T,null,2));if(T.length===0)return $("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");$(Mr(T.map(g=>[g.table,g.displayName,String(g.fields.length),g.status,g.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),Pr.command("plan").description("Preview what this project's declared tables would do. Writes nothing; exits 1 on a conflict.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: the app slug in .turbobase, else cli).").action(async(p,h)=>{let _=await _m(p??".");if(_||k(`no public/turbobase.json under ${Te(process.cwd(),p??".")}.`),_.tables.length===0)return $(`${_.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:x,token:T}=await ne(h.baseUrl),g=new Q({baseUrl:x,token:T}),S;try{S=await se("planning tables",()=>g.tablesPlan({claimedBy:h.as,tables:_.tables}))}catch(P){le(P,"extensions:deploy","plan tables"),Uo(P)}$(`claiming as ${w.bold(S.claimedBy)}`);for(let P of S.tables)Un(P,{showClaimants:!0});$(""),$(w.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),Pr.command("apply").description("Apply this project's declared tables to the instance.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: cli).").action(async(p,h)=>{let _=await _m(p??".");if(_||k(`no public/turbobase.json under ${Te(process.cwd(),p??".")}.`),_.tables.length===0)return $(`${_.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:x,token:T}=await ne(h.baseUrl),g=new Q({baseUrl:x,token:T}),S;try{S=await se("applying tables",()=>g.tablesApply({claimedBy:h.as,tables:_.tables}))}catch(P){le(P,"extensions:deploy","apply tables"),Uo(P)}for(let P of S.tables)Un(P,{showClaimants:!0});$(`applied ${S.tables.length} table${S.tables.length===1?"":"s"} as ${S.claimedBy}.`)}),Pr.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(p,h)=>[...h??[],p],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,h)=>{let _=h.field.map(P=>{let[C,L,M]=P.split(":");return(!C||!L)&&k(`--field "${P}" must be name:type[:required] (e.g. title:text:required).`),M!==void 0&&M!=="required"&&k(`--field "${P}": the third part may only be "required".`),{name:C,type:L,...M==="required"?{required:!0}:{}}}),{baseUrl:x,token:T}=await ne(h.baseUrl),g=new Q({baseUrl:x,token:T}),S;try{S=await se(`creating cr_${p}`,()=>g.tablesApply({tables:[{slug:p,displayName:h.name??p,fields:_,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(P){le(P,"extensions:deploy","create a table"),Uo(P)}for(let P of S.tables)Un(P);$(""),$(w.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),Pr.command("drop").description("Drop a table and everything in it. Irreversible.").argument("<slug>","Table slug (without the cr_ prefix).").requiredOption("--confirm <slug>","Type the EXACT slug to confirm (fail-closed).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,h)=>{h.confirm!==p&&k(`drop refused: --confirm "${h.confirm}" does not match "${p}".`);let{baseUrl:_,token:x}=await ne(h.baseUrl),T=new Q({baseUrl:_,token:x}),g;try{g=await se(`dropping cr_${p}`,()=>T.tablesDrop(p,h.confirm))}catch(S){le(S,"extensions:deploy","drop a table"),k(`drop failed: ${S instanceof Error?S.message:String(S)}`)}if(!g.removed)return $(`no table named "${p}" on this instance \u2014 nothing dropped.`);$(`dropped ${g.table} and every row in it.`)});let Mc=e.command("sandbox").description("Ephemeral local authoring sandboxes.");Mc.command("create").description("Stand up a fresh local sandbox seeded with a sampled+redacted slice of an instance.").requiredOption("--from <instance>","Source instance to clone the data slice from.").option("--ttl <duration>","Time-to-live before reaping (e.g. 72h, 30m, 7d).","72h").option("--sample <pct>","Percent of each table to copy (e.g. 2%).","2%").option("--base-url <url>","Local base URL the sandbox is reachable at.").action(async p=>{process.env.TURBOBASE_SANDBOX="1";let h=mm(),_;try{_=await Oy(h,{fromTenant:p.from,ttl:p.ttl,sample:p.sample,baseUrl:p.baseUrl})}catch(x){x instanceof is&&k(x.message),k(`sandbox create failed: ${x instanceof Error?x.message:String(x)}`)}$(`sandbox ${_.name} ready.`),$(` source: ${_.fromTenant} (sampled ${Math.round(_.sampleFraction*100)}%, redacted)`),$(` url: ${_.url}`),$(` expires: ${_.expiresAt}`)}),Mc.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async p=>{let h=mm();await Yl(h).catch(()=>[]);let _;try{_=await Cy(h,p)}catch(x){k(`sandbox destroy failed: ${x instanceof Error?x.message:String(x)}`)}_||k(`no sandbox named '${p}'.`),$(`destroyed sandbox ${_.name} (dropped ${_.database}).`)}),Mc.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let p=mm(),h=await Yl(p).catch(()=>[]),_=await Bi(),{active:x}=Jl(_);if(x.length===0)$("no active sandboxes.");else{for(let T of x)$(` ${T.name} from=${T.fromTenant} expires=${T.expiresAt} ${T.url}`);$(`
1991
+ ${x.length} active sandbox(es).`)}h.length>0&&$(`(reaped ${h.length} expired sandbox(es).)`)}),o.command("export").description("Snapshot the live instance into turbobase/bundle.json.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",Vi).action(async p=>{let{baseUrl:h,token:_}=await ne(p.baseUrl),x=new Q({baseUrl:h,token:_}),T;try{T=await se("exporting instance config",()=>x.configExport())}catch(P){P instanceof be&&(P.status===401||P.status===403)&&k("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),k(`ext export failed: ${P instanceof Error?P.message:String(P)}`)}let g=typeof T.serialized=="string"?T.serialized:`${JSON.stringify(T.manifest??T,null,2)}
1992
+ `,S=Te(process.cwd(),p.out,cs);await we.mkdir(Lo(S),{recursive:!0}),await we.writeFile(S,g,"utf8"),$(`wrote ${p.out}/${cs} (${g.split(`
1993
+ `).length} lines).`)});let vm=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),C$=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],xm=()=>process.env.TURBOBASE_HOME?.trim()||At(bL(),".turbobase"),z$=()=>"1.1.18",hi=async()=>Promise.all(C$.map(async p=>{try{return await import(p.name),{...p,present:!0}}catch{return{...p,present:!1}}}));vm.command("status").description("Report which optional native packages are installed.").action(async()=>{let p=await hi();for(let h of p)$(`${h.present?ut.success("installed"):ut.warn("missing")} ${w.bold(h.name)} \u2014 ${h.needs}`);p.some(h=>!h.present)&&$(`
1994
+ run \`${rs} ext extras install\` to fetch them into ${xm()}.`)}),vm.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let p=await hi();if(p.every(C=>C.present)){$(ut.success("extras already installed \u2014 nothing to do."));return}let h=xm();await we.mkdir(h,{recursive:!0});let _=p.filter(C=>!C.present).map(C=>C.name),x=Bl(process.platform,process.arch),T=async(C,L)=>{let{code:M,stderr:ae}=await fi("npm",["install","--prefix",h,"--no-audit","--no-fund",...C]);M!==0&&k(`extras install failed while installing ${L} (npm exited ${M}).
1995
+ ${ae.trim()}
1996
+ These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},g=_.filter(C=>C!=="isolated-vm");if(g.length>0){let C=g.map(L=>`${L}@${ql[L]??"latest"}`);$(`installing ${C.join(", ")} \u2192 ${h}/node_modules \u2026`),await T(C,g.join(", "))}if(_.includes("isolated-vm")){let C=`isolated-vm@${ql["isolated-vm"]}`;if($(`installing ${C} \u2192 ${h}/node_modules \u2026`),await T(["--ignore-scripts",C],"isolated-vm"),Sy.includes(x)){let M=`${Fl}@${z$()}`;$(`fetching ${M} (no upstream binary for ${x}) \u2026`);let{code:ae}=await fi("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",M]);ae!==0&&$(ut.warn(`could not fetch ${M} \u2014 falling back to a source build.`))}let L=await Ty({home:h});L.length>0&&$(` ${ut.success("prebuilt")} ${L.join(", ")} \u2192 isolated-vm/prebuilds/${x}`)}let S=await hi(),P=S.filter(C=>!C.present).map(C=>C.name);if(P.includes("isolated-vm")){$(ut.warn(`no prebuilt isolated-vm for ${x} / Node ${process.versions.node} (${Vl()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:C}=await fi("npm",["rebuild","--prefix",h,"isolated-vm"]);C===0&&(S=await hi(),P=S.filter(L=>!L.present).map(L=>L.name))}P.length>0&&k(`npm succeeded but ${P.join(", ")} still will not load \u2014 no prebuilt binary for ${x} / Node ${process.versions.node} (${Vl()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),$(ut.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let Zn=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return Zn.command("deploy").description("Enqueue a server-side release deploy. UPLOADS the SDF project src/ from the checkout (the producer swap) when present; else a solution-only live-fetch deploy. An approved target requires --approved-by.").requiredOption("--target <mode>","Deploy posture: auto (apply now) | approved (needs a recorded approval).").option("--solution <id>","The solution id the release delivers (omit for an upload-only deploy).").option("--project <dir>","SDF project dir whose src/ is uploaded (default: cwd).").option("--git-repo <repo>","Git provenance LINK: source repo (default $GITHUB_REPOSITORY or `git remote get-url origin`).").option("--git-ref <ref>","Git provenance LINK: ref/branch/tag (default $GITHUB_REF).").option("--ref <committish>","Git provenance: the ref/branch/tag/sha the upload was built from; resolved to a commit sha via `git rev-parse` (default $GITHUB_SHA or HEAD).").option("--pr-url <url>","Git provenance LINK: the PR this deploy came from (default $PR_URL).").option("--approved-by <email>","Record the approval (REQUIRED for --target approved).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async p=>{let h=p.target==="approved"?"approved":p.target==="auto"?"auto":null;h||k(`--target must be 'auto' or 'approved' (got '${p.target}').`);let _=await IL(Te(process.cwd(),p.project??".")),x=Object.keys(_).length;!p.solution&&x===0&&k("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let g=(p.ref?await gm(["rev-parse",p.ref])??p.ref:null)??process.env.GITHUB_SHA??await gm(["rev-parse","HEAD"]),S=p.gitRepo??process.env.GITHUB_REPOSITORY??await gm(["remote","get-url","origin"]),P=p.gitRef??process.env.GITHUB_REF??null,C=p.prUrl??process.env.PR_URL??null,{baseUrl:L,token:M}=await ne(p.baseUrl),ae=new Q({baseUrl:L,token:M}),U;try{U=await ae.releaseDeploy({solutionId:p.solution??null,target:h,approvedBy:p.approvedBy??null,files:x>0?_:null,gitRepo:S,gitRef:P,gitSha:g,prUrl:C})}catch(he){le(he,"releases:write","release deploy"),he instanceof be&&he.status===404&&k("solution_not_found \u2014 no solution with that id."),k(`release deploy failed: ${he instanceof Error?he.message:String(he)}`)}$(`release ${U.releaseId} enqueued \u2192 taskId=${U.taskId} (target=${h}`+(x>0?`, uploaded ${x} bundle file(s)`:", live-fetch")+")."),p.follow&&await Ml(()=>ae.releaseStatus(U.releaseId),`release ${U.releaseId}`,p.intervalMs)}),Zn.command("pull").argument("<id>","The release id").description("Write the SDF project a FAILED release built into <dir>: owned/ (yours, editable) and context/ (the rest of the bundle, read-only). Edit owned/, then `release push`.").requiredOption("--dir <path>","Directory to write the project into (created if absent).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,h)=>{let{baseUrl:_,token:x}=await ne(h.baseUrl),T=new Q({baseUrl:_,token:x}),g;try{g=await T.releaseFiles(p)}catch(C){C instanceof be&&C.status===404&&k(`release ${p} not found.`),C instanceof be&&C.status===409&&k(`no built project was retained for release ${p}. Files are kept for a FAILED attempt only \u2014 a shipped bundle is recoverable from the account.`),le(C,"releases:write","pull a release"),k(`release pull failed: ${C instanceof Error?C.message:String(C)}`)}let S=Te(process.cwd(),h.dir),P=0;for(let[C,L]of[["owned",g.owned],["context",g.context]])for(let[M,ae]of Object.entries(L)){let U=At(S,C,M);await we.mkdir(Lo(U),{recursive:!0}),await we.writeFile(U,ae,"utf8"),P++}await we.writeFile(At(S,".turbobase-release.json"),JSON.stringify({releaseId:g.releaseId,version:g.version,contentDigest:g.contentDigest},null,2),"utf8"),$(`pulled release ${g.releaseId} (${g.status}) \u2192 ${S}
1997
+ ${Object.keys(g.owned).length} owned file(s), ${Object.keys(g.context).length} context file(s), ${P} total
1824
1998
  `+(g.logTail?`
1825
1999
  the failure these bytes produced:
1826
2000
  ${g.logTail.trim()}
1827
2001
  `:"")+`
1828
2002
  edit the files under owned/, then:
1829
- turbobase release push ${g.releaseId} --dir ${h.dir}`)}),qn.command("push").argument("<id>","The release id the project was pulled from").description("Ship the edited project as a NEW release delivering the same solution. Refuses if a context/ file changed \u2014 those belong to other solutions.").requiredOption("--dir <path>","The directory `release pull` wrote.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--target <target>","'auto' (default) or 'approved'.","auto").option("--approved-by <who>","Required for an approved target (fails closed without it).").action(async(p,h)=>{let{baseUrl:w,token:_}=await ne(h.baseUrl),$=new ee({baseUrl:w,token:_}),g=Te(process.cwd(),h.dir),k;try{k=await $.releaseFiles(p)}catch(U){U instanceof be&&U.status===404&&S(`release ${p} not found.`),ke(U,"releases:write","push a release"),S(`release push failed: ${U instanceof Error?U.message:String(U)}`)}let A=async(U,me)=>{try{return await ye.readFile(Rt(g,U,me),"utf8")}catch{return null}},C=[];for(let[U,me]of Object.entries(k.context)){let se=await A("context",U);se!==null&&se!==me&&C.push(U)}C.length>0&&S(`refusing to push \u2014 these context/ files were modified, and they belong to other solutions in the same bundle:
2003
+ turbobase release push ${g.releaseId} --dir ${h.dir}`)}),Zn.command("push").argument("<id>","The release id the project was pulled from").description("Ship the edited project as a NEW release delivering the same solution. Refuses if a context/ file changed \u2014 those belong to other solutions.").requiredOption("--dir <path>","The directory `release pull` wrote.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--target <target>","'auto' (default) or 'approved'.","auto").option("--approved-by <who>","Required for an approved target (fails closed without it).").action(async(p,h)=>{let{baseUrl:_,token:x}=await ne(h.baseUrl),T=new Q({baseUrl:_,token:x}),g=Te(process.cwd(),h.dir),S;try{S=await T.releaseFiles(p)}catch(U){U instanceof be&&U.status===404&&k(`release ${p} not found.`),le(U,"releases:write","push a release"),k(`release push failed: ${U instanceof Error?U.message:String(U)}`)}let P=async(U,he)=>{try{return await we.readFile(At(g,U,he),"utf8")}catch{return null}},C=[];for(let[U,he]of Object.entries(S.context)){let me=await P("context",U);me!==null&&me!==he&&C.push(U)}C.length>0&&k(`refusing to push \u2014 these context/ files were modified, and they belong to other solutions in the same bundle:
1830
2004
  `+C.map(U=>` context/${U}`).join(`
1831
- `)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let L={...k.context},D=0;for(let[U,me]of Object.entries(k.owned)){let se=await A("owned",U);L[U]=se??me,se!==null&&se!==me&&D++}D===0&&T("nothing changed under owned/ \u2014 pushing the same bytes the release already built.");let oe=h.target==="approved"?"approved":"auto";try{let U=await $.releasePush(p,{files:L,target:oe,...h.approvedBy?{approvedBy:h.approvedBy}:{}});T(`pushed ${Object.keys(L).length} file(s) (${D} edited) \u2192 release ${U.releaseId} (task ${U.taskId}).
2005
+ `)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let L={...S.context},M=0;for(let[U,he]of Object.entries(S.owned)){let me=await P("owned",U);L[U]=me??he,me!==null&&me!==he&&M++}M===0&&$("nothing changed under owned/ \u2014 pushing the same bytes the release already built.");let ae=h.target==="approved"?"approved":"auto";try{let U=await T.releasePush(p,{files:L,target:ae,...h.approvedBy?{approvedBy:h.approvedBy}:{}});$(`pushed ${Object.keys(L).length} file(s) (${M} edited) \u2192 release ${U.releaseId} (task ${U.taskId}).
1832
2006
  follow it with:
1833
- turbobase release status ${U.releaseId} --follow`)}catch(U){U instanceof be&&U.status===403&&S("an approved target needs --approved-by (the deploy gate fails closed)."),U instanceof be&&U.status===409&&S("that solution already has an active release \u2014 roll it back or wait for it."),ke(U,"releases:write","push a release"),S(`release push failed: ${U instanceof Error?U.message:String(U)}`)}}),qn.command("status").argument("<id>","The release id").description("Show a release deploy job's status; with --follow, poll to completion.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async(p,h)=>{let{baseUrl:w,token:_}=await ne(h.baseUrl),$=new ee({baseUrl:w,token:_});if(h.follow){await Ol(()=>$.releaseStatus(p),`release ${p}`,h.intervalMs);return}let g;try{g=await $.releaseStatus(p)}catch(k){ke(k,"releases:write","release status"),k instanceof be&&k.status===404&&S(`release ${p} not found.`),S(`release status failed: ${k instanceof Error?k.message:String(k)}`)}T(`release ${p}: status=${g.releaseStatus??"?"} stage=${g.stage} ${g.percent}%`+(g.runStatus?` (${g.runStatus})`:"")),g.outputTail&&T(g.outputTail.replace(/\n+$/,""))}),qn.command("rollback").argument("<id>","The release id to roll back").description("Roll back a live release (LIFO-guarded; server-side reverse deploy).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,h)=>{let{baseUrl:w,token:_}=await ne(h.baseUrl),$=new ee({baseUrl:w,token:_}),g;try{g=await $.releaseRollback(p)}catch(k){ke(k,"releases:write","release rollback"),k instanceof be&&k.status===404&&S(`release ${p} not found.`),k instanceof be&&k.status===409&&S(`release ${p} cannot be rolled back (not live, or a newer release advanced past it).`),S(`release rollback failed: ${k instanceof Error?k.message:String(k)}`)}T(`release ${g.releaseId} rolled back \u2192 status=${g.release?.status??"rolled_back"}.`)}),qn.command("list").description("List releases, newest-first, with delivered titles + latest status.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async p=>{let{baseUrl:h,token:w}=await ne(p.baseUrl),_=new ee({baseUrl:h,token:w}),$;try{$=await _.releaseList()}catch(g){ke(g,"releases:write","release list"),S(`release list failed: ${g instanceof Error?g.message:String(g)}`)}if($.length===0){T("no releases.");return}if(wt())T(_n($.map(g=>[g.id,to(g.status),g.target,g.backend,g.solutionTitles?.length?g.solutionTitles.map(k=>`"${k}"`).join(", "):x.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let g of $){let k=g.solutionTitles?.length?` "${g.solutionTitles.join('", "')}"`:"";T(` ${g.id} ${g.status.padEnd(11)} target=${g.target} backend=${g.backend}${k}`)}T(`
1834
- ${$.length} release(s).`)}),e.command("mcp").description("Run the local stdio authoring MCP server, for clients pointed at a process rather than a URL. (The .mcp.json that `project init` writes uses the instance's HTTP servers instead.)").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async p=>{let{runAuthoringMcpServer:h}=await Promise.resolve().then(()=>(u$(),l$));await h({baseUrl:p.baseUrl})}),e.addHelpText("after",["","Common flows:"," turbobase auth login --base-url https://acme.turbobase.app --token tb_pat_\u2026"," turbobase project init && turbobase project types"," turbobase ext new hook --record salesOrder && turbobase ext test hooks/\u2026"," turbobase ext deploy --to prod"," turbobase apps deploy my-app ./app","","Run `turbobase <group> --help` for a group (auth, project, ext, apps, kb, sandbox, mcp).","Docs: https://docs.turbobase.io/cli/overview/"].join(`
1835
- `)),t&&void 0,e}function Kj(t,e,r){let n=o=>{let s=new RegExp(`${o}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return s?s[2]:void 0};return{id:n("id")??`marketplace:${e}`,recordType:n("recordType")??"*",event:n("event")??"before_save",source:n("source")??"standalone",sourceCode:t,extensionKind:r||"hook"}}async function im(){let t=Te(process.cwd(),Mi,rs),e;try{e=await ye.readFile(t,"utf8")}catch{S(`no bundle found at ${Mi}/${rs} \u2014 run \`turbobase ext export\` first.`)}try{return by(e)}catch(r){S(`bundle is invalid: ${r instanceof Error?r.message:String(r)}`)}}function Wj(t,e){T(`plan against ${e}:`);for(let r of t.add)T(` ${jr.add(`${r.kind} ${r.id}`)}`);for(let r of t.change)T(` ${jr.change(`${r.kind} ${r.id}`)}`);for(let r of t.destroy)T(` ${jr.destroy(`${r.kind} ${r.id}`)}`);T(`
1836
- ${t.add.length} to add, ${t.change.length} to change, ${t.destroy.length} to destroy.`+(t.add.length+t.change.length+t.destroy.length===0?" (no changes \u2014 up to date.)":""))}function Gj(t){try{let r=new URL(t).hostname.split(".")[0];return r&&r!=="localhost"?r:void 0}catch{return}}function ii(t,e,r){return new Promise(n=>{let o=um(t,e,{stdio:["ignore","inherit","pipe"],env:{...process.env,...r}}),s="";o.stderr?.on("data",i=>{let a=i.toString();s+=a,process.stderr.write(a)}),o.on("error",i=>n({code:-1,stderr:i.message})),o.on("exit",i=>n({code:i??-1,stderr:s}))})}function am(){let t=process.env.SANDBOX_LOCAL_DATABASE_URL??"postgres://postgres:postgres@127.0.0.1:54322/postgres",e=async(r,n)=>{let o=n?t.replace(/\/[^/]*$/,`/${n}`):t,s=await ii("psql",[o,"-v","ON_ERROR_STOP=1","-c",r]);if(s.code!==0)throw new Error(`psql failed (exit ${s.code}): ${s.stderr.trim()}`)};return{target:()=>t,createDatabase:async r=>{await e(`CREATE DATABASE ${r};`)},replayMigrations:async r=>{let n=t.replace(/\/[^/]*$/,`/${r}`),o=await ii("supabase",["migration","up","--db-url",n]);if(o.code!==0)throw new Error(`supabase migration up failed (exit ${o.code}): ${o.stderr.trim()}`)},dataCopyUnavailable:()=>"seeding a sandbox from an instance is not implemented yet: it needs a per-column PII classification for the source tables, and a sandbox will never copy a column it cannot prove is safe. Nothing was created. Use `turbobase ext test <file>` or `turbobase ext replay <file> --fixture <f>` for the offline paths.",readSourceTables:async r=>{throw new Error("sandbox data copy is not implemented.")},copyRows:async(r,n,o)=>{let s=Object.keys(o[0]??{});if(s.length===0)return;let i=o.map(a=>`(${s.map(c=>a[c]===null||a[c]===void 0?"NULL":`'${String(a[c]).replace(/'/g,"''")}'`).join(", ")})`).join(", ");await e(`INSERT INTO turbobase.${n} (${s.join(", ")}) VALUES ${i};`,r)},dropDatabase:async r=>{await e(`DROP DATABASE IF EXISTS ${r} WITH (FORCE);`)}}}async function Jj(t){let e=Te(t,"src"),r={},n=async o=>{let s;try{s=await ye.readdir(o,{withFileTypes:!0})}catch{return}for(let i of s){let a=Rt(o,i.name);if(i.isDirectory())await n(a);else if(i.isFile()){let c=Ic(e,a).split(lm).join("/");r[c]=await ye.readFile(a,"utf8")}}};return await n(e),r}function cm(t){return new Promise(e=>{let r=um("git",t,{stdio:["ignore","pipe","ignore"]}),n="";r.stdout?.on("data",o=>{n+=o.toString()}),r.on("error",()=>e(null)),r.on("exit",o=>e(o===0&&n.trim()?n.trim():null))})}var Yj=!1;Yj&&dm().parseAsync(process.argv).catch(t=>S(t instanceof Error?t.message:String(t)));dm().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
2007
+ turbobase release status ${U.releaseId} --follow`)}catch(U){U instanceof be&&U.status===403&&k("an approved target needs --approved-by (the deploy gate fails closed)."),U instanceof be&&U.status===409&&k("that solution already has an active release \u2014 roll it back or wait for it."),le(U,"releases:write","push a release"),k(`release push failed: ${U instanceof Error?U.message:String(U)}`)}}),Zn.command("status").argument("<id>","The release id").description("Show a release deploy job's status; with --follow, poll to completion.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async(p,h)=>{let{baseUrl:_,token:x}=await ne(h.baseUrl),T=new Q({baseUrl:_,token:x});if(h.follow){await Ml(()=>T.releaseStatus(p),`release ${p}`,h.intervalMs);return}let g;try{g=await T.releaseStatus(p)}catch(S){le(S,"releases:write","release status"),S instanceof be&&S.status===404&&k(`release ${p} not found.`),k(`release status failed: ${S instanceof Error?S.message:String(S)}`)}$(`release ${p}: status=${g.releaseStatus??"?"} stage=${g.stage} ${g.percent}%`+(g.runStatus?` (${g.runStatus})`:"")),g.outputTail&&$(g.outputTail.replace(/\n+$/,""))}),Zn.command("rollback").argument("<id>","The release id to roll back").description("Roll back a live release (LIFO-guarded; server-side reverse deploy).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,h)=>{let{baseUrl:_,token:x}=await ne(h.baseUrl),T=new Q({baseUrl:_,token:x}),g;try{g=await T.releaseRollback(p)}catch(S){le(S,"releases:write","release rollback"),S instanceof be&&S.status===404&&k(`release ${p} not found.`),S instanceof be&&S.status===409&&k(`release ${p} cannot be rolled back (not live, or a newer release advanced past it).`),k(`release rollback failed: ${S instanceof Error?S.message:String(S)}`)}$(`release ${g.releaseId} rolled back \u2192 status=${g.release?.status??"rolled_back"}.`)}),Zn.command("list").description("List releases, newest-first, with delivered titles + latest status.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async p=>{let{baseUrl:h,token:_}=await ne(p.baseUrl),x=new Q({baseUrl:h,token:_}),T;try{T=await x.releaseList()}catch(g){le(g,"releases:write","release list"),k(`release list failed: ${g instanceof Error?g.message:String(g)}`)}if(T.length===0){$("no releases.");return}if(Ye())$(Mr(T.map(g=>[g.id,eo(g.status),g.target,g.backend,g.solutionTitles?.length?g.solutionTitles.map(S=>`"${S}"`).join(", "):w.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let g of T){let S=g.solutionTitles?.length?` "${g.solutionTitles.join('", "')}"`:"";$(` ${g.id} ${g.status.padEnd(11)} target=${g.target} backend=${g.backend}${S}`)}$(`
2008
+ ${T.length} release(s).`)}),e.command("mcp").description("Run the local stdio authoring MCP server, for clients pointed at a process rather than a URL. (The .mcp.json that `project init` writes uses the instance's HTTP servers instead.)").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async p=>{let{runAuthoringMcpServer:h}=await Promise.resolve().then(()=>(A$(),P$));await h({baseUrl:p.baseUrl})}),e.addHelpText("after",["","Common flows:"," turbobase auth login --base-url https://acme.turbobase.app --token tb_pat_\u2026"," turbobase project init && turbobase project types"," turbobase ext new hook --record salesOrder && turbobase ext test hooks/\u2026"," turbobase ext deploy --to prod"," turbobase apps deploy my-app ./app","","Run `turbobase <group> --help` for a group (auth, project, ext, apps, kb, sandbox, mcp).","Docs: https://docs.turbobase.io/cli/overview/"].join(`
2009
+ `)),t&&void 0,e}function RL(t,e,r){let n=o=>{let s=new RegExp(`${o}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return s?s[2]:void 0};return{id:n("id")??`marketplace:${e}`,recordType:n("recordType")??"*",event:n("event")??"before_save",source:n("source")??"standalone",sourceCode:t,extensionKind:r||"hook"}}async function hm(){let t=Te(process.cwd(),Vi,cs),e;try{e=await we.readFile(t,"utf8")}catch{k(`no bundle found at ${Vi}/${cs} \u2014 run \`turbobase ext export\` first.`)}try{return jy(e)}catch(r){k(`bundle is invalid: ${r instanceof Error?r.message:String(r)}`)}}function PL(t,e){$(`plan against ${e}:`);for(let r of t.add)$(` ${Lr.add(`${r.kind} ${r.id}`)}`);for(let r of t.change)$(` ${Lr.change(`${r.kind} ${r.id}`)}`);for(let r of t.destroy)$(` ${Lr.destroy(`${r.kind} ${r.id}`)}`);$(`
2010
+ ${t.add.length} to add, ${t.change.length} to change, ${t.destroy.length} to destroy.`+(t.add.length+t.change.length+t.destroy.length===0?" (no changes \u2014 up to date.)":""))}function AL(t){try{let r=new URL(t).hostname.split(".")[0];return r&&r!=="localhost"?r:void 0}catch{return}}function fi(t,e,r){return new Promise(n=>{let o=bm(t,e,{stdio:["ignore","inherit","pipe"],env:{...process.env,...r}}),s="";o.stderr?.on("data",i=>{let a=i.toString();s+=a,process.stderr.write(a)}),o.on("error",i=>n({code:-1,stderr:i.message})),o.on("exit",i=>n({code:i??-1,stderr:s}))})}function mm(){let t=process.env.SANDBOX_LOCAL_DATABASE_URL??"postgres://postgres:postgres@127.0.0.1:54322/postgres",e=async(r,n)=>{let o=n?t.replace(/\/[^/]*$/,`/${n}`):t,s=await fi("psql",[o,"-v","ON_ERROR_STOP=1","-c",r]);if(s.code!==0)throw new Error(`psql failed (exit ${s.code}): ${s.stderr.trim()}`)};return{target:()=>t,createDatabase:async r=>{await e(`CREATE DATABASE ${r};`)},replayMigrations:async r=>{let n=t.replace(/\/[^/]*$/,`/${r}`),o=await fi("supabase",["migration","up","--db-url",n]);if(o.code!==0)throw new Error(`supabase migration up failed (exit ${o.code}): ${o.stderr.trim()}`)},dataCopyUnavailable:()=>"seeding a sandbox from an instance is not implemented yet: it needs a per-column PII classification for the source tables, and a sandbox will never copy a column it cannot prove is safe. Nothing was created. Use `turbobase ext test <file>` or `turbobase ext replay <file> --fixture <f>` for the offline paths.",readSourceTables:async r=>{throw new Error("sandbox data copy is not implemented.")},copyRows:async(r,n,o)=>{let s=Object.keys(o[0]??{});if(s.length===0)return;let i=o.map(a=>`(${s.map(c=>a[c]===null||a[c]===void 0?"NULL":`'${String(a[c]).replace(/'/g,"''")}'`).join(", ")})`).join(", ");await e(`INSERT INTO turbobase.${n} (${s.join(", ")}) VALUES ${i};`,r)},dropDatabase:async r=>{await e(`DROP DATABASE IF EXISTS ${r} WITH (FORCE);`)}}}async function IL(t){let e=Te(t,"src"),r={},n=async o=>{let s;try{s=await we.readdir(o,{withFileTypes:!0})}catch{return}for(let i of s){let a=At(o,i.name);if(i.isDirectory())await n(a);else if(i.isFile()){let c=Dc(e,a).split(ym).join("/");r[c]=await we.readFile(a,"utf8")}}};return await n(e),r}function gm(t){return new Promise(e=>{let r=bm("git",t,{stdio:["ignore","pipe","ignore"]}),n="";r.stdout?.on("data",o=>{n+=o.toString()}),r.on("error",()=>e(null)),r.on("exit",o=>e(o===0&&n.trim()?n.trim():null))})}var OL=!1;OL&&wm().parseAsync(process.argv).catch(t=>k(t instanceof Error?t.message:String(t)));wm().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
1837
2011
  `),process.exit(1)});