@turbobase/cli 1.1.19 → 1.1.20

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 Fc=Object.defineProperty;var U$=Object.getOwnPropertyDescriptor;var Z$=Object.getOwnPropertyNames;var q$=Object.getPrototypeOf,F$=Object.prototype.hasOwnProperty;var Bo=(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),Vo=(t,e)=>{for(var r in e)Fc(t,r,{get:e[r],enumerable:!0})},B$=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Z$(e))!F$.call(t,o)&&o!==r&&Fc(t,o,{get:()=>e[o],enumerable:!(n=U$(e,o))||n.enumerable});return t};var Bc=(t,e,r)=>(r=t!=null?M$(q$(t)):{},B$(e||!t||!t.__esModule?Fc(r,"default",{value:t,enumerable:!0}):r,t));var Ho=Z(Hc=>{var bi=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}},Vc=class extends bi{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Hc.CommanderError=bi;Hc.InvalidArgumentError=Vc});var wi=Z(Gc=>{var{InvalidArgumentError:V$}=Ho(),Kc=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 H$(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}Gc.Argument=Kc;Gc.humanReadableArgName=H$});var Jc=Z(Tm=>{var{humanReadableArgName:K$}=wi(),Wc=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(`
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(`
4
+ var nS=Object.create;var Jc=Object.defineProperty;var oS=Object.getOwnPropertyDescriptor;var sS=Object.getOwnPropertyNames;var iS=Object.getPrototypeOf,aS=Object.prototype.hasOwnProperty;var Vo=(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),Ho=(t,e)=>{for(var r in e)Jc(t,r,{get:e[r],enumerable:!0})},cS=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of sS(e))!aS.call(t,o)&&o!==r&&Jc(t,o,{get:()=>e[o],enumerable:!(n=oS(e,o))||n.enumerable});return t};var Yc=(t,e,r)=>(r=t!=null?nS(iS(t)):{},cS(e||!t||!t.__esModule?Jc(r,"default",{value:t,enumerable:!0}):r,t));var Ko=Z(Qc=>{var _i=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}},Xc=class extends _i{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Qc.CommanderError=_i;Qc.InvalidArgumentError=Xc});var vi=Z(tl=>{var{InvalidArgumentError:lS}=Ko(),el=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 lS(`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 uS(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}tl.Argument=el;tl.humanReadableArgName=uS});var nl=Z(zm=>{var{humanReadableArgName:dS}=vi(),rl=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=>dS(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,b){if(b){let k=`${f.padEnd(n+i)}${b}`;return r.wrap(k,o-s,n+i)}return f}function c(f){return f.join(`
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 w=r.visibleOptions(e).map(f=>a(r.optionTerm(f),r.optionDescription(f)));if(w.length>0&&(l=l.concat(["Options:",c(w),""])),this.showGlobalOptions){let f=r.visibleGlobalOptions(e).map(b=>a(r.optionTerm(b),r.optionDescription(b)));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
- `),u=" ".repeat(n),b="\\s\u200B",m=new RegExp(`
9
- |.{1,${a-1}}([${b}]|$)|[^${b}]+?([${b}]|$)`,"g"),f=l.match(m)||[];return c+f.map((y,v)=>y===`
10
- `?"":(v>0?u:"")+y.trimEnd()).join(`
11
- `)}};Tm.Help=Wc});var Qc=Z(_i=>{var{InvalidArgumentError:G$}=Ho(),Yc=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=Em(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 G$(`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 W$(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Xc=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 W$(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function Em(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}}_i.Option=Yc;_i.splitOptionFlags=Em;_i.DualOptions=Xc});var Pm=Z(Rm=>{function J$(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 Y$(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=J$(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?`
8
+ `),u=" ".repeat(n),w="\\s\u200B",m=new RegExp(`
9
+ |.{1,${a-1}}([${w}]|$)|[^${w}]+?([${w}]|$)`,"g"),f=l.match(m)||[];return c+f.map((b,k)=>b===`
10
+ `?"":(k>0?u:"")+b.trimEnd()).join(`
11
+ `)}};zm.Help=rl});var il=Z(xi=>{var{InvalidArgumentError:pS}=Ko(),ol=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=Nm(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 pS(`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 fS(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},sl=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 fS(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function Nm(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}}xi.Option=ol;xi.splitOptionFlags=Nm;xi.DualOptions=sl});var Lm=Z(jm=>{function hS(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 mS(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=hS(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]}?)`:""}Rm.suggestSimilar=Y$});var Nm=Z(zm=>{var X$=Bo("events").EventEmitter,el=Bo("child_process"),yr=Bo("path"),tl=Bo("fs"),Me=Bo("process"),{Argument:Q$,humanReadableArgName:eS}=wi(),{CommanderError:rl}=Ho(),{Help:tS}=Jc(),{Option:Am,splitOptionFlags:rS,DualOptions:nS}=Qc(),{suggestSimilar:Im}=Pm(),nl=class t extends X${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 tS,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 Q$(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 rl(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 Am(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 Am)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=yr.resolve(u,d);if(tl.existsSync(b))return b;if(o.includes(yr.extname(d)))return;let m=o.find(f=>tl.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=tl.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=yr.resolve(yr.dirname(u),a)}if(a){let u=s(a,i);if(!u&&!e._executableFile&&this._scriptPath){let d=yr.basename(this._scriptPath,yr.extname(this._scriptPath));d!==this._name&&(u=s(a,`${d}-${e._name}`))}i=u||i}n=o.includes(yr.extname(i));let c;Me.platform!=="win32"?n?(r.unshift(i),r=Cm(Me.execArgv).concat(r),c=el.spawn(Me.argv[0],r,{stdio:"inherit"})):c=el.spawn(i,r,{stdio:"inherit"}):(r.unshift(i),r=Cm(Me.execArgv).concat(r),c=el.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 rl(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]}?)`:""}jm.suggestSimilar=mS});var Fm=Z(qm=>{var gS=Vo("events").EventEmitter,al=Vo("child_process"),br=Vo("path"),cl=Vo("fs"),Me=Vo("process"),{Argument:yS,humanReadableArgName:bS}=vi(),{CommanderError:ll}=Ko(),{Help:wS}=nl(),{Option:Dm,splitOptionFlags:_S,DualOptions:vS}=il(),{suggestSimilar:Mm}=Lm(),ul=class t extends gS{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 wS,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 yS(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 ll(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 Dm(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 Dm)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 w=br.resolve(u,d);if(cl.existsSync(w))return w;if(o.includes(br.extname(d)))return;let m=o.find(f=>cl.existsSync(`${w}${f}`));if(m)return`${w}${m}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=cl.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=br.resolve(br.dirname(u),a)}if(a){let u=s(a,i);if(!u&&!e._executableFile&&this._scriptPath){let d=br.basename(this._scriptPath,br.extname(this._scriptPath));d!==this._name&&(u=s(a,`${d}-${e._name}`))}i=u||i}n=o.includes(br.extname(i));let c;Me.platform!=="win32"?n?(r.unshift(i),r=Zm(Me.execArgv).concat(r),c=al.spawn(Me.argv[0],r,{stdio:"inherit"})):c=al.spawn(i,r,{stdio:"inherit"}):(r.unshift(i),r=Zm(Me.execArgv).concat(r),c=al.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 ll(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",w=`'${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 rl(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 Om(this,r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),Om(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(w)}else if(u.code==="EACCES")throw new Error(`'${i}' not executable`);if(!l)Me.exit(1);else{let d=new ll(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 Um(this,r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),Um(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 nS(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=Im(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=Im(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=>eS(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=yr.basename(e,yr.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=rS(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 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 vS(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=Mm(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=Mm(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=>bS(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=br.basename(e,br.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=_S(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.
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 Om(t,e){t._hasHelpOption&&e.find(n=>n===t._helpLongFlag||n===t._helpShortFlag)&&(t.outputHelp(),t._exit(0,"commander.helpDisplayed","(outputHelp)"))}function Cm(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})}zm.Command=nl});var Mm=Z((Gt,Dm)=>{var{Argument:oS}=wi(),{Command:jm}=Nm(),{CommanderError:sS,InvalidArgumentError:Lm}=Ho(),{Help:iS}=Jc(),{Option:aS}=Qc();Gt=Dm.exports=new jm;Gt.program=Gt;Gt.Command=jm;Gt.Option=aS;Gt.Argument=oS;Gt.Help=iS;Gt.CommanderError=sS;Gt.InvalidArgumentError=Lm;Gt.InvalidOptionArgumentError=Lm});function Ko(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var vi=O(()=>{});var me,ol,F,ir,Go=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})(me||(me={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(ol||(ol={}));F=me.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ir=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,cS,wt,xi=O(()=>{Go();j=me.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"]),cS=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),wt=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,me.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()}};wt.create=t=>new wt(t)});var lS,br,sl=O(()=>{xi();Go();lS=(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,me.jsonStringifyReplacer)}`;break;case j.unrecognized_keys:r=`Unrecognized key(s) in object: ${me.joinValues(t.keys,", ")}`;break;case j.invalid_union:r="Invalid input";break;case j.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${me.joinValues(t.options)}`;break;case j.invalid_enum_value:r=`Invalid enum value. Expected ${me.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}"`:me.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,me.assertNever(t)}return{message:r}},br=lS});function uS(t){qm=t}function Bn(){return qm}var qm,ki=O(()=>{sl();qm=br});function q(t,e){let r=Bn(),n=Wo({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===br?void 0:br].filter(o=>!!o)});t.common.issues.push(n)}var Wo,dS,tt,ee,an,lt,$i,Si,Or,Vn,il=O(()=>{ki();sl();Wo=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}},dS=[];tt=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"}),an=t=>({status:"dirty",value:t}),lt=t=>({status:"valid",value:t}),$i=t=>t.status==="aborted",Si=t=>t.status==="dirty",Or=t=>t.status==="valid",Vn=t=>typeof Promise<"u"&&t instanceof Promise});var Fm=O(()=>{});var K,Bm=O(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(K||(K={}))});function ae(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 Gm(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 RS(t){return new RegExp(`^${Gm(t)}$`)}function Wm(t){let e=`${Km}T${Gm(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 PS(t,e){return!!((e==="v4"||!e)&&vS.test(t)||(e==="v6"||!e)&&kS.test(t))}function AS(t,e){if(!yS.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 IS(t,e){return!!((e==="v4"||!e)&&xS.test(t)||(e==="v6"||!e)&&$S.test(t))}function OS(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 Hn(t){if(t instanceof vt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=_t.create(Hn(n))}return new vt({...t._def,shape:()=>e})}else return t instanceof vr?new vr({...t._def,type:Hn(t.element)}):t instanceof _t?_t.create(Hn(t.unwrap())):t instanceof cr?cr.create(Hn(t.unwrap())):t instanceof ar?ar.create(t.items.map(e=>Hn(e))):t}function cl(t,e){let r=ir(t),n=ir(e);if(t===e)return{valid:!0,data:t};if(r===F.object&&n===F.object){let o=me.objectKeys(e),s=me.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=cl(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=cl(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 Jm(t,e){return new bn({values:t,typeName:L.ZodEnum,...ae(e)})}function Hm(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Ym(t,e={},r){return t?zr.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Hm(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Hm(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):zr.create()}var zt,Vm,de,pS,fS,hS,mS,gS,yS,bS,wS,_S,al,vS,xS,kS,$S,SS,TS,Km,ES,Cr,cn,ln,un,dn,Kn,pn,fn,zr,_r,Wt,Gn,vr,vt,hn,wr,Ti,mn,ar,Ei,Wn,Jn,Ri,gn,yn,bn,wn,Nr,Nt,_t,cr,_n,vn,Yn,CS,Jo,Yo,xn,zS,L,NS,Xm,Qm,jS,LS,eg,DS,MS,US,ZS,qS,FS,BS,VS,HS,ll,KS,GS,WS,JS,YS,XS,QS,eT,tT,rT,nT,oT,sT,iT,aT,cT,lT,uT,dT,pT,fT,hT,mT,gT,tg=O(()=>{xi();ki();Bm();il();Go();zt=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}},Vm=(t,e)=>{if(Or(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 wt(t.common.issues);return this._error=r,this._error}}};de=class{get description(){return this._def.description}_getType(e){return ir(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:ir(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new tt,ctx:{common:e.parent.common,data:e.data,parsedType:ir(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Vn(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:ir(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Vm(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ir(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Or(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=>Or(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:ir(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(Vn(o)?o:Promise.resolve(o));return Vm(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 Nt({schema:this,typeName:L.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 _t.create(this,this._def)}nullable(){return cr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return vr.create(this)}promise(){return Nr.create(this,this._def)}or(e){return hn.create([this,e],this._def)}and(e){return mn.create(this,e,this._def)}transform(e){return new Nt({...ae(this._def),schema:this,typeName:L.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new _n({...ae(this._def),innerType:this,defaultValue:r,typeName:L.ZodDefault})}brand(){return new Jo({typeName:L.ZodBranded,type:this,...ae(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new vn({...ae(this._def),innerType:this,catchValue:r,typeName:L.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Yo.create(this,e)}readonly(){return xn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},pS=/^c[^\s-]{8,}$/i,fS=/^[0-9a-z]+$/,hS=/^[0-9A-HJKMNP-TV-Z]{26}$/i,mS=/^[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,gS=/^[a-z0-9_-]{21}$/i,yS=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,bS=/^[-+]?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)?)??$/,wS=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_S="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",vS=/^(?:(?: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])$/,xS=/^(?:(?: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])$/,kS=/^(([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])$/,SS=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,TS=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Km="((\\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])))",ES=new RegExp(`^${Km}$`);Cr=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 tt,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")wS.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")al||(al=new RegExp(_S,"u")),al.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")mS.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")gS.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")pS.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")fS.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")hS.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"?Wm(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"?ES.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{code:j.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?RS(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"?bS.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"duration",code:j.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?PS(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"?AS(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"?IS(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"?SS.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"base64",code:j.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?TS.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"base64url",code:j.invalid_string,message:s.message}),n.dirty()):me.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}};Cr.create=t=>new Cr({checks:[],typeName:L.ZodString,coerce:t?.coerce??!1,...ae(t)});cn=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 tt;for(let s of this._def.checks)s.kind==="int"?me.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"?OS(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()):me.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"&&me.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)}};cn.create=t=>new cn({checks:[],typeName:L.ZodNumber,coerce:t?.coerce||!1,...ae(t)});ln=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 tt;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()):me.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}};ln.create=t=>new ln({checks:[],typeName:L.ZodBigInt,coerce:t?.coerce??!1,...ae(t)});un=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 lt(e.data)}};un.create=t=>new un({typeName:L.ZodBoolean,coerce:t?.coerce||!1,...ae(t)});dn=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 tt,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()):me.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}};dn.create=t=>new dn({checks:[],coerce:t?.coerce||!1,typeName:L.ZodDate,...ae(t)});Kn=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 lt(e.data)}};Kn.create=t=>new Kn({typeName:L.ZodSymbol,...ae(t)});pn=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 lt(e.data)}};pn.create=t=>new pn({typeName:L.ZodUndefined,...ae(t)});fn=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 lt(e.data)}};fn.create=t=>new fn({typeName:L.ZodNull,...ae(t)});zr=class extends de{constructor(){super(...arguments),this._any=!0}_parse(e){return lt(e.data)}};zr.create=t=>new zr({typeName:L.ZodAny,...ae(t)});_r=class extends de{constructor(){super(...arguments),this._unknown=!0}_parse(e){return lt(e.data)}};_r.create=t=>new _r({typeName:L.ZodUnknown,...ae(t)});Wt=class extends de{_parse(e){let r=this._getOrReturnCtx(e);return q(r,{code:j.invalid_type,expected:F.never,received:r.parsedType}),ee}};Wt.create=t=>new Wt({typeName:L.ZodNever,...ae(t)});Gn=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 lt(e.data)}};Gn.create=t=>new Gn({typeName:L.ZodVoid,...ae(t)});vr=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 zt(r,i,r.path,a)))).then(i=>tt.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new zt(r,i,r.path,a)));return tt.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)}};vr.create=(t,e)=>new vr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:L.ZodArray,...ae(e)});vt=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=me.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 Wt&&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 zt(o,d,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Wt){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 zt(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=>tt.mergeObjectSync(n,l)):tt.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:L.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 me.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 me.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Hn(this)}partial(e){let r={};for(let n of me.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 me.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof _t;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Jm(me.objectKeys(this.shape))}};vt.create=(t,e)=>new vt({shape:()=>t,unknownKeys:"strip",catchall:Wt.create(),typeName:L.ZodObject,...ae(e)});vt.strictCreate=(t,e)=>new vt({shape:()=>t,unknownKeys:"strict",catchall:Wt.create(),typeName:L.ZodObject,...ae(e)});vt.lazycreate=(t,e)=>new vt({shape:t,unknownKeys:"strip",catchall:Wt.create(),typeName:L.ZodObject,...ae(e)});hn=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 wt(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 wt(c));return q(r,{code:j.invalid_union,unionErrors:a}),ee}}get options(){return this._def.options}};hn.create=(t,e)=>new hn({options:t,typeName:L.ZodUnion,...ae(e)});wr=t=>t instanceof gn?wr(t.schema):t instanceof Nt?wr(t.innerType()):t instanceof yn?[t.value]:t instanceof bn?t.options:t instanceof wn?me.objectValues(t.enum):t instanceof _n?wr(t._def.innerType):t instanceof pn?[void 0]:t instanceof fn?[null]:t instanceof _t?[void 0,...wr(t.unwrap())]:t instanceof cr?[null,...wr(t.unwrap())]:t instanceof Jo||t instanceof xn?wr(t.unwrap()):t instanceof vn?wr(t._def.innerType):[],Ti=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=wr(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:L.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...ae(n)})}};mn=class extends de{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if($i(s)||$i(i))return ee;let a=cl(s.value,i.value);return a.valid?((Si(s)||Si(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}))}};mn.create=(t,e,r)=>new mn({left:t,right:e,typeName:L.ZodIntersection,...ae(r)});ar=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 zt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>tt.mergeArray(r,i)):tt.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};ar.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ar({items:t,typeName:L.ZodTuple,rest:null,...ae(e)})};Ei=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 zt(n,a,n.path,a)),value:i._parse(new zt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?tt.mergeObjectAsync(r,o):tt.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:L.ZodRecord,...ae(n)}):new t({keyType:Cr.create(),valueType:e,typeName:L.ZodRecord,...ae(r)})}},Wn=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 zt(n,a,n.path,[l,"key"])),value:s._parse(new zt(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}}}};Wn.create=(t,e,r)=>new Wn({valueType:e,keyType:t,typeName:L.ZodMap,...ae(r)});Jn=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 zt(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)}};Jn.create=(t,e)=>new Jn({valueType:t,minSize:null,maxSize:null,typeName:L.ZodSet,...ae(e)});Ri=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 Wo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Bn(),br].filter(l=>!!l),issueData:{code:j.invalid_arguments,argumentsError:c}})}function o(a,c){return Wo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Bn(),br].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 Nr){let a=this;return lt(async function(...c){let l=new wt([]),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 lt(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new wt([n(c,l.error)]);let u=Reflect.apply(i,this,l.data),d=a._def.returns.safeParse(u,s);if(!d.success)throw new wt([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:ar.create(e).rest(_r.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||ar.create([]).rest(_r.create()),returns:r||_r.create(),typeName:L.ZodFunction,...ae(n)})}},gn=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})}};gn.create=(t,e)=>new gn({getter:t,typeName:L.ZodLazy,...ae(e)});yn=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}};yn.create=(t,e)=>new yn({value:t,typeName:L.ZodLiteral,...ae(e)});bn=class t extends de{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return q(r,{expected:me.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 lt(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})}};bn.create=Jm;wn=class extends de{_parse(e){let r=me.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==F.string&&n.parsedType!==F.number){let o=me.objectValues(r);return q(n,{expected:me.joinValues(o),received:n.parsedType,code:j.invalid_type}),ee}if(this._cache||(this._cache=new Set(me.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=me.objectValues(r);return q(n,{received:n.data,code:j.invalid_enum_value,options:o}),ee}return lt(e.data)}get enum(){return this._def.values}};wn.create=(t,e)=>new wn({values:t,typeName:L.ZodNativeEnum,...ae(e)});Nr=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 lt(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Nr.create=(t,e)=>new Nr({type:t,typeName:L.ZodPromise,...ae(e)});Nt=class extends de{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===L.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"?an(c.value):r.value==="dirty"?an(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"?an(a.value):r.value==="dirty"?an(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(!Or(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=>Or(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):ee);me.assertNever(o)}};Nt.create=(t,e,r)=>new Nt({schema:t,typeName:L.ZodEffects,effect:e,...ae(r)});Nt.createWithPreprocess=(t,e,r)=>new Nt({schema:e,effect:{type:"preprocess",transform:t},typeName:L.ZodEffects,...ae(r)});_t=class extends de{_parse(e){return this._getType(e)===F.undefined?lt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};_t.create=(t,e)=>new _t({innerType:t,typeName:L.ZodOptional,...ae(e)});cr=class extends de{_parse(e){return this._getType(e)===F.null?lt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};cr.create=(t,e)=>new cr({innerType:t,typeName:L.ZodNullable,...ae(e)});_n=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}};_n.create=(t,e)=>new _n({innerType:t,typeName:L.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ae(e)});vn=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 Vn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new wt(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new wt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};vn.create=(t,e)=>new vn({innerType:t,typeName:L.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ae(e)});Yn=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}}};Yn.create=t=>new Yn({typeName:L.ZodNaN,...ae(t)});CS=Symbol("zod_brand"),Jo=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}},Yo=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(),an(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:L.ZodPipeline})}},xn=class extends de{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Or(o)&&(o.value=Object.freeze(o.value)),o);return Vn(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};xn.create=(t,e)=>new xn({innerType:t,typeName:L.ZodReadonly,...ae(e)});zS={object:vt.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"})(L||(L={}));NS=(t,e={message:`Input not instance of ${t.name}`})=>Ym(r=>r instanceof t,e),Xm=Cr.create,Qm=cn.create,jS=Yn.create,LS=ln.create,eg=un.create,DS=dn.create,MS=Kn.create,US=pn.create,ZS=fn.create,qS=zr.create,FS=_r.create,BS=Wt.create,VS=Gn.create,HS=vr.create,ll=vt.create,KS=vt.strictCreate,GS=hn.create,WS=Ti.create,JS=mn.create,YS=ar.create,XS=Ei.create,QS=Wn.create,eT=Jn.create,tT=Ri.create,rT=gn.create,nT=yn.create,oT=bn.create,sT=wn.create,iT=Nr.create,aT=Nt.create,cT=_t.create,lT=cr.create,uT=Nt.createWithPreprocess,dT=Yo.create,pT=()=>Xm().optional(),fT=()=>Qm().optional(),hT=()=>eg().optional(),mT={string:(t=>Cr.create({...t,coerce:!0})),number:(t=>cn.create({...t,coerce:!0})),boolean:(t=>un.create({...t,coerce:!0})),bigint:(t=>ln.create({...t,coerce:!0})),date:(t=>dn.create({...t,coerce:!0}))},gT=ee});var N={};Vo(N,{BRAND:()=>CS,DIRTY:()=>an,EMPTY_PATH:()=>dS,INVALID:()=>ee,NEVER:()=>gT,OK:()=>lt,ParseStatus:()=>tt,Schema:()=>de,ZodAny:()=>zr,ZodArray:()=>vr,ZodBigInt:()=>ln,ZodBoolean:()=>un,ZodBranded:()=>Jo,ZodCatch:()=>vn,ZodDate:()=>dn,ZodDefault:()=>_n,ZodDiscriminatedUnion:()=>Ti,ZodEffects:()=>Nt,ZodEnum:()=>bn,ZodError:()=>wt,ZodFirstPartyTypeKind:()=>L,ZodFunction:()=>Ri,ZodIntersection:()=>mn,ZodIssueCode:()=>j,ZodLazy:()=>gn,ZodLiteral:()=>yn,ZodMap:()=>Wn,ZodNaN:()=>Yn,ZodNativeEnum:()=>wn,ZodNever:()=>Wt,ZodNull:()=>fn,ZodNullable:()=>cr,ZodNumber:()=>cn,ZodObject:()=>vt,ZodOptional:()=>_t,ZodParsedType:()=>F,ZodPipeline:()=>Yo,ZodPromise:()=>Nr,ZodReadonly:()=>xn,ZodRecord:()=>Ei,ZodSchema:()=>de,ZodSet:()=>Jn,ZodString:()=>Cr,ZodSymbol:()=>Kn,ZodTransformer:()=>Nt,ZodTuple:()=>ar,ZodType:()=>de,ZodUndefined:()=>pn,ZodUnion:()=>hn,ZodUnknown:()=>_r,ZodVoid:()=>Gn,addIssueToContext:()=>q,any:()=>qS,array:()=>HS,bigint:()=>LS,boolean:()=>eg,coerce:()=>mT,custom:()=>Ym,date:()=>DS,datetimeRegex:()=>Wm,defaultErrorMap:()=>br,discriminatedUnion:()=>WS,effect:()=>aT,enum:()=>oT,function:()=>tT,getErrorMap:()=>Bn,getParsedType:()=>ir,instanceof:()=>NS,intersection:()=>JS,isAborted:()=>$i,isAsync:()=>Vn,isDirty:()=>Si,isValid:()=>Or,late:()=>zS,lazy:()=>rT,literal:()=>nT,makeIssue:()=>Wo,map:()=>QS,nan:()=>jS,nativeEnum:()=>sT,never:()=>BS,null:()=>ZS,nullable:()=>lT,number:()=>Qm,object:()=>ll,objectUtil:()=>ol,oboolean:()=>hT,onumber:()=>fT,optional:()=>cT,ostring:()=>pT,pipeline:()=>dT,preprocess:()=>uT,promise:()=>iT,quotelessJson:()=>cS,record:()=>XS,set:()=>eT,setErrorMap:()=>uS,strictObject:()=>KS,string:()=>Xm,symbol:()=>MS,transformer:()=>aT,tuple:()=>YS,undefined:()=>US,union:()=>GS,unknown:()=>FS,util:()=>me,void:()=>VS});var Pi=O(()=>{ki();il();Fm();Go();tg();xi()});var Xn=O(()=>{Pi();Pi()});function Ai(t){let e=ul.safeParse(t);return e.success?(e.data.inputs??[]).filter(r=>r.type==="connection"):[]}function dl(t,e){let r=ul.safeParse(t);if(!r.success)throw new jr(`invalid manifest: ${r.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}`);if(rg.test(e))throw new jr('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(rg.test(n))throw new jr("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var ng,og,ul,jr,rg,sg=O(()=>{Xn();ng=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()}),og=N.discriminatedUnion("type",[ng]),ul=N.object({inputs:N.array(og).optional()}).passthrough(),jr=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};rg=/\bconnection[_-]?id\b["']?\s*[:=]/i});var Ii,pl=O(()=>{Ii=["before_read","before_save","after_save","before_sync","after_sync","on_sync_failure"]});var fl,ig,ag=O(()=>{Xn();vi();pl();fl=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(Ii),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"})}),ig=Ko({kind:"hook",schema:fl,factoryName:"defineHook"})});var cg=O(()=>{ag();pl()});var Oi,hl=O(()=>{Oi=["after_canonicalize_inbound","after_sync_success_outbound"]});var ml,lg,ug=O(()=>{Xn();vi();hl();ml=N.object({id:N.string().min(1,"conduit id must be non-empty"),on:N.enum(Oi),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"})}),lg=Ko({kind:"conduit",schema:ml,factoryName:"defineConduit"})});var dg=O(()=>{ug();hl()});async function vT(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 Ci(t,e={}){return(e.transform??vT)(t)}var gl=O(()=>{});function yl(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 pg(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function bl(t){return`${pg(t.source)}${pg(t.recordType)}`}function xT(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function kT(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 wl(t){let e=bl(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 Um(t,e){t._hasHelpOption&&e.find(n=>n===t._helpLongFlag||n===t._helpShortFlag)&&(t.outputHelp(),t._exit(0,"commander.helpDisplayed","(outputHelp)"))}function Zm(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})}qm.Command=ul});var Km=Z((Wt,Hm)=>{var{Argument:xS}=vi(),{Command:Bm}=Fm(),{CommanderError:kS,InvalidArgumentError:Vm}=Ko(),{Help:$S}=nl(),{Option:SS}=il();Wt=Hm.exports=new Bm;Wt.program=Wt;Wt.Command=Bm;Wt.Option=SS;Wt.Argument=xS;Wt.Help=$S;Wt.CommanderError=kS;Wt.InvalidArgumentError=Vm;Wt.InvalidOptionArgumentError=Vm});function Go(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var ki=O(()=>{});var ge,dl,F,ar,Wo=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})})(dl||(dl={}));F=ge.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ar=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 L,TS,vt,$i=O(()=>{Wo();L=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"]),TS=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),vt=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()}};vt.create=t=>new vt(t)});var ES,wr,pl=O(()=>{$i();Wo();ES=(t,e)=>{let r;switch(t.code){case L.invalid_type:t.received===F.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case L.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ge.jsonStringifyReplacer)}`;break;case L.unrecognized_keys:r=`Unrecognized key(s) in object: ${ge.joinValues(t.keys,", ")}`;break;case L.invalid_union:r="Invalid input";break;case L.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ge.joinValues(t.options)}`;break;case L.invalid_enum_value:r=`Invalid enum value. Expected ${ge.joinValues(t.options)}, received '${t.received}'`;break;case L.invalid_arguments:r="Invalid function arguments";break;case L.invalid_return_type:r="Invalid function return type";break;case L.invalid_date:r="Invalid date";break;case L.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 L.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 L.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 L.custom:r="Invalid input";break;case L.invalid_intersection_types:r="Intersection results could not be merged";break;case L.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case L.not_finite:r="Number must be finite";break;default:r=e.defaultError,ge.assertNever(t)}return{message:r}},wr=ES});function RS(t){Jm=t}function Vn(){return Jm}var Jm,Si=O(()=>{pl();Jm=wr});function q(t,e){let r=Vn(),n=Jo({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===wr?void 0:wr].filter(o=>!!o)});t.common.issues.push(n)}var Jo,PS,rt,ee,cn,ut,Ti,Ei,Nr,Hn,fl=O(()=>{Si();pl();Jo=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}},PS=[];rt=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"}),cn=t=>({status:"dirty",value:t}),ut=t=>({status:"valid",value:t}),Ti=t=>t.status==="aborted",Ei=t=>t.status==="dirty",Nr=t=>t.status==="valid",Hn=t=>typeof Promise<"u"&&t instanceof Promise});var Ym=O(()=>{});var K,Xm=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 rg(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 HS(t){return new RegExp(`^${rg(t)}$`)}function ng(t){let e=`${tg}T${rg(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 KS(t,e){return!!((e==="v4"||!e)&&MS.test(t)||(e==="v6"||!e)&&ZS.test(t))}function GS(t,e){if(!NS.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 WS(t,e){return!!((e==="v4"||!e)&&US.test(t)||(e==="v6"||!e)&&qS.test(t))}function JS(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 Kn(t){if(t instanceof kt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=xt.create(Kn(n))}return new kt({...t._def,shape:()=>e})}else return t instanceof xr?new xr({...t._def,type:Kn(t.element)}):t instanceof xt?xt.create(Kn(t.unwrap())):t instanceof lr?lr.create(Kn(t.unwrap())):t instanceof cr?cr.create(t.items.map(e=>Kn(e))):t}function ml(t,e){let r=ar(t),n=ar(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=ml(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=ml(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 og(t,e){return new wn({values:t,typeName:D.ZodEnum,...ce(e)})}function eg(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function sg(t,e={},r){return t?Lr.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=eg(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=eg(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Lr.create()}var Nt,Qm,de,AS,IS,OS,CS,zS,NS,jS,LS,DS,hl,MS,US,ZS,qS,FS,BS,tg,VS,jr,ln,un,dn,pn,Gn,fn,hn,Lr,vr,Jt,Wn,xr,kt,mn,_r,Ri,gn,cr,Pi,Jn,Yn,Ai,yn,bn,wn,_n,Dr,jt,xt,lr,vn,xn,Xn,YS,Yo,Xo,kn,XS,D,QS,ig,ag,eT,tT,cg,rT,nT,oT,sT,iT,aT,cT,lT,uT,gl,dT,pT,fT,hT,mT,gT,yT,bT,wT,_T,vT,xT,kT,$T,ST,TT,ET,RT,PT,AT,IT,OT,CT,zT,lg=O(()=>{$i();Si();Xm();fl();Wo();Nt=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(Nr(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 vt(t.common.issues);return this._error=r,this._error}}};de=class{get description(){return this._def.description}_getType(e){return ar(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:ar(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new rt,ctx:{common:e.parent.common,data:e.data,parsedType:ar(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Hn(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:ar(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:ar(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Nr(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=>Nr(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:ar(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(Hn(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:L.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 jt({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 xt.create(this,this._def)}nullable(){return lr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return xr.create(this)}promise(){return Dr.create(this,this._def)}or(e){return mn.create([this,e],this._def)}and(e){return gn.create(this,e,this._def)}transform(e){return new jt({...ce(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new vn({...ce(this._def),innerType:this,defaultValue:r,typeName:D.ZodDefault})}brand(){return new Yo({typeName:D.ZodBranded,type:this,...ce(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new xn({...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 Xo.create(this,e)}readonly(){return kn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},AS=/^c[^\s-]{8,}$/i,IS=/^[0-9a-z]+$/,OS=/^[0-9A-HJKMNP-TV-Z]{26}$/i,CS=/^[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,zS=/^[a-z0-9_-]{21}$/i,NS=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,jS=/^[-+]?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)?)??$/,LS=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,DS="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",MS=/^(?:(?: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])$/,US=/^(?:(?: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])$/,ZS=/^(([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]))$/,qS=/^(([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])$/,FS=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,BS=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,tg="((\\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])))",VS=new RegExp(`^${tg}$`);jr=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:L.invalid_type,expected:F.string,received:s.parsedType}),ee}let n=new rt,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:L.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:L.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:L.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&q(o,{code:L.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")LS.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"email",code:L.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")hl||(hl=new RegExp(DS,"u")),hl.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"emoji",code:L.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")CS.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"uuid",code:L.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")zS.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"nanoid",code:L.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")AS.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"cuid",code:L.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")IS.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"cuid2",code:L.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")OS.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"ulid",code:L.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:L.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:L.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:L.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:L.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:L.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?ng(s).test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{code:L.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?VS.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{code:L.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?HS(s).test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{code:L.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?jS.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"duration",code:L.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?KS(e.data,s.version)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"ip",code:L.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?GS(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"jwt",code:L.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?WS(e.data,s.version)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"cidr",code:L.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?FS.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"base64",code:L.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?BS.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"base64url",code:L.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:L.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}};jr.create=t=>new jr({checks:[],typeName:D.ZodString,coerce:t?.coerce??!1,...ce(t)});ln=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:L.invalid_type,expected:F.number,received:s.parsedType}),ee}let n,o=new rt;for(let s of this._def.checks)s.kind==="int"?ge.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),q(n,{code:L.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:L.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:L.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?JS(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),q(n,{code:L.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:L.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,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"&&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)}};ln.create=t=>new ln({checks:[],typeName:D.ZodNumber,coerce:t?.coerce||!1,...ce(t)});un=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 rt;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:L.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:L.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:L.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:L.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}};un.create=t=>new un({checks:[],typeName:D.ZodBigInt,coerce:t?.coerce??!1,...ce(t)});dn=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:L.invalid_type,expected:F.boolean,received:n.parsedType}),ee}return ut(e.data)}};dn.create=t=>new dn({typeName:D.ZodBoolean,coerce:t?.coerce||!1,...ce(t)});pn=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:L.invalid_type,expected:F.date,received:s.parsedType}),ee}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return q(s,{code:L.invalid_date}),ee}let n=new rt,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),q(o,{code:L.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:L.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: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}};pn.create=t=>new pn({checks:[],coerce:t?.coerce||!1,typeName:D.ZodDate,...ce(t)});Gn=class extends de{_parse(e){if(this._getType(e)!==F.symbol){let n=this._getOrReturnCtx(e);return q(n,{code:L.invalid_type,expected:F.symbol,received:n.parsedType}),ee}return ut(e.data)}};Gn.create=t=>new Gn({typeName:D.ZodSymbol,...ce(t)});fn=class extends de{_parse(e){if(this._getType(e)!==F.undefined){let n=this._getOrReturnCtx(e);return q(n,{code:L.invalid_type,expected:F.undefined,received:n.parsedType}),ee}return ut(e.data)}};fn.create=t=>new fn({typeName:D.ZodUndefined,...ce(t)});hn=class extends de{_parse(e){if(this._getType(e)!==F.null){let n=this._getOrReturnCtx(e);return q(n,{code:L.invalid_type,expected:F.null,received:n.parsedType}),ee}return ut(e.data)}};hn.create=t=>new hn({typeName:D.ZodNull,...ce(t)});Lr=class extends de{constructor(){super(...arguments),this._any=!0}_parse(e){return ut(e.data)}};Lr.create=t=>new Lr({typeName:D.ZodAny,...ce(t)});vr=class extends de{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ut(e.data)}};vr.create=t=>new vr({typeName:D.ZodUnknown,...ce(t)});Jt=class extends de{_parse(e){let r=this._getOrReturnCtx(e);return q(r,{code:L.invalid_type,expected:F.never,received:r.parsedType}),ee}};Jt.create=t=>new Jt({typeName:D.ZodNever,...ce(t)});Wn=class extends de{_parse(e){if(this._getType(e)!==F.undefined){let n=this._getOrReturnCtx(e);return q(n,{code:L.invalid_type,expected:F.void,received:n.parsedType}),ee}return ut(e.data)}};Wn.create=t=>new Wn({typeName:D.ZodVoid,...ce(t)});xr=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:L.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?L.too_big:L.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:L.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:L.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 Nt(r,i,r.path,a)))).then(i=>rt.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new Nt(r,i,r.path,a)));return rt.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)}};xr.create=(t,e)=>new xr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...ce(e)});kt=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=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:L.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 Jt&&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 Nt(o,d,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Jt){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:L.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 Nt(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,w=await u.value;l.push({key:d,value:w,alwaysSet:u.alwaysSet})}return l}).then(l=>rt.mergeObjectSync(n,l)):rt.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 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 Kn(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 xt;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return og(ge.objectKeys(this.shape))}};kt.create=(t,e)=>new kt({shape:()=>t,unknownKeys:"strip",catchall:Jt.create(),typeName:D.ZodObject,...ce(e)});kt.strictCreate=(t,e)=>new kt({shape:()=>t,unknownKeys:"strict",catchall:Jt.create(),typeName:D.ZodObject,...ce(e)});kt.lazycreate=(t,e)=>new kt({shape:t,unknownKeys:"strip",catchall:Jt.create(),typeName:D.ZodObject,...ce(e)});mn=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 vt(a.ctx.common.issues));return q(r,{code:L.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 vt(c));return q(r,{code:L.invalid_union,unionErrors:a}),ee}}get options(){return this._def.options}};mn.create=(t,e)=>new mn({options:t,typeName:D.ZodUnion,...ce(e)});_r=t=>t instanceof yn?_r(t.schema):t instanceof jt?_r(t.innerType()):t instanceof bn?[t.value]:t instanceof wn?t.options:t instanceof _n?ge.objectValues(t.enum):t instanceof vn?_r(t._def.innerType):t instanceof fn?[void 0]:t instanceof hn?[null]:t instanceof xt?[void 0,..._r(t.unwrap())]:t instanceof lr?[null,..._r(t.unwrap())]:t instanceof Yo||t instanceof kn?_r(t.unwrap()):t instanceof xn?_r(t._def.innerType):[],Ri=class t extends de{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==F.object)return q(r,{code:L.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:L.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=_r(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)})}};gn=class extends de{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Ti(s)||Ti(i))return ee;let a=ml(s.value,i.value);return a.valid?((Ei(s)||Ei(i))&&r.dirty(),{status:r.value,value:a.data}):(q(n,{code:L.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}))}};gn.create=(t,e,r)=>new gn({left:t,right:e,typeName:D.ZodIntersection,...ce(r)});cr=class t extends de{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==F.array)return q(n,{code:L.invalid_type,expected:F.array,received:n.parsedType}),ee;if(n.data.length<this._def.items.length)return q(n,{code:L.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:L.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 Nt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>rt.mergeArray(r,i)):rt.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};cr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new cr({items:t,typeName:D.ZodTuple,rest:null,...ce(e)})};Pi=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:L.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 Nt(n,a,n.path,a)),value:i._parse(new Nt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?rt.mergeObjectAsync(r,o):rt.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:jr.create(),valueType:e,typeName:D.ZodRecord,...ce(r)})}},Jn=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:L.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 Nt(n,a,n.path,[l,"key"])),value:s._parse(new Nt(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}}}};Jn.create=(t,e,r)=>new Jn({valueType:e,keyType:t,typeName:D.ZodMap,...ce(r)});Yn=class t extends de{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==F.set)return q(n,{code:L.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:L.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:L.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 Nt(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)}};Yn.create=(t,e)=>new Yn({valueType:t,minSize:null,maxSize:null,typeName:D.ZodSet,...ce(e)});Ai=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:L.invalid_type,expected:F.function,received:r.parsedType}),ee;function n(a,c){return Jo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Vn(),wr].filter(l=>!!l),issueData:{code:L.invalid_arguments,argumentsError:c}})}function o(a,c){return Jo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Vn(),wr].filter(l=>!!l),issueData:{code:L.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Dr){let a=this;return ut(async function(...c){let l=new vt([]),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 ut(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new vt([n(c,l.error)]);let u=Reflect.apply(i,this,l.data),d=a._def.returns.safeParse(u,s);if(!d.success)throw new vt([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:cr.create(e).rest(vr.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||cr.create([]).rest(vr.create()),returns:r||vr.create(),typeName:D.ZodFunction,...ce(n)})}},yn=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})}};yn.create=(t,e)=>new yn({getter:t,typeName:D.ZodLazy,...ce(e)});bn=class extends de{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return q(r,{received:r.data,code:L.invalid_literal,expected:this._def.value}),ee}return{status:"valid",value:e.data}}get value(){return this._def.value}};bn.create=(t,e)=>new bn({value:t,typeName:D.ZodLiteral,...ce(e)});wn=class t extends de{_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:L.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:L.invalid_enum_value,options:n}),ee}return ut(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})}};wn.create=og;_n=class extends de{_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:L.invalid_type}),ee}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:L.invalid_enum_value,options:o}),ee}return ut(e.data)}get enum(){return this._def.values}};_n.create=(t,e)=>new _n({values:t,typeName:D.ZodNativeEnum,...ce(e)});Dr=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:L.invalid_type,expected:F.promise,received:r.parsedType}),ee;let n=r.parsedType===F.promise?r.data:Promise.resolve(r.data);return ut(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Dr.create=(t,e)=>new Dr({type:t,typeName:D.ZodPromise,...ce(e)});jt=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"?cn(c.value):r.value==="dirty"?cn(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"?cn(a.value):r.value==="dirty"?cn(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(!Nr(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=>Nr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):ee);ge.assertNever(o)}};jt.create=(t,e,r)=>new jt({schema:t,typeName:D.ZodEffects,effect:e,...ce(r)});jt.createWithPreprocess=(t,e,r)=>new jt({schema:e,effect:{type:"preprocess",transform:t},typeName:D.ZodEffects,...ce(r)});xt=class extends de{_parse(e){return this._getType(e)===F.undefined?ut(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};xt.create=(t,e)=>new xt({innerType:t,typeName:D.ZodOptional,...ce(e)});lr=class extends de{_parse(e){return this._getType(e)===F.null?ut(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};lr.create=(t,e)=>new lr({innerType:t,typeName:D.ZodNullable,...ce(e)});vn=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}};vn.create=(t,e)=>new vn({innerType:t,typeName:D.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ce(e)});xn=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 Hn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new vt(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new vt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};xn.create=(t,e)=>new xn({innerType:t,typeName:D.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ce(e)});Xn=class extends de{_parse(e){if(this._getType(e)!==F.nan){let n=this._getOrReturnCtx(e);return q(n,{code:L.invalid_type,expected:F.nan,received:n.parsedType}),ee}return{status:"valid",value:e.data}}};Xn.create=t=>new Xn({typeName:D.ZodNaN,...ce(t)});YS=Symbol("zod_brand"),Yo=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}},Xo=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(),cn(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})}},kn=class extends de{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Nr(o)&&(o.value=Object.freeze(o.value)),o);return Hn(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};kn.create=(t,e)=>new kn({innerType:t,typeName:D.ZodReadonly,...ce(e)});XS={object:kt.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={}));QS=(t,e={message:`Input not instance of ${t.name}`})=>sg(r=>r instanceof t,e),ig=jr.create,ag=ln.create,eT=Xn.create,tT=un.create,cg=dn.create,rT=pn.create,nT=Gn.create,oT=fn.create,sT=hn.create,iT=Lr.create,aT=vr.create,cT=Jt.create,lT=Wn.create,uT=xr.create,gl=kt.create,dT=kt.strictCreate,pT=mn.create,fT=Ri.create,hT=gn.create,mT=cr.create,gT=Pi.create,yT=Jn.create,bT=Yn.create,wT=Ai.create,_T=yn.create,vT=bn.create,xT=wn.create,kT=_n.create,$T=Dr.create,ST=jt.create,TT=xt.create,ET=lr.create,RT=jt.createWithPreprocess,PT=Xo.create,AT=()=>ig().optional(),IT=()=>ag().optional(),OT=()=>cg().optional(),CT={string:(t=>jr.create({...t,coerce:!0})),number:(t=>ln.create({...t,coerce:!0})),boolean:(t=>dn.create({...t,coerce:!0})),bigint:(t=>un.create({...t,coerce:!0})),date:(t=>pn.create({...t,coerce:!0}))},zT=ee});var N={};Ho(N,{BRAND:()=>YS,DIRTY:()=>cn,EMPTY_PATH:()=>PS,INVALID:()=>ee,NEVER:()=>zT,OK:()=>ut,ParseStatus:()=>rt,Schema:()=>de,ZodAny:()=>Lr,ZodArray:()=>xr,ZodBigInt:()=>un,ZodBoolean:()=>dn,ZodBranded:()=>Yo,ZodCatch:()=>xn,ZodDate:()=>pn,ZodDefault:()=>vn,ZodDiscriminatedUnion:()=>Ri,ZodEffects:()=>jt,ZodEnum:()=>wn,ZodError:()=>vt,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>Ai,ZodIntersection:()=>gn,ZodIssueCode:()=>L,ZodLazy:()=>yn,ZodLiteral:()=>bn,ZodMap:()=>Jn,ZodNaN:()=>Xn,ZodNativeEnum:()=>_n,ZodNever:()=>Jt,ZodNull:()=>hn,ZodNullable:()=>lr,ZodNumber:()=>ln,ZodObject:()=>kt,ZodOptional:()=>xt,ZodParsedType:()=>F,ZodPipeline:()=>Xo,ZodPromise:()=>Dr,ZodReadonly:()=>kn,ZodRecord:()=>Pi,ZodSchema:()=>de,ZodSet:()=>Yn,ZodString:()=>jr,ZodSymbol:()=>Gn,ZodTransformer:()=>jt,ZodTuple:()=>cr,ZodType:()=>de,ZodUndefined:()=>fn,ZodUnion:()=>mn,ZodUnknown:()=>vr,ZodVoid:()=>Wn,addIssueToContext:()=>q,any:()=>iT,array:()=>uT,bigint:()=>tT,boolean:()=>cg,coerce:()=>CT,custom:()=>sg,date:()=>rT,datetimeRegex:()=>ng,defaultErrorMap:()=>wr,discriminatedUnion:()=>fT,effect:()=>ST,enum:()=>xT,function:()=>wT,getErrorMap:()=>Vn,getParsedType:()=>ar,instanceof:()=>QS,intersection:()=>hT,isAborted:()=>Ti,isAsync:()=>Hn,isDirty:()=>Ei,isValid:()=>Nr,late:()=>XS,lazy:()=>_T,literal:()=>vT,makeIssue:()=>Jo,map:()=>yT,nan:()=>eT,nativeEnum:()=>kT,never:()=>cT,null:()=>sT,nullable:()=>ET,number:()=>ag,object:()=>gl,objectUtil:()=>dl,oboolean:()=>OT,onumber:()=>IT,optional:()=>TT,ostring:()=>AT,pipeline:()=>PT,preprocess:()=>RT,promise:()=>$T,quotelessJson:()=>TS,record:()=>gT,set:()=>bT,setErrorMap:()=>RS,strictObject:()=>dT,string:()=>ig,symbol:()=>nT,transformer:()=>ST,tuple:()=>mT,undefined:()=>oT,union:()=>pT,unknown:()=>aT,util:()=>ge,void:()=>lT});var Ii=O(()=>{Si();fl();Ym();Wo();lg();$i()});var Qn=O(()=>{Ii();Ii()});function Oi(t){let e=yl.safeParse(t);return e.success?(e.data.inputs??[]).filter(r=>r.type==="connection"):[]}function bl(t,e){let r=yl.safeParse(t);if(!r.success)throw new Mr(`invalid manifest: ${r.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}`);if(ug.test(e))throw new Mr('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(ug.test(n))throw new Mr("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var dg,pg,yl,Mr,ug,fg=O(()=>{Qn();dg=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()}),pg=N.discriminatedUnion("type",[dg]),yl=N.object({inputs:N.array(pg).optional()}).passthrough(),Mr=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};ug=/\bconnection[_-]?id\b["']?\s*[:=]/i});var Ci,wl=O(()=>{Ci=["before_read","before_save","after_save","before_delete","after_delete","before_sync","after_sync","on_sync_failure"]});var _l,hg,mg=O(()=>{Qn();ki();wl();_l=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(Ci),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"})}),hg=Go({kind:"hook",schema:_l,factoryName:"defineHook"})});var gg=O(()=>{mg();wl()});var zi,vl=O(()=>{zi=["after_canonicalize_inbound","after_sync_success_outbound"]});var xl,yg,bg=O(()=>{Qn();ki();vl();xl=N.object({id:N.string().min(1,"conduit id must be non-empty"),on:N.enum(zi),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"})}),yg=Go({kind:"conduit",schema:xl,factoryName:"defineConduit"})});var wg=O(()=>{bg();vl()});async function MT(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 Ni(t,e={}){return(e.transform??MT)(t)}var kl=O(()=>{});function $l(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 _g(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Sl(t){return`${_g(t.source)}${_g(t.recordType)}`}function UT(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function ZT(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 Tl(t){let e=Sl(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=yl(s.pgType),a=s.nullable?"?":"",c=s.nullable?" | null":"";return` /** ${kT(s)} */
32
- ${xT(s.name)}${a}: ${i}${c};`});return`${n}
31
+ }`;let o=t.columns.map(s=>{let i=$l(s.pgType),a=s.nullable?"?":"",c=s.nullable?" | null":"";return` /** ${ZT(s)} */
32
+ ${UT(s.name)}${a}: ${i}${c};`});return`${n}
33
33
  export interface ${e} {
34
34
  ${o.join(`
35
35
  `)}
36
- }`}function zi(t){return[...t.records].sort((n,o)=>`${n.source}:${n.recordType}`.localeCompare(`${o.source}:${o.recordType}`)).map(wl).join(`
36
+ }`}function ji(t){return[...t.records].sort((n,o)=>`${n.source}:${n.recordType}`.localeCompare(`${o.source}:${o.recordType}`)).map(Tl).join(`
37
37
 
38
- `)}function fg(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 _l(t){let e=fg(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 vl=O(()=>{});function ST(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function hg(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 Lr(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let r=ST(t.baseUrl),n=await hg(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=zi(n),s=[TT,"// ----- Record shapes (from /v1/catalog/records) -----",o,"// ----- Keyset seek keys (derived from column nullability) -----",_l(n)];if(!t.recordsOnly){let i=await hg(r.openapi,t.token,e),a=await Ci(i,t.openApi);s.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return s.join(`
38
+ `)}function vg(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 qT(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function El(t){let e=vg(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` ${qT(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 Rl=O(()=>{});function FT(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function xg(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 Ur(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let r=FT(t.baseUrl),n=await xg(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=ji(n),s=[BT,"// ----- Record shapes (from /v1/catalog/records) -----",o,"// ----- Keyset seek keys (derived from column nullability) -----",El(n)];if(!t.recordsOnly){let i=await xg(r.openapi,t.token,e),a=await Ni(i,t.openApi);s.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return s.join(`
40
40
 
41
41
  `)+`
42
- `}var TT,mg=O(()=>{gl();vl();vl();gl();TT=["/**"," * 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 xl=O(()=>{vi();sg();cg();dg();mg()});import{homedir as ET}from"node:os";import{join as gg}from"node:path";import{promises as kl}from"node:fs";function jt(t){return t.trim().replace(/\/+$/,"")}function Ni(){let t=process.env.TURBOBASE_HOME??gg(ET(),".turbobase");return{dir:t,file:gg(t,"credentials")}}function yg(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function Xo(){let{file:t}=Ni(),e;try{let s=await kl.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))yg(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))yg(i)&&(n[s]={token:i.token,updatedAt:i.updatedAt});return{active:RT(n),tenants:n}}function RT(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 $l(t){let{dir:e,file:r}=Ni();await kl.mkdir(e,{recursive:!0,mode:448}),await kl.writeFile(r,JSON.stringify(t,null,2)+`
44
- `,{mode:384})}async function bg(t){let e=jt(t.baseUrl),r=await Xo(),n=new Date().toISOString();return r.tenants[e]={token:t.token,updatedAt:n},r.active=e,await $l(r),{baseUrl:e,token:t.token,updatedAt:n}}async function Jt(t){let e=await Xo();if(t){let s=jt(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 ji(t){let e=jt(t),r=await Xo(),n=r.tenants[e];return n?(r.active=e,await $l(r),{baseUrl:e,token:n.token,updatedAt:n.updatedAt}):null}async function Sl(t){let e=await Xo(),r=t?jt(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 $l(e),r}async function xr(){let t=await Xo();return Object.entries(t.tenants).map(([e,r])=>({baseUrl:e,token:r.token,updatedAt:r.updatedAt}))}var Qo=O(()=>{});function wg(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 _g(t){return t.replace(/\/+$/,"")}function Tl(t=process.env){let e=(t[Qn]??"").trim(),r=(t[Li]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function El(t){let e;try{e=new URL(t)}catch{return`${Qn} 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:`${Qn} 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 ge,Q,Qn,Li,es,Dr=O(()=>{ge=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=_g(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=wg(a);throw new ge(`${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`)}},Qn="TURBOBASE_REGISTRY_URL",Li="TURBOBASE_REGISTRY_TOKEN";es=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=_g(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=wg(a);throw new ge(`${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 AT(t){if(PT.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function OT(){return{name:"extension-self-contained-fence",setup(t){t.onResolve({filter:/.*/},e=>e.kind==="entry-point"?null:AT(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:")||zT(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:IT,loader:"js"}))}}}function zT(t){let e=t.startsWith("node:")?t.slice(5):t;return CT.has(e.split("/")[0])}function vg(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 NT(){try{return(await import("esbuild")).build}catch(t){throw vg("esbuild",t)}}async function jT(){try{return(await import("isolated-vm")).default}catch(t){throw vg("isolated-vm",t)}}async function Di(t){let e=await NT(),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:[OT()]})}catch(n){let s=n.errors?.map(i=>i.text).filter(Boolean).join("; ");throw new Rl(s||`extension bundle failed: ${String(n)}`)}return r.outputFiles?.[0]?.text??""}async function ts(t,e,r={}){let n=r.timeoutMs??200,o=r.memoryLimitMb??16,s=r.member??"run",i={patches:[],logs:[]},a=await jT(),c=new a.Isolate({memoryLimit:o});try{let l=await c.createContext(),u=l.global,d=new a.Callback(P=>{let z=JSON.parse(String(P));i.rejection||(i.rejection=z)}),b=new a.Callback(P=>{i.patches.push(JSON.parse(String(P)))}),m=new a.Callback(P=>{let z=JSON.parse(String(P));i.logs.push(z)}),f=new a.Callback(P=>{i.result=JSON.parse(String(P))});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(LT(e)));let y=DT(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 LT(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 DT(t,e){return`
42
+ `}var BT,kg=O(()=>{kl();Rl();Rl();kl();BT=["/**"," * 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(()=>{ki();fg();gg();wg();kg()});import{homedir as VT}from"node:os";import{join as $g}from"node:path";import{promises as Al}from"node:fs";function Lt(t){return t.trim().replace(/\/+$/,"")}function Li(){let t=process.env.TURBOBASE_HOME??$g(VT(),".turbobase");return{dir:t,file:$g(t,"credentials")}}function Sg(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function Qo(){let{file:t}=Li(),e;try{let s=await Al.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:HT(n),tenants:n}}function HT(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 Il(t){let{dir:e,file:r}=Li();await Al.mkdir(e,{recursive:!0,mode:448}),await Al.writeFile(r,JSON.stringify(t,null,2)+`
44
+ `,{mode:384})}async function Tg(t){let e=Lt(t.baseUrl),r=await Qo(),n=new Date().toISOString();return r.tenants[e]={token:t.token,updatedAt:n},r.active=e,await Il(r),{baseUrl:e,token:t.token,updatedAt:n}}async function Yt(t){let e=await Qo();if(t){let s=Lt(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 Di(t){let e=Lt(t),r=await Qo(),n=r.tenants[e];return n?(r.active=e,await Il(r),{baseUrl:e,token:n.token,updatedAt:n.updatedAt}):null}async function Ol(t){let e=await Qo(),r=t?Lt(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 Il(e),r}async function kr(){let t=await Qo();return Object.entries(t.tenants).map(([e,r])=>({baseUrl:e,token:r.token,updatedAt:r.updatedAt}))}var es=O(()=>{});function Eg(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 Rg(t){return t.replace(/\/+$/,"")}function Cl(t=process.env){let e=(t[eo]??"").trim(),r=(t[Mi]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function zl(t){let e;try{e=new URL(t)}catch{return`${eo} 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:`${eo} 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 pe,X,eo,Mi,ts,$r=O(()=>{pe=class extends Error{constructor(r,n,o){super(r);this.status=n;this.body=o;this.name="ApiError"}status;body};X=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=Rg(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=Eg(a);throw new pe(`${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 proposals(e={}){let r=new URLSearchParams;e.status?.length&&r.set("status",e.status.join(",")),e.provenance?.length&&r.set("provenance",e.provenance.join(",")),e.recordType&&r.set("recordType",e.recordType),e.source&&r.set("source",e.source),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString();return(await this.request("GET",`/v1/extensions/proposals${n?`?${n}`:""}`)).proposals??[]}proposalPromote(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/promote`,{})}proposalRetract(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/retract`,{})}proposalReject(e,r){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/reject`,r?{reason:r}:{})}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)}guardrailPostureGet(){return this.request("GET","/v1/guardrails/posture")}guardrailPostureSet(e){return this.request("PUT","/v1/guardrails/posture",{mode: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`)}},eo="TURBOBASE_REGISTRY_URL",Mi="TURBOBASE_REGISTRY_TOKEN";ts=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=Rg(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=Eg(a);throw new pe(`${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 GT(t){if(KT.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function JT(){return{name:"extension-self-contained-fence",setup(t){t.onResolve({filter:/.*/},e=>e.kind==="entry-point"?null:GT(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:")||XT(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:WT,loader:"js"}))}}}function XT(t){let e=t.startsWith("node:")?t.slice(5):t;return YT.has(e.split("/")[0])}function Pg(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 QT(){try{return(await import("esbuild")).build}catch(t){throw Pg("esbuild",t)}}async function e0(){try{return(await import("isolated-vm")).default}catch(t){throw Pg("isolated-vm",t)}}async function Ui(t){let e=await QT(),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:[JT()]})}catch(n){let s=n.errors?.map(i=>i.text).filter(Boolean).join("; ");throw new Nl(s||`extension bundle failed: ${String(n)}`)}return r.outputFiles?.[0]?.text??""}async function rs(t,e,r={}){let n=r.timeoutMs??200,o=r.memoryLimitMb??16,s=r.member??"run",i={patches:[],logs:[]},a=await e0(),c=new a.Isolate({memoryLimit:o});try{let l=await c.createContext(),u=l.global,d=new a.Callback(P=>{let z=JSON.parse(String(P));i.rejection||(i.rejection=z)}),w=new a.Callback(P=>{i.patches.push(JSON.parse(String(P)))}),m=new a.Callback(P=>{let z=JSON.parse(String(P));i.logs.push(z)}),f=new a.Callback(P=>{i.result=JSON.parse(String(P))});await u.set("__tb_reject",d),await u.set("__tb_patch",w),await u.set("__tb_log",m),await u.set("__tb_result",f),await u.set("__tb_ctx_json",JSON.stringify(t0(e)));let b=r0(t,s),E=await(await c.compileScript(b)).run(l,{timeout:n,promise:!0});return s==="when"?{effects:i,whenResult:!!E}:{effects:i}}finally{c.isDisposed||c.dispose()}}function t0(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 r0(t,e){return`
45
45
  "use strict";
46
46
  (async () => {
47
47
  const __tb_ctx = JSON.parse(__tb_ctx_json);
@@ -110,36 +110,36 @@ ${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 PT,IT,Rl,CT,Pl=O(()=>{PT=new Set(["@/sync/hooks","@/sync/hooks/index.js","@/sync/conduits","@/sync/conduits/index.js","@turbobase/extensions","@turbobase/extensions/hook","@turbobase/extensions/conduit"]);IT=`
113
+ `}var KT,WT,Nl,YT,jl=O(()=>{KT=new Set(["@/sync/hooks","@/sync/hooks/index.js","@/sync/conduits","@/sync/conduits/index.js","@turbobase/extensions","@turbobase/extensions/hook","@turbobase/extensions/conduit"]);WT=`
114
114
  export const defineHook = (def) => def;
115
115
  export const defineConduit = (def) => def;
116
116
  export default defineHook;
117
- `,Rl=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};CT=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 Al}from"node:fs";import{join as MT}from"node:path";function UT(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 ZT(t,e,r){let n=e.name??r,o=e.expect??"pass";try{let{effects:s}=await ts(t,UT(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 Mi(t,e){let r=await Di(t),n=[];for(let o=0;o<e.length;o+=1)n.push(await ZT(r,e[o],`sample[${o}]`));return n}async function rs(t){let e;try{e=await Al.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 Al.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 ns(t){return Al.readFile(t,"utf8")}var Il=O(()=>{Pl()});function qr(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function b0(t){let e=t.recordType;if(!e)throw new Ut("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
+ `,Nl=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};YT=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 Ll}from"node:fs";import{join as n0}from"node:path";function o0(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 s0(t,e,r){let n=e.name??r,o=e.expect??"pass";try{let{effects:s}=await rs(t,o0(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 Zi(t,e){let r=await Ui(t),n=[];for(let o=0;o<e.length;o+=1)n.push(await s0(r,e[o],`sample[${o}]`));return n}async function ns(t){let e;try{e=await Ll.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 Ll.readFile(n0(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 os(t){return Ll.readFile(t,"utf8")}var Dl=O(()=>{jl()});function Fr(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function j0(t){let e=t.recordType;if(!e)throw new Zt("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 Ut("require-field template needs --field=<name>");i=`
122
+ },`,a="custom";else if(n==="require-field"){let w=t.field;if(!w)throw new Zt("require-field template needs --field=<name>");i=`
123
123
  run: (ctx) => {
124
- const v = ctx.payload[${JSON.stringify(b)}];
124
+ const v = ctx.payload[${JSON.stringify(w)}];
125
125
  if (v === undefined || v === null || v === '') {
126
126
  ctx.reject({
127
127
  code: 'MANDATORY_FIELD_MISSING',
128
- field: ${JSON.stringify(b)},
129
- message: ${JSON.stringify(`${b} is required`)},
128
+ field: ${JSON.stringify(w)},
129
+ message: ${JSON.stringify(`${w} is required`)},
130
130
  });
131
131
  }
132
- },`,a=`require-field-${b}`}else if(n==="enforce-format"){let b=t.field;if(!b)throw new Ut("enforce-format template needs --field=<name>");if(!t.regex)throw new Ut("enforce-format template needs --regex=<pattern>");i=`
132
+ },`,a=`require-field-${w}`}else if(n==="enforce-format"){let w=t.field;if(!w)throw new Zt("enforce-format template needs --field=<name>");if(!t.regex)throw new Zt("enforce-format template needs --regex=<pattern>");i=`
133
133
  run: (ctx) => {
134
- const v = ctx.payload[${JSON.stringify(b)}];
134
+ const v = ctx.payload[${JSON.stringify(w)}];
135
135
  if (typeof v === 'string' && v && !/${t.regex}/.test(v)) {
136
136
  ctx.reject({
137
137
  code: 'INVALID_FORMAT',
138
- field: ${JSON.stringify(b)},
139
- message: ${JSON.stringify(`${b} does not match expected format`)},
138
+ field: ${JSON.stringify(w)},
139
+ message: ${JSON.stringify(`${w} does not match expected format`)},
140
140
  });
141
141
  }
142
- },`,a=`enforce-format-${b}`}else throw new Ut(`unsupported template: ${n}. Supported: require-field | enforce-format | blank.`);let c=t.id??`custom:${e}:${a}${t.regex?`-${qr(t.regex).slice(0,24)}`:""}`,u=`/**
142
+ },`,a=`enforce-format-${w}`}else throw new Zt(`unsupported template: ${n}. Supported: require-field | enforce-format | blank.`);let c=t.id??`custom:${e}:${a}${t.regex?`-${Fr(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 w0(t){let e=t.recordType;if(!e)throw new Ut("record type is required (e.g. --record=order)");let r=t.source;if(!r)throw new Ut("--source is required (the origin source, e.g. --source=shopify)");let n=t.to;if(!n)throw new Ut("--to is required (the target source, e.g. --to=netsuite)");if(r===n)throw new Ut(`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??`${qr(r)}2${qr(n)}:${qr(e)}`,c=`/**
155
+ `;return{relativePath:`hooks/${e}/${r}.${a}.ts`,content:u}}function L0(t){let e=t.recordType;if(!e)throw new Zt("record type is required (e.g. --record=order)");let r=t.source;if(!r)throw new Zt("--source is required (the origin source, e.g. --source=shopify)");let n=t.to;if(!n)throw new Zt("--to is required (the target source, e.g. --to=netsuite)");if(r===n)throw new Zt(`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??`${Fr(r)}2${Fr(n)}:${Fr(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/${qr(r)}-${qr(e)}-to-${qr(n)}-${qr(o)}.ts`,content:c}}function no(t,e){let r=_0[t];if(!r)throw new Ut(`unknown extension kind '${t}'. Scaffoldable kinds: ${Hg.join(", ")}.`);return r(e)}var Hg,Ut,_0,Dl=O(()=>{Hg=["hook","conduit"];Ut=class extends Error{};_0={hook:b0,conduit:w0}});function eR(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 tR(t){return Fy[eR(t)%Fy.length]}function rR(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 By(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Vy(t,e){let[r,n]=tR(t),o=By(rR(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${By(e)}">
198
+ `;return{relativePath:`conduits/${Fr(r)}-${Fr(e)}-to-${Fr(n)}-${Fr(o)}.ts`,content:c}}function Br(t,e){let r=D0[t];if(!r)throw new Zt(`unknown extension kind '${t}'. Scaffoldable kinds: ${ey.join(", ")}.`);return r(e)}var ey,Zt,D0,Vi=O(()=>{ey=["hook","conduit"];Zt=class extends Error{};D0={hook:j0,conduit:L0}});function RR(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 PR(t){return ab[RR(t)%ab.length]}function AR(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 cb(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function lb(t,e){let[r,n]=PR(t),o=cb(AR(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${cb(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 Fy,Hy=O(()=>{Fy=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var Ky,Gy=O(()=>{Ky=Object.freeze({instance:!0,platform:!0,share:"inherit"})});var rb={};Vo(rb,{MAIN_TSX:()=>eb,STYLES_CSS:()=>tb,TSCONFIG:()=>Xy,TURBOBASE_CLIENT:()=>Wy,indexHtml:()=>Qy,instanceOriginFromEnv:()=>lR,packageJson:()=>Jy,scaffoldAppFiles:()=>dR,starterApp:()=>pR,viteConfig:()=>Yy});function oR(t){let e={name:t.title},r=(t.description??"").trim().slice(0,nR);return r&&(e.description=r),e.icon="favicon.svg",e.learnings={...Ky},JSON.stringify(e,null,2)+`
209
- `}function Jy(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview",pretest:sR},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 cR(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 lR(t=process.env){let e=(t.TENANT_SLUG??"").trim(),r=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!r))return`https://${e}.${r}`}function Yy(t,e={}){let r=cR(e.instanceOrigin);return`import { defineConfig } from 'vite';
208
+ `}var ab,ub=O(()=>{ab=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var db,pb=O(()=>{db=Object.freeze({instance:!0,platform:!0,share:"inherit"})});var _b={};Ho(_b,{MAIN_TSX:()=>bb,STYLES_CSS:()=>wb,TSCONFIG:()=>gb,TURBOBASE_CLIENT:()=>fb,indexHtml:()=>yb,instanceOriginFromEnv:()=>LR,packageJson:()=>hb,scaffoldAppFiles:()=>MR,starterApp:()=>UR,viteConfig:()=>mb});function OR(t){let e={name:t.title},r=(t.description??"").trim().slice(0,IR);return r&&(e.description=r),e.icon="favicon.svg",e.learnings={...db},JSON.stringify(e,null,2)+`
209
+ `}function hb(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview",pretest:CR},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 jR(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 LR(t=process.env){let e=(t.TENANT_SLUG??"").trim(),r=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!r))return`https://${e}.${r}`}function mb(t,e={}){let r=jR(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??iR}'; // /rest + the Realtime WS
225
- const API = process.env.TURBOBASE_API_URL || '${r??aR}'; // /v1, /auth, /login, /_app
224
+ const TENANT = process.env.SUPABASE_URL || '${r??zR}'; // /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 Qy(t){return`<!doctype html>
257
+ `}function yb(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 dR(t){return{"package.json":Jy(t.slug),"vite.config.ts":Yy(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":uR,"tsconfig.json":Xy,"index.html":Qy(t.title),"public/turbobase.json":oR(t),"public/favicon.svg":Vy(t.slug,t.title),"src/main.tsx":eb,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":Wy,"src/styles.css":tb,"README.md":`# ${t.title}
270
+ `}function MR(t){return{"package.json":hb(t.slug),"vite.config.ts":mb(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":DR,"tsconfig.json":gb,"index.html":yb(t.title),"public/turbobase.json":OR(t),"public/favicon.svg":lb(t.slug,t.title),"src/main.tsx":bb,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":fb,"src/styles.css":wb,"README.md":`# ${t.title}
271
271
 
272
272
  \`\`\`sh
273
273
  npm install
@@ -288,33 +288,153 @@ 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 pR(t){return`import React from 'react';
292
- import { select } from './lib/turbobase';
291
+ `}}function UR(t){return`import React from 'react';
292
+ import { select, write, del } from './lib/turbobase';
293
293
 
294
- /** Swap for any record type \u2014 GET /v1/catalog/records lists what this instance has. */
294
+ /** Swap for any record type \u2014 GET /v1/catalog/records lists what this instance has.
295
+ * \`hooks/\` in this project carries a \`before_save\` example for the same one. */
295
296
  const RECORD_TYPE = 'customer';
296
297
 
298
+ /** Project the columns you render. Never \`select=*\` on a mirrored table \u2014 it
299
+ * drags the whole \`raw\` source document down with every row. */
300
+ const COLUMNS = 'pg_row_id,company_name,email';
301
+
302
+ type Row = { pg_row_id: string; company_name: string | null; email: string | null };
303
+
304
+ const message = (e: unknown): string => (e instanceof Error ? e.message : String(e));
305
+ const label = (r: Row): string => r.company_name ?? r.email ?? r.pg_row_id;
306
+
297
307
  export default function App() {
298
- const [rows, setRows] = React.useState<Record<string, unknown>[]>([]);
308
+ const [rows, setRows] = React.useState<Row[]>([]);
299
309
  const [error, setError] = React.useState<string | null>(null);
310
+ const [note, setNote] = React.useState<string | null>(null);
311
+ const [editing, setEditing] = React.useState<{ pgRowId: string; email: string } | null>(null);
312
+ const [busy, setBusy] = React.useState(false);
313
+
314
+ // Reads are RLS-scoped to the signed-in user \u2014 no key, no token handling. A
315
+ // tombstoned row is hidden by a restrictive policy, so a deleted row simply
316
+ // stops coming back rather than needing a filter here.
317
+ const refresh = React.useCallback(
318
+ () => select<Row>(\`\${RECORD_TYPE}?select=\${COLUMNS}&limit=25\`).then(setRows),
319
+ [],
320
+ );
300
321
 
301
322
  React.useEffect(() => {
302
- // Reads are RLS-scoped to the signed-in user \u2014 no key, no token handling.
303
- select<Record<string, unknown>>(\`\${RECORD_TYPE}?select=*&limit=25\`)
304
- .then(setRows)
305
- .catch((e: unknown) => setError(e instanceof Error ? e.message : String(e)));
306
- }, []);
323
+ refresh().catch((e: unknown) => setError(message(e)));
324
+ }, [refresh]);
325
+
326
+ /** Run one mutation and report what actually happened. Every refusal below
327
+ * arrives as a THROW \u2014 a guardrail denial, a hook \`ctx.reject\`, a source that
328
+ * will not accept the operation \u2014 so nothing is quietly swallowed. */
329
+ async function run(mutate: () => Promise<string>): Promise<void> {
330
+ setBusy(true);
331
+ setError(null);
332
+ setNote(null);
333
+ try {
334
+ const outcome = await mutate();
335
+ await refresh();
336
+ setNote(outcome);
337
+ } catch (e: unknown) {
338
+ setError(message(e));
339
+ } finally {
340
+ setBusy(false);
341
+ }
342
+ }
343
+
344
+ /** EDIT \u2014 through \`POST /v1/data/<recordType>\`, the canonical write boundary.
345
+ * Not a PostgREST write: \`authenticated\` holds no UPDATE on the mirror, so
346
+ * that path is a 42501 whatever the query says. This one runs the record
347
+ * type's \`before_save\` hooks, which is where validation belongs \u2014 a rule
348
+ * enforced in this component is bypassed by the chat agent, an MCP client and
349
+ * the next app to touch the row. The scaffolded hook rejects a malformed
350
+ * email, so typing one here surfaces its rejection in the banner below. */
351
+ const saveEmail = (row: Row, email: string): Promise<void> =>
352
+ run(async () => {
353
+ const res = await write<{ row: { pg_row_id: string | null; external_id: string | null } }>(
354
+ RECORD_TYPE,
355
+ { pgRowId: row.pg_row_id, parent: { email } },
356
+ );
357
+ setEditing(null);
358
+ return \`write() accepted row \${res.row.pg_row_id ?? '(unkeyed)'} \u2014 the source write is queued, not confirmed.\`;
359
+ });
360
+
361
+ /** DELETE \u2014 through \`DELETE /v1/data/<recordType>\`. Destructive, so it is
362
+ * gated harder than a write: it needs a \`<recordType>.delete\` guardrail
363
+ * allow (a \`.write\` allow does NOT cover delete), is denied outright under
364
+ * deny-by-default, and is capped by the per-minute/hour/day delete rate
365
+ * limit. Any of those, or a source with delete-to-source parked, throws. */
366
+ const remove = (row: Row): Promise<void> =>
367
+ run(async () => {
368
+ const result = await del(RECORD_TYPE, { pgRowId: row.pg_row_id });
369
+ const { enqueued } = result;
370
+ // \`deleted\` is the LOCAL tombstone. \`enqueued\` is whether a source delete
371
+ // was queued behind it \u2014 false means the row had never synced upstream, so
372
+ // there was nothing to delete there. enqueued=true is NOT "the source
373
+ // deleted it": that leg can still be held for operator approval (a
374
+ // require_confirm guardrail) or refused by the source (dependent records,
375
+ // a required deletion reason), and either way the failure surfaces as a
376
+ // sync_failure rather than here.
377
+ return \`del() \u2192 \${JSON.stringify(result)} \u2014 \${
378
+ enqueued
379
+ ? 'the source delete is QUEUED; it can still be held for approval or refused upstream, so watch sync failures.'
380
+ : 'nothing was queued; this row had never synced upstream, so the tombstone is purely local.'
381
+ }\`;
382
+ });
307
383
 
308
384
  return (
309
- <main style={{ padding: 24 }}>
385
+ <main style={{ padding: 24, maxWidth: 760 }}>
310
386
  <h1>${t}</h1>
311
- {error && <p style={{ color: 'crimson' }}>{error}</p>}
387
+ {error && <p role="alert" style={{ color: 'crimson' }}>{error}</p>}
388
+ {note && <p style={{ color: '#166534' }}>{note}</p>}
312
389
  <p>{rows.length} {RECORD_TYPE} row(s), scoped to you.</p>
313
- <pre>{JSON.stringify(rows.slice(0, 3), null, 2)}</pre>
390
+ <ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
391
+ {rows.map((row) => {
392
+ const edit = editing && editing.pgRowId === row.pg_row_id ? editing : null;
393
+ return (
394
+ <li key={row.pg_row_id} style={{ borderTop: '1px solid #e2e8f0', padding: '8px 0' }}>
395
+ <strong>{label(row)}</strong>{' '}
396
+ <span style={{ color: '#64748b' }}>{row.email ?? 'no email'}</span>{' '}
397
+ {edit ? (
398
+ <>
399
+ <input
400
+ value={edit.email}
401
+ placeholder="email"
402
+ onChange={(e) => setEditing({ pgRowId: row.pg_row_id, email: e.target.value })}
403
+ />
404
+ <button disabled={busy} onClick={() => void saveEmail(row, edit.email)}>Save</button>
405
+ <button disabled={busy} onClick={() => setEditing(null)}>Cancel</button>
406
+ </>
407
+ ) : (
408
+ <>
409
+ <button
410
+ disabled={busy}
411
+ onClick={() => setEditing({ pgRowId: row.pg_row_id, email: row.email ?? '' })}
412
+ >
413
+ Edit email
414
+ </button>
415
+ <button
416
+ disabled={busy}
417
+ onClick={() => {
418
+ // Destructive and real: this deletes upstream too, subject
419
+ // to the guardrails above. Confirm before firing it.
420
+ if (window.confirm(\`Delete \${label(row)}?\`)) void remove(row);
421
+ }}
422
+ >
423
+ Delete
424
+ </button>
425
+ </>
426
+ )}
427
+ </li>
428
+ );
429
+ })}
430
+ </ul>
431
+ {rows.length === 0 && !error && (
432
+ <p>Nothing to show \u2014 sync a {RECORD_TYPE}, or point RECORD_TYPE at a record this instance has.</p>
433
+ )}
314
434
  </main>
315
435
  );
316
436
  }
317
- `}var nR,Wy,ps,sR,iR,aR,uR,Xy,eb,tb,nb=O(()=>{Hy();Gy();nR=200;Wy=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
437
+ `}var IR,fb,fs,CR,zR,NR,DR,gb,bb,wb,vb=O(()=>{ub();pb();IR=200;fb=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
318
438
  // Reads go through PostgREST (RLS-scoped); writes go through POST /v1/data/<recordType>.
319
439
  // A cold first paint that fans out many reads should use batch() \u2014 ONE request
320
440
  // that multiplexes them, sidestepping the per-request rate limiter.
@@ -603,6 +723,31 @@ export async function write<T = unknown>(recordType: string, body: unknown): Pro
603
723
  return (await res.json()) as T;
604
724
  }
605
725
 
726
+ /** Delete a record through the canonical boundary DELETE /v1/data/<recordType>.
727
+ * Identify the row by \`pgRowId\` OR \`externalId\` (one is required). NEVER issue a
728
+ * hard SQL DELETE against a table \u2014 apps hold no DELETE grant, and it would not
729
+ * propagate to the source.
730
+ *
731
+ * What happens: the row is soft-deleted (tombstoned) locally, and \u2014 for a
732
+ * bidirectional, delete-capable source (NetSuite today; others parked) \u2014 the
733
+ * delete is queued to the source. Deletes are gated as a DESTRUCTIVE op: they
734
+ * need a \`<record>.delete\` guardrail allow (a \`.write\` allow does NOT cover
735
+ * delete), are denied under deny-by-default, and are capped by the per-minute/
736
+ * hour/day delete rate limit. A parked source, a denied guardrail, or a source
737
+ * that refuses the delete (e.g. NetSuite deletion-reason / has-dependents) fails
738
+ * LOUDLY \u2014 this throws, or the sync surfaces a \`sync_failure\`; nothing is
739
+ * silently upserted. Returns \`{ deleted, enqueued }\`: \`enqueued\` is false when
740
+ * the row never synced upstream (a purely local tombstone). */
741
+ export async function del(
742
+ recordType: string,
743
+ key: { pgRowId: string } | { externalId: string },
744
+ ): Promise<{ deleted: boolean; enqueued: boolean }> {
745
+ const q = 'pgRowId' in key ? \`pgRowId=\${encodeURIComponent(key.pgRowId)}\` : \`externalId=\${encodeURIComponent(key.externalId)}\`;
746
+ const res = await req(\`/v1/data/\${recordType}?\${q}\`, { method: 'DELETE' });
747
+ if (!res.ok) throw new Error(await readError(res));
748
+ return (await res.json()) as { deleted: boolean; enqueued: boolean };
749
+ }
750
+
606
751
  /** One sub-result from batch(): its own status, so a 429/5xx on one query does
607
752
  * not fail the others. \`ok\` is status 2xx; \`rows\` is the parsed body on
608
753
  * success (undefined on failure \u2014 read \`status\`/\`error\`). */
@@ -1071,7 +1216,7 @@ export async function selectPage<T = unknown>(
1071
1216
  }
1072
1217
  return { rows, nextCursor };
1073
1218
  }
1074
- `,ps="src/types.ts",sR=`turbobase project types -o ${ps} || node -e "if(require('node:fs').existsSync('${ps}')){console.error('turbobase: could not refresh ${ps} (offline or signed out) - testing against the copy on disk, which may be stale.')}else{console.error('turbobase: ${ps} 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 ${ps}');process.exit(1)}"`;iR="http://localhost:54331",aR="http://localhost:4100";uR=`node_modules/
1219
+ `,fs="src/types.ts",CR=`turbobase project types -o ${fs} || node -e "if(require('node:fs').existsSync('${fs}')){console.error('turbobase: could not refresh ${fs} (offline or signed out) - testing against the copy on disk, which may be stale.')}else{console.error('turbobase: ${fs} 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 ${fs}');process.exit(1)}"`;zR="http://localhost:54331",NR="http://localhost:4100";DR=`node_modules/
1075
1220
  dist/
1076
1221
  build/
1077
1222
 
@@ -1083,8 +1228,8 @@ build/
1083
1228
  !.env.example
1084
1229
 
1085
1230
  .DS_Store
1086
- `,Xy=`${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
- `;eb=`import React from 'react';
1231
+ `,gb=`${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)}
1232
+ `;bb=`import React from 'react';
1088
1233
  import { createRoot } from 'react-dom/client';
1089
1234
  import App from './App';
1090
1235
  import './styles.css';
@@ -1094,80 +1239,80 @@ createRoot(document.getElementById('root')!).render(
1094
1239
  <App />
1095
1240
  </React.StrictMode>,
1096
1241
  );
1097
- `,tb=`:root { color-scheme: light; font-family: ui-sans-serif, system-ui, sans-serif; }
1242
+ `,wb=`:root { color-scheme: light; font-family: ui-sans-serif, system-ui, sans-serif; }
1098
1243
  * { box-sizing: border-box; }
1099
1244
  body { margin: 0; background: #f8fafc; color: #0f172a; }
1100
- `});var fs=O(()=>{Pi()});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 At(t){return t&&Object.assign(Wi,t),Wi}var hR,Sr,Wi,lo=O(()=>{hR=Object.freeze({status:"aborted"});Sr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Wi={}});var be={};Vo(be,{BIGINT_FORMAT_RANGES:()=>sb,Class:()=>ru,NUMBER_FORMAT_RANGES:()=>lu,aborted:()=>Sn,allowsEval:()=>iu,assert:()=>wR,assertEqual:()=>mR,assertIs:()=>yR,assertNever:()=>bR,assertNotEqual:()=>gR,assignProp:()=>su,cached:()=>gs,captureStackTrace:()=>Yi,cleanEnum:()=>OR,cleanRegex:()=>bs,clone:()=>It,createTransparentProxy:()=>SR,defineLazy:()=>Ce,esc:()=>$n,escapeRegex:()=>Fr,extend:()=>RR,finalizeIssue:()=>Yt,floatSafeRemainder:()=>ou,getElementAtPath:()=>_R,getEnumValues:()=>ms,getLengthableOrigin:()=>ws,getParsedType:()=>$R,getSizableOrigin:()=>ib,isObject:()=>uo,isPlainObject:()=>po,issue:()=>uu,joinValues:()=>Ji,jsonStringifyReplacer:()=>nu,merge:()=>PR,normalizeParams:()=>te,nullish:()=>ys,numKeys:()=>kR,omit:()=>ER,optionalKeys:()=>cu,partial:()=>AR,pick:()=>TR,prefixIssues:()=>lr,primitiveTypes:()=>ob,promiseAllObject:()=>vR,propertyKeyTypes:()=>au,randomString:()=>xR,required:()=>IR,stringifyPrimitive:()=>Xi,unwrapMessage:()=>hs});function mR(t){return t}function gR(t){return t}function yR(t){}function bR(t){throw new Error}function wR(t){}function ms(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 Ji(t,e="|"){return t.map(r=>Xi(r)).join(e)}function nu(t,e){return typeof e=="bigint"?e.toString():e}function gs(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function ys(t){return t==null}function bs(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function ou(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 Ce(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 su(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function _R(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function vR(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 xR(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function $n(t){return JSON.stringify(t)}function uo(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function po(t){if(uo(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(uo(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function kR(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function Fr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function It(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 SR(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 Xi(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function cu(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function TR(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 It(t,{...t._zod.def,shape:r,checks:[]})}function ER(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 It(t,{...t._zod.def,shape:r,checks:[]})}function RR(t,e){if(!po(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 su(this,"shape",n),n},checks:[]};return It(t,r)}function PR(t,e){return It(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return su(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function AR(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 It(e,{...e._zod.def,shape:o,checks:[]})}function IR(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 It(e,{...e._zod.def,shape:o,checks:[]})}function Sn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function lr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function hs(t){return typeof t=="string"?t:t?.message}function Yt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=hs(t.inst?._zod.def?.error?.(t))??hs(e?.error?.(t))??hs(r.customError?.(t))??hs(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function ib(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function ws(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function uu(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function OR(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Yi,iu,$R,au,ob,lu,sb,ru,ur=O(()=>{Yi=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};iu=gs(()=>{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}`)}},au=new Set(["string","number","symbol"]),ob=new Set(["string","number","bigint","boolean","symbol","undefined"]);lu={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]},sb={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};ru=class{constructor(...e){}}});function du(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 pu(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 ab,Qi,_s,fu=O(()=>{lo();ur();ab=(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,nu,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Qi=I("$ZodError",ab),_s=I("$ZodError",ab,{Parent:Error})});var hu,mu,gu,yu,bu,Tn,wu,En,_u=O(()=>{lo();fu();ur();hu=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 Sr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Yt(c,s,At())));throw Yi(a,o?.callee),a}return i.value},mu=hu(_s),gu=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=>Yt(c,s,At())));throw Yi(a,o?.callee),a}return i.value},yu=gu(_s),bu=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 Sr;return s.issues.length?{success:!1,error:new(t??Qi)(s.issues.map(i=>Yt(i,o,At())))}:{success:!0,data:s.value}},Tn=bu(_s),wu=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=>Yt(i,o,At())))}:{success:!0,data:s.value}},En=wu(_s)});function yb(){return new RegExp(zR,"u")}function Eb(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 Rb(t){return new RegExp(`^${Eb(t)}$`)}function Pb(t){let e=Eb({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(`^${Sb}T(?:${n})$`)}var cb,lb,ub,db,pb,fb,hb,mb,vu,gb,zR,bb,wb,_b,vb,xb,xu,kb,$b,Sb,Tb,Ab,Ib,Ob,Cb,zb,Nb,jb,ta=O(()=>{cb=/^[cC][^\s-]{8,}$/,lb=/^[0-9a-z]+$/,ub=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,db=/^[0-9a-vA-V]{20}$/,pb=/^[A-Za-z0-9]{27}$/,fb=/^[a-zA-Z0-9_-]{21}$/,hb=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,mb=/^([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})$/,vu=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)$/,gb=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,zR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";bb=/^(?:(?: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])$/,wb=/^(([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})$/,_b=/^((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])$/,vb=/^(([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])$/,xb=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,xu=/^[A-Za-z0-9_-]*$/,kb=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,$b=/^\+(?:[0-9]){6,14}[0-9]$/,Sb="(?:(?:\\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])))",Tb=new RegExp(`^${Sb}$`);Ab=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Ib=/^\d+$/,Ob=/^-?\d+(?:\.\d+)?/i,Cb=/true|false/i,zb=/null/i,Nb=/^[^A-Z]*$/,jb=/^[^a-z]*$/});var rt,Lb,ku,$u,Db,Mb,Ub,Zb,qb,vs,Fb,Bb,Vb,Hb,Kb,Gb,Wb,ra=O(()=>{lo();ta();ur();rt=I("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Lb={number:"number",bigint:"bigint",object:"date"},ku=I("$ZodCheckLessThan",(t,e)=>{rt.init(t,e);let r=Lb[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})}}),$u=I("$ZodCheckGreaterThan",(t,e)=>{rt.init(t,e);let r=Lb[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})}}),Db=I("$ZodCheckMultipleOf",(t,e)=>{rt.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):ou(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})}}),Mb=I("$ZodCheckNumberFormat",(t,e)=>{rt.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=lu[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=Ib)}),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})}}),Ub=I("$ZodCheckMaxLength",(t,e)=>{var r;rt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ys(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=ws(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Zb=I("$ZodCheckMinLength",(t,e)=>{var r;rt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ys(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=ws(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),qb=I("$ZodCheckLengthEquals",(t,e)=>{var r;rt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ys(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=ws(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})}}),vs=I("$ZodCheckStringFormat",(t,e)=>{var r,n;rt.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=()=>{})}),Fb=I("$ZodCheckRegex",(t,e)=>{vs.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})}}),Bb=I("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Nb),vs.init(t,e)}),Vb=I("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=jb),vs.init(t,e)}),Hb=I("$ZodCheckIncludes",(t,e)=>{rt.init(t,e);let r=Fr(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})}}),Kb=I("$ZodCheckStartsWith",(t,e)=>{rt.init(t,e);let r=new RegExp(`^${Fr(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})}}),Gb=I("$ZodCheckEndsWith",(t,e)=>{rt.init(t,e);let r=new RegExp(`.*${Fr(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})}}),Wb=I("$ZodCheckOverwrite",(t,e)=>{rt.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var na,Su=O(()=>{na=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(`
1245
+ `});var hs=O(()=>{Ii()});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 It(t){return t&&Object.assign(ea,t),ea}var qR,Er,ea,uo=O(()=>{qR=Object.freeze({status:"aborted"});Er=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},ea={}});var be={};Ho(be,{BIGINT_FORMAT_RANGES:()=>kb,Class:()=>uu,NUMBER_FORMAT_RANGES:()=>yu,aborted:()=>En,allowsEval:()=>hu,assert:()=>KR,assertEqual:()=>FR,assertIs:()=>VR,assertNever:()=>HR,assertNotEqual:()=>BR,assignProp:()=>fu,cached:()=>ys,captureStackTrace:()=>ra,cleanEnum:()=>iP,cleanRegex:()=>ws,clone:()=>Ot,createTransparentProxy:()=>QR,defineLazy:()=>Ce,esc:()=>Tn,escapeRegex:()=>Vr,extend:()=>rP,finalizeIssue:()=>Qt,floatSafeRemainder:()=>pu,getElementAtPath:()=>GR,getEnumValues:()=>gs,getLengthableOrigin:()=>_s,getParsedType:()=>XR,getSizableOrigin:()=>$b,isObject:()=>po,isPlainObject:()=>fo,issue:()=>bu,joinValues:()=>ta,jsonStringifyReplacer:()=>du,merge:()=>nP,normalizeParams:()=>te,nullish:()=>bs,numKeys:()=>YR,omit:()=>tP,optionalKeys:()=>gu,partial:()=>oP,pick:()=>eP,prefixIssues:()=>ur,primitiveTypes:()=>xb,promiseAllObject:()=>WR,propertyKeyTypes:()=>mu,randomString:()=>JR,required:()=>sP,stringifyPrimitive:()=>na,unwrapMessage:()=>ms});function FR(t){return t}function BR(t){return t}function VR(t){}function HR(t){throw new Error}function KR(t){}function gs(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 ta(t,e="|"){return t.map(r=>na(r)).join(e)}function du(t,e){return typeof e=="bigint"?e.toString():e}function ys(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function bs(t){return t==null}function ws(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function pu(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 Ce(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 fu(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 WR(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 JR(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Tn(t){return JSON.stringify(t)}function po(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function fo(t){if(po(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(po(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function YR(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function Vr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ot(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 QR(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 na(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function gu(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function eP(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 Ot(t,{...t._zod.def,shape:r,checks:[]})}function tP(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 Ot(t,{...t._zod.def,shape:r,checks:[]})}function rP(t,e){if(!fo(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 fu(this,"shape",n),n},checks:[]};return Ot(t,r)}function nP(t,e){return Ot(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return fu(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function oP(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 Ot(e,{...e._zod.def,shape:o,checks:[]})}function sP(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 Ot(e,{...e._zod.def,shape:o,checks:[]})}function En(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function ur(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function ms(t){return typeof t=="string"?t:t?.message}function Qt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=ms(t.inst?._zod.def?.error?.(t))??ms(e?.error?.(t))??ms(r.customError?.(t))??ms(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function $b(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function _s(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function bu(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function iP(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var ra,hu,XR,mu,xb,yu,kb,uu,dr=O(()=>{ra=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};hu=ys(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});XR=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}`)}},mu=new Set(["string","number","symbol"]),xb=new Set(["string","number","bigint","boolean","symbol","undefined"]);yu={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]},kb={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};uu=class{constructor(...e){}}});function wu(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 _u(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 Sb,oa,vs,vu=O(()=>{uo();dr();Sb=(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,du,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},oa=I("$ZodError",Sb),vs=I("$ZodError",Sb,{Parent:Error})});var xu,ku,$u,Su,Tu,Rn,Eu,Pn,Ru=O(()=>{uo();vu();dr();xu=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 Er;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Qt(c,s,It())));throw ra(a,o?.callee),a}return i.value},ku=xu(vs),$u=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=>Qt(c,s,It())));throw ra(a,o?.callee),a}return i.value},Su=$u(vs),Tu=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 Er;return s.issues.length?{success:!1,error:new(t??oa)(s.issues.map(i=>Qt(i,o,It())))}:{success:!0,data:s.value}},Rn=Tu(vs),Eu=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=>Qt(i,o,It())))}:{success:!0,data:s.value}},Pn=Eu(vs)});function Nb(){return new RegExp(cP,"u")}function Vb(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 Hb(t){return new RegExp(`^${Vb(t)}$`)}function Kb(t){let e=Vb({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(`^${Fb}T(?:${n})$`)}var Tb,Eb,Rb,Pb,Ab,Ib,Ob,Cb,Pu,zb,cP,jb,Lb,Db,Mb,Ub,Au,Zb,qb,Fb,Bb,Gb,Wb,Jb,Yb,Xb,Qb,ew,ia=O(()=>{Tb=/^[cC][^\s-]{8,}$/,Eb=/^[0-9a-z]+$/,Rb=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Pb=/^[0-9a-vA-V]{20}$/,Ab=/^[A-Za-z0-9]{27}$/,Ib=/^[a-zA-Z0-9_-]{21}$/,Ob=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Cb=/^([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})$/,Pu=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)$/,zb=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,cP="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";jb=/^(?:(?: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])$/,Lb=/^(([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})$/,Db=/^((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])$/,Mb=/^(([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])$/,Ub=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Au=/^[A-Za-z0-9_-]*$/,Zb=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,qb=/^\+(?:[0-9]){6,14}[0-9]$/,Fb="(?:(?:\\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])))",Bb=new RegExp(`^${Fb}$`);Gb=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Wb=/^\d+$/,Jb=/^-?\d+(?:\.\d+)?/i,Yb=/true|false/i,Xb=/null/i,Qb=/^[^A-Z]*$/,ew=/^[^a-z]*$/});var nt,tw,Iu,Ou,rw,nw,ow,sw,iw,xs,aw,cw,lw,uw,dw,pw,fw,aa=O(()=>{uo();ia();dr();nt=I("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),tw={number:"number",bigint:"bigint",object:"date"},Iu=I("$ZodCheckLessThan",(t,e)=>{nt.init(t,e);let r=tw[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})}}),Ou=I("$ZodCheckGreaterThan",(t,e)=>{nt.init(t,e);let r=tw[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})}}),rw=I("$ZodCheckMultipleOf",(t,e)=>{nt.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):pu(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})}}),nw=I("$ZodCheckNumberFormat",(t,e)=>{nt.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=yu[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=Wb)}),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})}}),ow=I("$ZodCheckMaxLength",(t,e)=>{var r;nt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!bs(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=_s(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),sw=I("$ZodCheckMinLength",(t,e)=>{var r;nt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!bs(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=_s(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),iw=I("$ZodCheckLengthEquals",(t,e)=>{var r;nt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!bs(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=_s(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})}}),xs=I("$ZodCheckStringFormat",(t,e)=>{var r,n;nt.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=()=>{})}),aw=I("$ZodCheckRegex",(t,e)=>{xs.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})}}),cw=I("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Qb),xs.init(t,e)}),lw=I("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=ew),xs.init(t,e)}),uw=I("$ZodCheckIncludes",(t,e)=>{nt.init(t,e);let r=Vr(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})}}),dw=I("$ZodCheckStartsWith",(t,e)=>{nt.init(t,e);let r=new RegExp(`^${Vr(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})}}),pw=I("$ZodCheckEndsWith",(t,e)=>{nt.init(t,e);let r=new RegExp(`.*${Vr(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})}}),fw=I("$ZodCheckOverwrite",(t,e)=>{nt.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var ca,Cu=O(()=>{ca=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(`
1101
1246
  `).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(`
1102
- `))}}});var Yb,Tu=O(()=>{Yb={major:4,minor:0,patch:0}});function dw(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function NR(t){if(!xu.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return dw(r)}function jR(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 Xb(t,e,r){t.issues.length&&e.issues.push(...lr(r,t.issues)),e.value[r]=t.value}function oa(t,e,r){t.issues.length&&e.issues.push(...lr(r,t.issues)),e.value[r]=t.value}function Qb(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(...lr(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function ew(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=>Yt(s,n,At())))}),e}function Eu(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(po(t)&&po(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=Eu(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=Eu(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 tw(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Sn(t))return t;let n=Eu(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 rw(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function nw(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 ow(t,e,r){return Sn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function sw(t){return t.value=Object.freeze(t.value),t}function iw(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(uu(o))}}var Ae,xs,ze,Ru,Pu,Au,Iu,Ou,Cu,zu,Nu,ju,Lu,Du,aw,cw,lw,uw,Mu,Uu,Zu,qu,Fu,Bu,Vu,Hu,sa,Ku,Gu,Wu,Ju,Yu,Xu,ia,aa,Qu,ed,td,rd,nd,od,sd,id,ad,cd,ld,ud,dd,pd,fd,pw=O(()=>{ra();lo();Su();_u();ta();ur();Tu();ur();Ae=I("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Yb;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=Sn(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 Sr;if(l||b instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await b,s.issues.length!==d&&(c||(c=Sn(s,d)))});else{if(s.issues.length===d)continue;c||(c=Sn(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 Sr;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=Tn(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return En(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),xs=I("$ZodString",(t,e)=>{Ae.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}}),ze=I("$ZodStringFormat",(t,e)=>{vs.init(t,e),xs.init(t,e)}),Ru=I("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=mb),ze.init(t,e)}),Pu=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=vu(n))}else e.pattern??(e.pattern=vu());ze.init(t,e)}),Au=I("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=gb),ze.init(t,e)}),Iu=I("$ZodURL",(t,e)=>{ze.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:kb.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})}}}),Ou=I("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=yb()),ze.init(t,e)}),Cu=I("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=fb),ze.init(t,e)}),zu=I("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=cb),ze.init(t,e)}),Nu=I("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=lb),ze.init(t,e)}),ju=I("$ZodULID",(t,e)=>{e.pattern??(e.pattern=ub),ze.init(t,e)}),Lu=I("$ZodXID",(t,e)=>{e.pattern??(e.pattern=db),ze.init(t,e)}),Du=I("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=pb),ze.init(t,e)}),aw=I("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Pb(e)),ze.init(t,e)}),cw=I("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Tb),ze.init(t,e)}),lw=I("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Rb(e)),ze.init(t,e)}),uw=I("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=hb),ze.init(t,e)}),Mu=I("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=bb),ze.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Uu=I("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=wb),ze.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})}}}),Zu=I("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=_b),ze.init(t,e)}),qu=I("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=vb),ze.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})}}});Fu=I("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=xb),ze.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{dw(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});Bu=I("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=xu),ze.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{NR(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Vu=I("$ZodE164",(t,e)=>{e.pattern??(e.pattern=$b),ze.init(t,e)});Hu=I("$ZodJWT",(t,e)=>{ze.init(t,e),t._zod.check=r=>{jR(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),sa=I("$ZodNumber",(t,e)=>{Ae.init(t,e),t._zod.pattern=t._zod.bag.pattern??Ob,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}}),Ku=I("$ZodNumber",(t,e)=>{Mb.init(t,e),sa.init(t,e)}),Gu=I("$ZodBoolean",(t,e)=>{Ae.init(t,e),t._zod.pattern=Cb,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}}),Wu=I("$ZodNull",(t,e)=>{Ae.init(t,e),t._zod.pattern=zb,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}}),Ju=I("$ZodUnknown",(t,e)=>{Ae.init(t,e),t._zod.parse=r=>r}),Yu=I("$ZodNever",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});Xu=I("$ZodArray",(t,e)=>{Ae.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=>Xb(l,r,i))):Xb(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});ia=I("$ZodObject",(t,e)=>{Ae.init(t,e);let r=gs(()=>{let d=Object.keys(e.shape);for(let m of d)if(!(e.shape[m]instanceof Ae))throw new Error(`Invalid element at key "${m}": expected a Zod schema`);let b=cu(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(b)}});Ce(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 na(["shape","payload","ctx"]),m=r.value,f=P=>{let z=$n(P);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 P of m.keys)y[P]=`key_${v++}`;b.write("const newResult = {}");for(let P of m.keys)if(m.optionalKeys.has(P)){let z=y[P];b.write(`const ${z} = ${f(P)};`);let V=$n(P);b.write(`
1247
+ `))}}});var mw,zu=O(()=>{mw={major:4,minor:0,patch:0}});function Pw(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function lP(t){if(!Au.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Pw(r)}function uP(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 gw(t,e,r){t.issues.length&&e.issues.push(...ur(r,t.issues)),e.value[r]=t.value}function la(t,e,r){t.issues.length&&e.issues.push(...ur(r,t.issues)),e.value[r]=t.value}function yw(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(...ur(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function bw(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=>Qt(s,n,It())))}),e}function Nu(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(fo(t)&&fo(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=Nu(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=Nu(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 ww(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),En(t))return t;let n=Nu(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 _w(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function vw(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 xw(t,e,r){return En(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function kw(t){return t.value=Object.freeze(t.value),t}function $w(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(bu(o))}}var Ae,ks,ze,ju,Lu,Du,Mu,Uu,Zu,qu,Fu,Bu,Vu,Hu,Sw,Tw,Ew,Rw,Ku,Gu,Wu,Ju,Yu,Xu,Qu,ed,ua,td,rd,nd,od,sd,id,da,pa,ad,cd,ld,ud,dd,pd,fd,hd,md,gd,yd,bd,wd,_d,vd,Aw=O(()=>{aa();uo();Cu();Ru();ia();dr();zu();dr();Ae=I("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=mw;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=En(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,w=u._zod.check(s);if(w instanceof Promise&&a?.async===!1)throw new Er;if(l||w instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await w,s.issues.length!==d&&(c||(c=En(s,d)))});else{if(s.issues.length===d)continue;c||(c=En(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 Er;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=Rn(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Pn(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),ks=I("$ZodString",(t,e)=>{Ae.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Gb(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}}),ze=I("$ZodStringFormat",(t,e)=>{xs.init(t,e),ks.init(t,e)}),ju=I("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Cb),ze.init(t,e)}),Lu=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=Pu(n))}else e.pattern??(e.pattern=Pu());ze.init(t,e)}),Du=I("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=zb),ze.init(t,e)}),Mu=I("$ZodURL",(t,e)=>{ze.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:Zb.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})}}}),Uu=I("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Nb()),ze.init(t,e)}),Zu=I("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Ib),ze.init(t,e)}),qu=I("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Tb),ze.init(t,e)}),Fu=I("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Eb),ze.init(t,e)}),Bu=I("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Rb),ze.init(t,e)}),Vu=I("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Pb),ze.init(t,e)}),Hu=I("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Ab),ze.init(t,e)}),Sw=I("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Kb(e)),ze.init(t,e)}),Tw=I("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Bb),ze.init(t,e)}),Ew=I("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Hb(e)),ze.init(t,e)}),Rw=I("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Ob),ze.init(t,e)}),Ku=I("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=jb),ze.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Gu=I("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Lb),ze.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})}}}),Wu=I("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Db),ze.init(t,e)}),Ju=I("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Mb),ze.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})}}});Yu=I("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Ub),ze.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{Pw(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});Xu=I("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Au),ze.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{lP(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=qb),ze.init(t,e)});ed=I("$ZodJWT",(t,e)=>{ze.init(t,e),t._zod.check=r=>{uP(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),ua=I("$ZodNumber",(t,e)=>{Ae.init(t,e),t._zod.pattern=t._zod.bag.pattern??Jb,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}}),td=I("$ZodNumber",(t,e)=>{nw.init(t,e),ua.init(t,e)}),rd=I("$ZodBoolean",(t,e)=>{Ae.init(t,e),t._zod.pattern=Yb,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}}),nd=I("$ZodNull",(t,e)=>{Ae.init(t,e),t._zod.pattern=Xb,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}}),od=I("$ZodUnknown",(t,e)=>{Ae.init(t,e),t._zod.parse=r=>r}),sd=I("$ZodNever",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});id=I("$ZodArray",(t,e)=>{Ae.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=>gw(l,r,i))):gw(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});da=I("$ZodObject",(t,e)=>{Ae.init(t,e);let r=ys(()=>{let d=Object.keys(e.shape);for(let m of d)if(!(e.shape[m]instanceof Ae))throw new Error(`Invalid element at key "${m}": expected a Zod schema`);let w=gu(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(w)}});Ce(t._zod,"propValues",()=>{let d=e.shape,w={};for(let m in d){let f=d[m]._zod;if(f.values){w[m]??(w[m]=new Set);for(let b of f.values)w[m].add(b)}}return w});let n=d=>{let w=new ca(["shape","payload","ctx"]),m=r.value,f=P=>{let z=Tn(P);return`shape[${z}]._zod.run({ value: input[${z}], issues: [] }, ctx)`};w.write("const input = payload.value;");let b=Object.create(null),k=0;for(let P of m.keys)b[P]=`key_${k++}`;w.write("const newResult = {}");for(let P of m.keys)if(m.optionalKeys.has(P)){let z=b[P];w.write(`const ${z} = ${f(P)};`);let H=Tn(P);w.write(`
1103
1248
  if (${z}.issues.length) {
1104
- if (input[${V}] === undefined) {
1105
- if (${V} in input) {
1106
- newResult[${V}] = undefined;
1249
+ if (input[${H}] === undefined) {
1250
+ if (${H} in input) {
1251
+ newResult[${H}] = undefined;
1107
1252
  }
1108
1253
  } else {
1109
1254
  payload.issues = payload.issues.concat(
1110
1255
  ${z}.issues.map((iss) => ({
1111
1256
  ...iss,
1112
- path: iss.path ? [${V}, ...iss.path] : [${V}],
1257
+ path: iss.path ? [${H}, ...iss.path] : [${H}],
1113
1258
  }))
1114
1259
  );
1115
1260
  }
1116
1261
  } else if (${z}.value === undefined) {
1117
- if (${V} in input) newResult[${V}] = undefined;
1262
+ if (${H} in input) newResult[${H}] = undefined;
1118
1263
  } else {
1119
- newResult[${V}] = ${z}.value;
1264
+ newResult[${H}] = ${z}.value;
1120
1265
  }
1121
- `)}else{let z=y[P];b.write(`const ${z} = ${f(P)};`),b.write(`
1266
+ `)}else{let z=b[P];w.write(`const ${z} = ${f(P)};`),w.write(`
1122
1267
  if (${z}.issues.length) payload.issues = payload.issues.concat(${z}.issues.map(iss => ({
1123
1268
  ...iss,
1124
- path: iss.path ? [${$n(P)}, ...iss.path] : [${$n(P)}]
1125
- })));`),b.write(`newResult[${$n(P)}] = ${z}.value`)}b.write("payload.value = newResult;"),b.write("return payload;");let E=b.compile();return(P,z)=>E(d,P,z)},o,s=uo,i=!Wi.jitless,c=i&&iu.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 Y=z[V],Ke=Y._zod.run({value:m[V],issues:[]},b),et=Y._zod.optin==="optional"&&Y._zod.optout==="optional";Ke instanceof Promise?f.push(Ke.then(Ar=>et?Qb(Ar,d,V,m):oa(Ar,d,V))):et?Qb(Ke,d,V,m):oa(Ke,d,V)}}if(!l)return f.length?Promise.all(f).then(()=>d):d;let y=[],v=u.keySet,E=l._zod,P=E.def.type;for(let z of Object.keys(m)){if(v.has(z))continue;if(P==="never"){y.push(z);continue}let V=E.run({value:m[z],issues:[]},b);V instanceof Promise?f.push(V.then(Y=>oa(Y,d,z))):oa(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}});aa=I("$ZodUnion",(t,e)=>{Ae.init(t,e),Ce(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Ce(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Ce(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Ce(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=>bs(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=>ew(i,r,t,n)):ew(s,r,t,n)}}),Qu=I("$ZodDiscriminatedUnion",(t,e)=>{aa.init(t,e);let r=t._zod.parse;Ce(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=gs(()=>{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(!uo(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)}}),ed=I("$ZodIntersection",(t,e)=>{Ae.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])=>tw(r,c,l)):tw(r,s,i)}});td=I("$ZodRecord",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!po(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(...lr(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...lr(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=>Yt(l,n,At())),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(...lr(i,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...lr(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),rd=I("$ZodEnum",(t,e)=>{Ae.init(t,e);let r=ms(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>au.has(typeof n)).map(n=>typeof n=="string"?Fr(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}}),nd=I("$ZodLiteral",(t,e)=>{Ae.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Fr(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}}),od=I("$ZodTransform",(t,e)=>{Ae.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 Sr;return r.value=o,r}}),sd=I("$ZodOptional",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Ce(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Ce(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${bs(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)}),id=I("$ZodNullable",(t,e)=>{Ae.init(t,e),Ce(t._zod,"optin",()=>e.innerType._zod.optin),Ce(t._zod,"optout",()=>e.innerType._zod.optout),Ce(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${bs(r.source)}|null)$`):void 0}),Ce(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)}),ad=I("$ZodDefault",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",Ce(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=>rw(s,e)):rw(o,e)}});cd=I("$ZodPrefault",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",Ce(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))}),ld=I("$ZodNonOptional",(t,e)=>{Ae.init(t,e),Ce(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=>nw(s,t)):nw(o,t)}});ud=I("$ZodCatch",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",Ce(t._zod,"optout",()=>e.innerType._zod.optout),Ce(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=>Yt(i,n,At()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>Yt(s,n,At()))},input:r.value}),r.issues=[]),r)}}),dd=I("$ZodPipe",(t,e)=>{Ae.init(t,e),Ce(t._zod,"values",()=>e.in._zod.values),Ce(t._zod,"optin",()=>e.in._zod.optin),Ce(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=>ow(s,e,n)):ow(o,e,n)}});pd=I("$ZodReadonly",(t,e)=>{Ae.init(t,e),Ce(t._zod,"propValues",()=>e.innerType._zod.propValues),Ce(t._zod,"values",()=>e.innerType._zod.values),Ce(t._zod,"optin",()=>e.innerType._zod.optin),Ce(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(sw):sw(o)}});fd=I("$ZodCustom",(t,e)=>{rt.init(t,e),Ae.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=>iw(s,r,n,t));iw(o,r,n,t)}})});function fw(){return{localeError:DR()}}var LR,DR,hw=O(()=>{ur();LR=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},DR=()=>{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 ${LR(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Xi(n.values[0])}`:`Invalid option: expected one of ${Ji(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":""}: ${Ji(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 ca=O(()=>{});function mw(){return new ks}var ks,Br,md=O(()=>{ks=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)}};Br=mw()});function gd(t,e){return new t({type:"string",...te(e)})}function yd(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...te(e)})}function la(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...te(e)})}function bd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...te(e)})}function wd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...te(e)})}function _d(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...te(e)})}function vd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...te(e)})}function xd(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...te(e)})}function kd(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...te(e)})}function $d(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...te(e)})}function Sd(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...te(e)})}function Td(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...te(e)})}function Ed(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...te(e)})}function Rd(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...te(e)})}function Pd(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...te(e)})}function Ad(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...te(e)})}function Id(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...te(e)})}function Od(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...te(e)})}function Cd(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...te(e)})}function zd(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...te(e)})}function Nd(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...te(e)})}function jd(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...te(e)})}function Ld(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...te(e)})}function gw(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...te(e)})}function yw(t,e){return new t({type:"string",format:"date",check:"string_format",...te(e)})}function bw(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...te(e)})}function ww(t,e){return new t({type:"string",format:"duration",check:"string_format",...te(e)})}function Dd(t,e){return new t({type:"number",checks:[],...te(e)})}function Md(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...te(e)})}function Ud(t,e){return new t({type:"boolean",...te(e)})}function Zd(t,e){return new t({type:"null",...te(e)})}function qd(t){return new t({type:"unknown"})}function Fd(t,e){return new t({type:"never",...te(e)})}function ua(t,e){return new ku({check:"less_than",...te(e),value:t,inclusive:!1})}function $s(t,e){return new ku({check:"less_than",...te(e),value:t,inclusive:!0})}function da(t,e){return new $u({check:"greater_than",...te(e),value:t,inclusive:!1})}function Ss(t,e){return new $u({check:"greater_than",...te(e),value:t,inclusive:!0})}function pa(t,e){return new Db({check:"multiple_of",...te(e),value:t})}function fa(t,e){return new Ub({check:"max_length",...te(e),maximum:t})}function fo(t,e){return new Zb({check:"min_length",...te(e),minimum:t})}function ha(t,e){return new qb({check:"length_equals",...te(e),length:t})}function Bd(t,e){return new Fb({check:"string_format",format:"regex",...te(e),pattern:t})}function Vd(t){return new Bb({check:"string_format",format:"lowercase",...te(t)})}function Hd(t){return new Vb({check:"string_format",format:"uppercase",...te(t)})}function Kd(t,e){return new Hb({check:"string_format",format:"includes",...te(e),includes:t})}function Gd(t,e){return new Kb({check:"string_format",format:"starts_with",...te(e),prefix:t})}function Wd(t,e){return new Gb({check:"string_format",format:"ends_with",...te(e),suffix:t})}function Rn(t){return new Wb({check:"overwrite",tx:t})}function Jd(t){return Rn(e=>e.normalize(t))}function Yd(){return Rn(t=>t.trim())}function Xd(){return Rn(t=>t.toLowerCase())}function Qd(){return Rn(t=>t.toUpperCase())}function _w(t,e,r){return new t({type:"array",element:e,...te(r)})}function ep(t,e,r){let n=te(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function tp(t,e,r){return new t({type:"custom",check:"custom",fn:e,...te(r)})}var vw=O(()=>{ra();ur()});var xw=O(()=>{});function rp(t,e){if(t instanceof ks){let n=new ma(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 ma(e);return r.process(t),r.emit(t,e)}function Je(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 Je(o.element,r);case"object":{for(let s in o.shape)if(Je(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(Je(s,r))return!0;return!1}case"intersection":return Je(o.left,r)||Je(o.right,r);case"tuple":{for(let s of o.items)if(Je(s,r))return!0;return!!(o.rest&&Je(o.rest,r))}case"record":return Je(o.keyType,r)||Je(o.valueType,r);case"map":return Je(o.keyType,r)||Je(o.valueType,r);case"set":return Je(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Je(o.innerType,r);case"lazy":return Je(o.getter(),r);case"default":return Je(o.innerType,r);case"prefault":return Je(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Je(o.in,r)||Je(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var ma,kw=O(()=>{md();ur();ma=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Br,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:P,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),P&&P.size>0){let V=[...P];V.length===1?f.pattern=V[0].source:V.length>1&&(a.schema.allOf=[...V.map(Y=>({...this.target==="draft-7"?{type:"string"}:{},pattern:Y.source}))])}break}case"number":{let f=m,{minimum:y,maximum:v,format:E,multipleOf:P,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 P=="number"&&(f.multipleOf=P);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 P in y)f.properties[P]=this.process(y[P],{...d,path:[...d.path,"properties",P]});let v=new Set(Object.keys(y)),E=new Set([...v].filter(P=>{let z=o.shape[P]._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,P=[...E(y)?y.allOf:[y],...E(v)?v.allOf:[v]];f.allOf=P;break}case"tuple":{let f=m;f.type="array";let y=o.items.map((P,z)=>this.process(P,{...d,path:[...d.path,"prefixItems",z]}));if(this.target==="draft-2020-12"?f.prefixItems=y:f.items=y,o.rest){let P=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?f.items=P:f.additionalItems=P}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=ms(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:P}=e._zod.bag;v!==void 0&&(y.minLength=v),E!==void 0&&(y.maxLength=E),P?P.length===1?(y.contentMediaType=P[0],Object.assign(f,y)):f.anyOf=P.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"&&Je(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??(P=>P);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>
1269
+ path: iss.path ? [${Tn(P)}, ...iss.path] : [${Tn(P)}]
1270
+ })));`),w.write(`newResult[${Tn(P)}] = ${z}.value`)}w.write("payload.value = newResult;"),w.write("return payload;");let E=w.compile();return(P,z)=>E(d,P,z)},o,s=po,i=!ea.jitless,c=i&&hu.value,l=e.catchall,u;t._zod.parse=(d,w)=>{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&&w?.async===!1&&w.jitless!==!0)o||(o=n(e.shape)),d=o(d,w);else{d.value={};let z=u.shape;for(let H of u.keys){let Y=z[H],Ge=Y._zod.run({value:m[H],issues:[]},w),tt=Y._zod.optin==="optional"&&Y._zod.optout==="optional";Ge instanceof Promise?f.push(Ge.then(Or=>tt?yw(Or,d,H,m):la(Or,d,H))):tt?yw(Ge,d,H,m):la(Ge,d,H)}}if(!l)return f.length?Promise.all(f).then(()=>d):d;let b=[],k=u.keySet,E=l._zod,P=E.def.type;for(let z of Object.keys(m)){if(k.has(z))continue;if(P==="never"){b.push(z);continue}let H=E.run({value:m[z],issues:[]},w);H instanceof Promise?f.push(H.then(Y=>la(Y,d,z))):la(H,d,z)}return b.length&&d.issues.push({code:"unrecognized_keys",keys:b,input:m,inst:t}),f.length?Promise.all(f).then(()=>d):d}});pa=I("$ZodUnion",(t,e)=>{Ae.init(t,e),Ce(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Ce(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Ce(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Ce(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=>ws(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=>bw(i,r,t,n)):bw(s,r,t,n)}}),ad=I("$ZodDiscriminatedUnion",(t,e)=>{pa.init(t,e);let r=t._zod.parse;Ce(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=ys(()=>{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(!po(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)}}),cd=I("$ZodIntersection",(t,e)=>{Ae.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])=>ww(r,c,l)):ww(r,s,i)}});ld=I("$ZodRecord",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!fo(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(...ur(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...ur(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=>Qt(l,n,It())),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(...ur(i,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...ur(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),ud=I("$ZodEnum",(t,e)=>{Ae.init(t,e);let r=gs(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>mu.has(typeof n)).map(n=>typeof n=="string"?Vr(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}}),dd=I("$ZodLiteral",(t,e)=>{Ae.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Vr(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}}),pd=I("$ZodTransform",(t,e)=>{Ae.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 Er;return r.value=o,r}}),fd=I("$ZodOptional",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Ce(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Ce(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${ws(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)}),hd=I("$ZodNullable",(t,e)=>{Ae.init(t,e),Ce(t._zod,"optin",()=>e.innerType._zod.optin),Ce(t._zod,"optout",()=>e.innerType._zod.optout),Ce(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${ws(r.source)}|null)$`):void 0}),Ce(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)}),md=I("$ZodDefault",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",Ce(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=>_w(s,e)):_w(o,e)}});gd=I("$ZodPrefault",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",Ce(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))}),yd=I("$ZodNonOptional",(t,e)=>{Ae.init(t,e),Ce(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=>vw(s,t)):vw(o,t)}});bd=I("$ZodCatch",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",Ce(t._zod,"optout",()=>e.innerType._zod.optout),Ce(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=>Qt(i,n,It()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>Qt(s,n,It()))},input:r.value}),r.issues=[]),r)}}),wd=I("$ZodPipe",(t,e)=>{Ae.init(t,e),Ce(t._zod,"values",()=>e.in._zod.values),Ce(t._zod,"optin",()=>e.in._zod.optin),Ce(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=>xw(s,e,n)):xw(o,e,n)}});_d=I("$ZodReadonly",(t,e)=>{Ae.init(t,e),Ce(t._zod,"propValues",()=>e.innerType._zod.propValues),Ce(t._zod,"values",()=>e.innerType._zod.values),Ce(t._zod,"optin",()=>e.innerType._zod.optin),Ce(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(kw):kw(o)}});vd=I("$ZodCustom",(t,e)=>{nt.init(t,e),Ae.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=>$w(s,r,n,t));$w(o,r,n,t)}})});function Iw(){return{localeError:pP()}}var dP,pP,Ow=O(()=>{dr();dP=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},pP=()=>{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 ${dP(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${na(n.values[0])}`:`Invalid option: expected one of ${ta(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":""}: ${ta(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 fa=O(()=>{});function Cw(){return new $s}var $s,Hr,kd=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)}};Hr=Cw()});function $d(t,e){return new t({type:"string",...te(e)})}function Sd(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...te(e)})}function ha(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...te(e)})}function Td(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...te(e)})}function Ed(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...te(e)})}function Rd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...te(e)})}function Pd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...te(e)})}function Ad(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...te(e)})}function Id(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...te(e)})}function Od(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...te(e)})}function Cd(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...te(e)})}function zd(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...te(e)})}function Nd(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...te(e)})}function jd(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...te(e)})}function Ld(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...te(e)})}function Dd(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...te(e)})}function Md(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...te(e)})}function Ud(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...te(e)})}function Zd(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...te(e)})}function qd(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...te(e)})}function Fd(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...te(e)})}function Bd(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...te(e)})}function Vd(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...te(e)})}function zw(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...te(e)})}function Nw(t,e){return new t({type:"string",format:"date",check:"string_format",...te(e)})}function jw(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...te(e)})}function Lw(t,e){return new t({type:"string",format:"duration",check:"string_format",...te(e)})}function Hd(t,e){return new t({type:"number",checks:[],...te(e)})}function Kd(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...te(e)})}function Gd(t,e){return new t({type:"boolean",...te(e)})}function Wd(t,e){return new t({type:"null",...te(e)})}function Jd(t){return new t({type:"unknown"})}function Yd(t,e){return new t({type:"never",...te(e)})}function ma(t,e){return new Iu({check:"less_than",...te(e),value:t,inclusive:!1})}function Ss(t,e){return new Iu({check:"less_than",...te(e),value:t,inclusive:!0})}function ga(t,e){return new Ou({check:"greater_than",...te(e),value:t,inclusive:!1})}function Ts(t,e){return new Ou({check:"greater_than",...te(e),value:t,inclusive:!0})}function ya(t,e){return new rw({check:"multiple_of",...te(e),value:t})}function ba(t,e){return new ow({check:"max_length",...te(e),maximum:t})}function ho(t,e){return new sw({check:"min_length",...te(e),minimum:t})}function wa(t,e){return new iw({check:"length_equals",...te(e),length:t})}function Xd(t,e){return new aw({check:"string_format",format:"regex",...te(e),pattern:t})}function Qd(t){return new cw({check:"string_format",format:"lowercase",...te(t)})}function ep(t){return new lw({check:"string_format",format:"uppercase",...te(t)})}function tp(t,e){return new uw({check:"string_format",format:"includes",...te(e),includes:t})}function rp(t,e){return new dw({check:"string_format",format:"starts_with",...te(e),prefix:t})}function np(t,e){return new pw({check:"string_format",format:"ends_with",...te(e),suffix:t})}function An(t){return new fw({check:"overwrite",tx:t})}function op(t){return An(e=>e.normalize(t))}function sp(){return An(t=>t.trim())}function ip(){return An(t=>t.toLowerCase())}function ap(){return An(t=>t.toUpperCase())}function Dw(t,e,r){return new t({type:"array",element:e,...te(r)})}function cp(t,e,r){let n=te(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function lp(t,e,r){return new t({type:"custom",check:"custom",fn:e,...te(r)})}var Mw=O(()=>{aa();dr()});var Uw=O(()=>{});function up(t,e){if(t instanceof $s){let n=new _a(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 _a(e);return r.process(t),r.emit(t,e)}function Ye(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 Ye(o.element,r);case"object":{for(let s in o.shape)if(Ye(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(Ye(s,r))return!0;return!1}case"intersection":return Ye(o.left,r)||Ye(o.right,r);case"tuple":{for(let s of o.items)if(Ye(s,r))return!0;return!!(o.rest&&Ye(o.rest,r))}case"record":return Ye(o.keyType,r)||Ye(o.valueType,r);case"map":return Ye(o.keyType,r)||Ye(o.valueType,r);case"set":return Ye(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ye(o.innerType,r);case"lazy":return Ye(o.getter(),r);case"default":return Ye(o.innerType,r);case"prefault":return Ye(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Ye(o.in,r)||Ye(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var _a,Zw=O(()=>{kd();dr();_a=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Hr,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},w=e._zod.parent;if(w)a.ref=w,this.process(w,d),this.seen.get(w).isParent=!0;else{let m=a.schema;switch(o.type){case"string":{let f=m;f.type="string";let{minimum:b,maximum:k,format:E,patterns:P,contentEncoding:z}=e._zod.bag;if(typeof b=="number"&&(f.minLength=b),typeof k=="number"&&(f.maxLength=k),E&&(f.format=s[E]??E,f.format===""&&delete f.format),z&&(f.contentEncoding=z),P&&P.size>0){let H=[...P];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:b,maximum:k,format:E,multipleOf:P,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 b=="number"&&(f.minimum=b,typeof H=="number"&&(H>=b?delete f.minimum:delete f.exclusiveMinimum)),typeof z=="number"&&(f.exclusiveMaximum=z),typeof k=="number"&&(f.maximum=k,typeof z=="number"&&(z<=k?delete f.maximum:delete f.exclusiveMaximum)),typeof P=="number"&&(f.multipleOf=P);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:b,maximum:k}=e._zod.bag;typeof b=="number"&&(f.minItems=b),typeof k=="number"&&(f.maxItems=k),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 b=o.shape;for(let P in b)f.properties[P]=this.process(b[P],{...d,path:[...d.path,"properties",P]});let k=new Set(Object.keys(b)),E=new Set([...k].filter(P=>{let z=o.shape[P]._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((b,k)=>this.process(b,{...d,path:[...d.path,"anyOf",k]}));break}case"intersection":{let f=m,b=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),k=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),E=z=>"allOf"in z&&Object.keys(z).length===1,P=[...E(b)?b.allOf:[b],...E(k)?k.allOf:[k]];f.allOf=P;break}case"tuple":{let f=m;f.type="array";let b=o.items.map((P,z)=>this.process(P,{...d,path:[...d.path,"prefixItems",z]}));if(this.target==="draft-2020-12"?f.prefixItems=b:f.items=b,o.rest){let P=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?f.items=P:f.additionalItems=P}o.rest&&(f.items=this.process(o.rest,{...d,path:[...d.path,"items"]}));let{minimum:k,maximum:E}=e._zod.bag;typeof k=="number"&&(f.minItems=k),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,b=gs(o.entries);b.every(k=>typeof k=="number")&&(f.type="number"),b.every(k=>typeof k=="string")&&(f.type="string"),f.enum=b;break}case"literal":{let f=m,b=[];for(let k of o.values)if(k===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof k=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");b.push(Number(k))}else b.push(k);if(b.length!==0)if(b.length===1){let k=b[0];f.type=k===null?"null":typeof k,f.const=k}else b.every(k=>typeof k=="number")&&(f.type="number"),b.every(k=>typeof k=="string")&&(f.type="string"),b.every(k=>typeof k=="boolean")&&(f.type="string"),b.every(k=>k===null)&&(f.type="null"),f.enum=b;break}case"file":{let f=m,b={type:"string",format:"binary",contentEncoding:"binary"},{minimum:k,maximum:E,mime:P}=e._zod.bag;k!==void 0&&(b.minLength=k),E!==void 0&&(b.maxLength=E),P?P.length===1?(b.contentMediaType=P[0],Object.assign(f,b)):f.anyOf=P.map(z=>({...b,contentMediaType:z})):Object.assign(f,b);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,b=e._zod.pattern;if(!b)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=b.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"&&Ye(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 b=n.external.registry.get(u[0])?.id,k=n.external.uri??(P=>P);if(b)return{ref:k(b)};let E=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=E,{defId:E,ref:`${k("__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:w,defId:m}=s(u);d.def={...d.schema},m&&(d.defId=m);let f=d.schema;for(let b in f)delete f[b];f.$ref=w};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>
1126
1271
 
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 $w=O(()=>{});var ht=O(()=>{lo();_u();fu();pw();ra();Tu();ur();ta();ca();md();Su();xw();vw();kw();$w()});var np=O(()=>{ht()});function op(t,e){let r={type:"object",get shape(){return be.assignProp(this,"shape",{...t}),this.shape},...be.normalizeParams(e)};return new _P(r)}var wP,_P,Sw=O(()=>{ht();ht();np();wP=I("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");Ae.init(t,e),t.def=e,t.parse=(r,n)=>mu(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Tn(t,r,n),t.parseAsync=async(r,n)=>yu(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>En(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)=>It(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),_P=I("ZodMiniObject",(t,e)=>{ia.init(t,e),wP.init(t,e),be.defineLazy(t,"shape",()=>e.shape)})});var Tw=O(()=>{});var Ew=O(()=>{});var Rw=O(()=>{});var Pw=O(()=>{ht();np();Sw();Tw();ht();ca();Ew();Rw()});var Aw=O(()=>{Pw()});var sp=O(()=>{Aw()});function dr(t){return!!t._zod}function An(t){let e=Object.values(t);if(e.length===0)return op({});let r=e.every(dr),n=e.every(o=>!dr(o));if(r)return op(t);if(n)return ll(t);throw new Error("Mixed Zod versions detected in object shape.")}function Vr(t,e){return dr(t)?Tn(t,e):t.safeParse(e)}async function ga(t,e){return dr(t)?await En(t,e):await t.safeParseAsync(e)}function Hr(t){if(!t)return;let e;if(dr(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function ho(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 An(t)}}if(dr(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 kP(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function ya(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 ${kP(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 Ow(t){return t.description}function Cw(t){if(dr(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function mo(t){if(dr(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 Ts=O(()=>{fs();sp()});var ip=O(()=>{ht()});var Es={};Vo(Es,{ZodISODate:()=>Nw,ZodISODateTime:()=>zw,ZodISODuration:()=>Lw,ZodISOTime:()=>jw,date:()=>cp,datetime:()=>ap,duration:()=>up,time:()=>lp});function ap(t){return gw(zw,t)}function cp(t){return yw(Nw,t)}function lp(t){return bw(jw,t)}function up(t){return ww(Lw,t)}var zw,Nw,jw,Lw,dp=O(()=>{ht();pp();zw=I("ZodISODateTime",(t,e)=>{aw.init(t,e),Ue.init(t,e)});Nw=I("ZodISODate",(t,e)=>{cw.init(t,e),Ue.init(t,e)});jw=I("ZodISOTime",(t,e)=>{lw.init(t,e),Ue.init(t,e)});Lw=I("ZodISODuration",(t,e)=>{uw.init(t,e),Ue.init(t,e)})});var Dw,_q,Rs,fp=O(()=>{ht();ht();Dw=(t,e)=>{Qi.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>pu(t,r)},flatten:{value:r=>du(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},_q=I("ZodError",Dw),Rs=I("ZodError",Dw,{Parent:Error})});var Mw,Uw,Zw,qw,hp=O(()=>{ht();fp();Mw=hu(Rs),Uw=gu(Rs),Zw=bu(Rs),qw=wu(Rs)});function A(t){return gd(IP,t)}function Te(t){return Dd(Kw,t)}function Bw(t){return Md(WP,t)}function Qe(t){return Ud(JP,t)}function Gw(t){return Zd(YP,t)}function Ze(){return qd(XP)}function eA(t){return Fd(QP,t)}function we(t,e){return _w(tA,t,e)}function B(t,e){let r={type:"object",get shape(){return be.assignProp(this,"shape",{...t}),this.shape},...be.normalizeParams(e)};return new Ww(r)}function mt(t,e){return new Ww({type:"object",get shape(){return be.assignProp(this,"shape",{...t}),this.shape},catchall:Ze(),...be.normalizeParams(e)})}function je(t,e){return new Jw({type:"union",options:t,...be.normalizeParams(e)})}function yp(t,e,r){return new rA({type:"union",options:e,discriminator:t,...be.normalizeParams(r)})}function wa(t,e){return new nA({type:"intersection",left:t,right:e})}function Ne(t,e,r){return new oA({type:"record",keyType:t,valueType:e,...be.normalizeParams(r)})}function kt(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new mp({type:"enum",entries:r,...be.normalizeParams(e)})}function W(t,e){return new sA({type:"literal",values:Array.isArray(t)?t:[t],...be.normalizeParams(e)})}function Yw(t){return new iA({type:"transform",transform:t})}function qe(t){return new Xw({type:"optional",innerType:t})}function Vw(t){return new aA({type:"nullable",innerType:t})}function lA(t,e){return new cA({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function dA(t,e){return new uA({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function pA(t,e){return new Qw({type:"nonoptional",innerType:t,...be.normalizeParams(e)})}function hA(t,e){return new fA({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function gp(t,e){return new mA({type:"pipe",in:t,out:e})}function yA(t){return new gA({type:"readonly",innerType:t})}function bA(t){let e=new rt({check:"custom"});return e._zod.check=t,e}function t_(t,e){return ep(e_,t??(()=>!0),e)}function wA(t,e={}){return tp(e_,t,e)}function _A(t){let e=bA(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(be.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(be.issue(o))}},t(r.value,r)));return e}function bp(t,e){return gp(Yw(t),e)}var Be,Hw,IP,Ue,OP,Fw,ba,CP,zP,NP,jP,LP,DP,MP,UP,ZP,qP,FP,BP,VP,HP,KP,GP,Kw,WP,JP,YP,XP,QP,tA,Ww,Jw,rA,nA,oA,mp,sA,iA,Xw,aA,cA,uA,Qw,fA,mA,gA,e_,pp=O(()=>{ht();ht();ip();dp();hp();Be=I("ZodType",(t,e)=>(Ae.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)=>It(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Mw(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Zw(t,r,n),t.parseAsync=async(r,n)=>Uw(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>qw(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(wA(r,n)),t.superRefine=r=>t.check(_A(r)),t.overwrite=r=>t.check(Rn(r)),t.optional=()=>qe(t),t.nullable=()=>Vw(t),t.nullish=()=>qe(Vw(t)),t.nonoptional=r=>pA(t,r),t.array=()=>we(t),t.or=r=>je([t,r]),t.and=r=>wa(t,r),t.transform=r=>gp(t,Yw(r)),t.default=r=>lA(t,r),t.prefault=r=>dA(t,r),t.catch=r=>hA(t,r),t.pipe=r=>gp(t,r),t.readonly=()=>yA(t),t.describe=r=>{let n=t.clone();return Br.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Br.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Br.get(t);let n=t.clone();return Br.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Hw=I("_ZodString",(t,e)=>{xs.init(t,e),Be.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(Bd(...n)),t.includes=(...n)=>t.check(Kd(...n)),t.startsWith=(...n)=>t.check(Gd(...n)),t.endsWith=(...n)=>t.check(Wd(...n)),t.min=(...n)=>t.check(fo(...n)),t.max=(...n)=>t.check(fa(...n)),t.length=(...n)=>t.check(ha(...n)),t.nonempty=(...n)=>t.check(fo(1,...n)),t.lowercase=n=>t.check(Vd(n)),t.uppercase=n=>t.check(Hd(n)),t.trim=()=>t.check(Yd()),t.normalize=(...n)=>t.check(Jd(...n)),t.toLowerCase=()=>t.check(Xd()),t.toUpperCase=()=>t.check(Qd())}),IP=I("ZodString",(t,e)=>{xs.init(t,e),Hw.init(t,e),t.email=r=>t.check(yd(OP,r)),t.url=r=>t.check(xd(CP,r)),t.jwt=r=>t.check(Ld(GP,r)),t.emoji=r=>t.check(kd(zP,r)),t.guid=r=>t.check(la(Fw,r)),t.uuid=r=>t.check(bd(ba,r)),t.uuidv4=r=>t.check(wd(ba,r)),t.uuidv6=r=>t.check(_d(ba,r)),t.uuidv7=r=>t.check(vd(ba,r)),t.nanoid=r=>t.check($d(NP,r)),t.guid=r=>t.check(la(Fw,r)),t.cuid=r=>t.check(Sd(jP,r)),t.cuid2=r=>t.check(Td(LP,r)),t.ulid=r=>t.check(Ed(DP,r)),t.base64=r=>t.check(zd(VP,r)),t.base64url=r=>t.check(Nd(HP,r)),t.xid=r=>t.check(Rd(MP,r)),t.ksuid=r=>t.check(Pd(UP,r)),t.ipv4=r=>t.check(Ad(ZP,r)),t.ipv6=r=>t.check(Id(qP,r)),t.cidrv4=r=>t.check(Od(FP,r)),t.cidrv6=r=>t.check(Cd(BP,r)),t.e164=r=>t.check(jd(KP,r)),t.datetime=r=>t.check(ap(r)),t.date=r=>t.check(cp(r)),t.time=r=>t.check(lp(r)),t.duration=r=>t.check(up(r))});Ue=I("ZodStringFormat",(t,e)=>{ze.init(t,e),Hw.init(t,e)}),OP=I("ZodEmail",(t,e)=>{Au.init(t,e),Ue.init(t,e)}),Fw=I("ZodGUID",(t,e)=>{Ru.init(t,e),Ue.init(t,e)}),ba=I("ZodUUID",(t,e)=>{Pu.init(t,e),Ue.init(t,e)}),CP=I("ZodURL",(t,e)=>{Iu.init(t,e),Ue.init(t,e)}),zP=I("ZodEmoji",(t,e)=>{Ou.init(t,e),Ue.init(t,e)}),NP=I("ZodNanoID",(t,e)=>{Cu.init(t,e),Ue.init(t,e)}),jP=I("ZodCUID",(t,e)=>{zu.init(t,e),Ue.init(t,e)}),LP=I("ZodCUID2",(t,e)=>{Nu.init(t,e),Ue.init(t,e)}),DP=I("ZodULID",(t,e)=>{ju.init(t,e),Ue.init(t,e)}),MP=I("ZodXID",(t,e)=>{Lu.init(t,e),Ue.init(t,e)}),UP=I("ZodKSUID",(t,e)=>{Du.init(t,e),Ue.init(t,e)}),ZP=I("ZodIPv4",(t,e)=>{Mu.init(t,e),Ue.init(t,e)}),qP=I("ZodIPv6",(t,e)=>{Uu.init(t,e),Ue.init(t,e)}),FP=I("ZodCIDRv4",(t,e)=>{Zu.init(t,e),Ue.init(t,e)}),BP=I("ZodCIDRv6",(t,e)=>{qu.init(t,e),Ue.init(t,e)}),VP=I("ZodBase64",(t,e)=>{Fu.init(t,e),Ue.init(t,e)}),HP=I("ZodBase64URL",(t,e)=>{Bu.init(t,e),Ue.init(t,e)}),KP=I("ZodE164",(t,e)=>{Vu.init(t,e),Ue.init(t,e)}),GP=I("ZodJWT",(t,e)=>{Hu.init(t,e),Ue.init(t,e)}),Kw=I("ZodNumber",(t,e)=>{sa.init(t,e),Be.init(t,e),t.gt=(n,o)=>t.check(da(n,o)),t.gte=(n,o)=>t.check(Ss(n,o)),t.min=(n,o)=>t.check(Ss(n,o)),t.lt=(n,o)=>t.check(ua(n,o)),t.lte=(n,o)=>t.check($s(n,o)),t.max=(n,o)=>t.check($s(n,o)),t.int=n=>t.check(Bw(n)),t.safe=n=>t.check(Bw(n)),t.positive=n=>t.check(da(0,n)),t.nonnegative=n=>t.check(Ss(0,n)),t.negative=n=>t.check(ua(0,n)),t.nonpositive=n=>t.check($s(0,n)),t.multipleOf=(n,o)=>t.check(pa(n,o)),t.step=(n,o)=>t.check(pa(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});WP=I("ZodNumberFormat",(t,e)=>{Ku.init(t,e),Kw.init(t,e)});JP=I("ZodBoolean",(t,e)=>{Gu.init(t,e),Be.init(t,e)});YP=I("ZodNull",(t,e)=>{Wu.init(t,e),Be.init(t,e)});XP=I("ZodUnknown",(t,e)=>{Ju.init(t,e),Be.init(t,e)});QP=I("ZodNever",(t,e)=>{Yu.init(t,e),Be.init(t,e)});tA=I("ZodArray",(t,e)=>{Xu.init(t,e),Be.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(fo(r,n)),t.nonempty=r=>t.check(fo(1,r)),t.max=(r,n)=>t.check(fa(r,n)),t.length=(r,n)=>t.check(ha(r,n)),t.unwrap=()=>t.element});Ww=I("ZodObject",(t,e)=>{ia.init(t,e),Be.init(t,e),be.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>kt(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Ze()}),t.loose=()=>t.clone({...t._zod.def,catchall:Ze()}),t.strict=()=>t.clone({...t._zod.def,catchall:eA()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>be.extend(t,r),t.merge=r=>be.merge(t,r),t.pick=r=>be.pick(t,r),t.omit=r=>be.omit(t,r),t.partial=(...r)=>be.partial(Xw,t,r[0]),t.required=(...r)=>be.required(Qw,t,r[0])});Jw=I("ZodUnion",(t,e)=>{aa.init(t,e),Be.init(t,e),t.options=e.options});rA=I("ZodDiscriminatedUnion",(t,e)=>{Jw.init(t,e),Qu.init(t,e)});nA=I("ZodIntersection",(t,e)=>{ed.init(t,e),Be.init(t,e)});oA=I("ZodRecord",(t,e)=>{td.init(t,e),Be.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});mp=I("ZodEnum",(t,e)=>{rd.init(t,e),Be.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 mp({...e,checks:[],...be.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 mp({...e,checks:[],...be.normalizeParams(o),entries:s})}});sA=I("ZodLiteral",(t,e)=>{nd.init(t,e),Be.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]}})});iA=I("ZodTransform",(t,e)=>{od.init(t,e),Be.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(be.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(be.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});Xw=I("ZodOptional",(t,e)=>{sd.init(t,e),Be.init(t,e),t.unwrap=()=>t._zod.def.innerType});aA=I("ZodNullable",(t,e)=>{id.init(t,e),Be.init(t,e),t.unwrap=()=>t._zod.def.innerType});cA=I("ZodDefault",(t,e)=>{ad.init(t,e),Be.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});uA=I("ZodPrefault",(t,e)=>{cd.init(t,e),Be.init(t,e),t.unwrap=()=>t._zod.def.innerType});Qw=I("ZodNonOptional",(t,e)=>{ld.init(t,e),Be.init(t,e),t.unwrap=()=>t._zod.def.innerType});fA=I("ZodCatch",(t,e)=>{ud.init(t,e),Be.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});mA=I("ZodPipe",(t,e)=>{dd.init(t,e),Be.init(t,e),t.in=e.in,t.out=e.out});gA=I("ZodReadonly",(t,e)=>{pd.init(t,e),Be.init(t,e)});e_=I("ZodCustom",(t,e)=>{fd.init(t,e),Be.init(t,e)})});var r_=O(()=>{});var n_=O(()=>{});var o_=O(()=>{ht();pp();ip();fp();hp();r_();ht();hw();ca();dp();n_();At(fw())});var s_=O(()=>{o_()});var i_=O(()=>{s_()});function k_(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function $_(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var _p,a_,Kr,va,Ye,c_,l_,jq,kA,$A,vp,Ot,Ps,u_,nt,Zt,qt,ot,xa,d_,xp,p_,f_,kp,As,X,$p,h_,m_,Lq,ka,SA,$a,TA,Is,go,g_,EA,RA,PA,AA,IA,OA,Sp,CA,zA,Tp,Sa,NA,jA,Ta,LA,Os,Cs,DA,zs,yo,MA,Ns,Ea,Ra,Pa,Dq,Aa,Ia,Oa,y_,b_,w_,Ep,__,js,bo,v_,UA,Ca,ZA,za,qA,Rp,FA,Na,BA,VA,HA,KA,GA,WA,JA,YA,XA,QA,ja,eI,tI,La,Pp,Ap,Ip,rI,nI,oI,Op,sI,iI,aI,cI,lI,x_,Da,uI,Ma,Mq,dI,wo,pI,Uq,Ls,fI,Cp,hI,mI,gI,yI,bI,wI,_I,_a,vI,xI,kI,Ds,zp,$I,SI,TI,EI,RI,PI,AI,II,OI,CI,zI,NI,jI,LI,DI,MI,UI,ZI,_o,qI,FI,BI,Ua,VI,HI,KI,Np,GI,Zq,qq,Fq,Bq,Vq,Hq,G,wp,vo=O(()=>{i_();_p="2025-11-25",a_=[_p,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Kr="io.modelcontextprotocol/related-task",va="2.0",Ye=t_(t=>t!==null&&(typeof t=="object"||typeof t=="function")),c_=je([A(),Te().int()]),l_=A(),jq=mt({ttl:Te().optional(),pollInterval:Te().optional()}),kA=B({ttl:Te().optional()}),$A=B({taskId:A()}),vp=mt({progressToken:c_.optional(),[Kr]:$A.optional()}),Ot=B({_meta:vp.optional()}),Ps=Ot.extend({task:kA.optional()}),u_=t=>Ps.safeParse(t).success,nt=B({method:A(),params:Ot.loose().optional()}),Zt=B({_meta:vp.optional()}),qt=B({method:A(),params:Zt.loose().optional()}),ot=mt({_meta:vp.optional()}),xa=je([A(),Te().int()]),d_=B({jsonrpc:W(va),id:xa,...nt.shape}).strict(),xp=t=>d_.safeParse(t).success,p_=B({jsonrpc:W(va),...qt.shape}).strict(),f_=t=>p_.safeParse(t).success,kp=B({jsonrpc:W(va),id:xa,result:ot}).strict(),As=t=>kp.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={}));$p=B({jsonrpc:W(va),id:xa.optional(),error:B({code:Te().int(),message:A(),data:Ze().optional()})}).strict(),h_=t=>$p.safeParse(t).success,m_=je([d_,p_,kp,$p]),Lq=je([kp,$p]),ka=ot.strict(),SA=Zt.extend({requestId:xa.optional(),reason:A().optional()}),$a=qt.extend({method:W("notifications/cancelled"),params:SA}),TA=B({src:A(),mimeType:A().optional(),sizes:we(A()).optional(),theme:kt(["light","dark"]).optional()}),Is=B({icons:we(TA).optional()}),go=B({name:A(),title:A().optional()}),g_=go.extend({...go.shape,...Is.shape,version:A(),websiteUrl:A().optional(),description:A().optional()}),EA=wa(B({applyDefaults:Qe().optional()}),Ne(A(),Ze())),RA=bp(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,wa(B({form:EA.optional(),url:Ye.optional()}),Ne(A(),Ze()).optional())),PA=mt({list:Ye.optional(),cancel:Ye.optional(),requests:mt({sampling:mt({createMessage:Ye.optional()}).optional(),elicitation:mt({create:Ye.optional()}).optional()}).optional()}),AA=mt({list:Ye.optional(),cancel:Ye.optional(),requests:mt({tools:mt({call:Ye.optional()}).optional()}).optional()}),IA=B({experimental:Ne(A(),Ye).optional(),sampling:B({context:Ye.optional(),tools:Ye.optional()}).optional(),elicitation:RA.optional(),roots:B({listChanged:Qe().optional()}).optional(),tasks:PA.optional(),extensions:Ne(A(),Ye).optional()}),OA=Ot.extend({protocolVersion:A(),capabilities:IA,clientInfo:g_}),Sp=nt.extend({method:W("initialize"),params:OA}),CA=B({experimental:Ne(A(),Ye).optional(),logging:Ye.optional(),completions:Ye.optional(),prompts:B({listChanged:Qe().optional()}).optional(),resources:B({subscribe:Qe().optional(),listChanged:Qe().optional()}).optional(),tools:B({listChanged:Qe().optional()}).optional(),tasks:AA.optional(),extensions:Ne(A(),Ye).optional()}),zA=ot.extend({protocolVersion:A(),capabilities:CA,serverInfo:g_,instructions:A().optional()}),Tp=qt.extend({method:W("notifications/initialized"),params:Zt.optional()}),Sa=nt.extend({method:W("ping"),params:Ot.optional()}),NA=B({progress:Te(),total:qe(Te()),message:qe(A())}),jA=B({...Zt.shape,...NA.shape,progressToken:c_}),Ta=qt.extend({method:W("notifications/progress"),params:jA}),LA=Ot.extend({cursor:l_.optional()}),Os=nt.extend({params:LA.optional()}),Cs=ot.extend({nextCursor:l_.optional()}),DA=kt(["working","input_required","completed","failed","cancelled"]),zs=B({taskId:A(),status:DA,ttl:je([Te(),Gw()]),createdAt:A(),lastUpdatedAt:A(),pollInterval:qe(Te()),statusMessage:qe(A())}),yo=ot.extend({task:zs}),MA=Zt.merge(zs),Ns=qt.extend({method:W("notifications/tasks/status"),params:MA}),Ea=nt.extend({method:W("tasks/get"),params:Ot.extend({taskId:A()})}),Ra=ot.merge(zs),Pa=nt.extend({method:W("tasks/result"),params:Ot.extend({taskId:A()})}),Dq=ot.loose(),Aa=Os.extend({method:W("tasks/list")}),Ia=Cs.extend({tasks:we(zs)}),Oa=nt.extend({method:W("tasks/cancel"),params:Ot.extend({taskId:A()})}),y_=ot.merge(zs),b_=B({uri:A(),mimeType:qe(A()),_meta:Ne(A(),Ze()).optional()}),w_=b_.extend({text:A()}),Ep=A().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),__=b_.extend({blob:Ep}),js=kt(["user","assistant"]),bo=B({audience:we(js).optional(),priority:Te().min(0).max(1).optional(),lastModified:Es.datetime({offset:!0}).optional()}),v_=B({...go.shape,...Is.shape,uri:A(),description:qe(A()),mimeType:qe(A()),size:qe(Te()),annotations:bo.optional(),_meta:qe(mt({}))}),UA=B({...go.shape,...Is.shape,uriTemplate:A(),description:qe(A()),mimeType:qe(A()),annotations:bo.optional(),_meta:qe(mt({}))}),Ca=Os.extend({method:W("resources/list")}),ZA=Cs.extend({resources:we(v_)}),za=Os.extend({method:W("resources/templates/list")}),qA=Cs.extend({resourceTemplates:we(UA)}),Rp=Ot.extend({uri:A()}),FA=Rp,Na=nt.extend({method:W("resources/read"),params:FA}),BA=ot.extend({contents:we(je([w_,__]))}),VA=qt.extend({method:W("notifications/resources/list_changed"),params:Zt.optional()}),HA=Rp,KA=nt.extend({method:W("resources/subscribe"),params:HA}),GA=Rp,WA=nt.extend({method:W("resources/unsubscribe"),params:GA}),JA=Zt.extend({uri:A()}),YA=qt.extend({method:W("notifications/resources/updated"),params:JA}),XA=B({name:A(),description:qe(A()),required:qe(Qe())}),QA=B({...go.shape,...Is.shape,description:qe(A()),arguments:qe(we(XA)),_meta:qe(mt({}))}),ja=Os.extend({method:W("prompts/list")}),eI=Cs.extend({prompts:we(QA)}),tI=Ot.extend({name:A(),arguments:Ne(A(),A()).optional()}),La=nt.extend({method:W("prompts/get"),params:tI}),Pp=B({type:W("text"),text:A(),annotations:bo.optional(),_meta:Ne(A(),Ze()).optional()}),Ap=B({type:W("image"),data:Ep,mimeType:A(),annotations:bo.optional(),_meta:Ne(A(),Ze()).optional()}),Ip=B({type:W("audio"),data:Ep,mimeType:A(),annotations:bo.optional(),_meta:Ne(A(),Ze()).optional()}),rI=B({type:W("tool_use"),name:A(),id:A(),input:Ne(A(),Ze()),_meta:Ne(A(),Ze()).optional()}),nI=B({type:W("resource"),resource:je([w_,__]),annotations:bo.optional(),_meta:Ne(A(),Ze()).optional()}),oI=v_.extend({type:W("resource_link")}),Op=je([Pp,Ap,Ip,oI,nI]),sI=B({role:js,content:Op}),iI=ot.extend({description:A().optional(),messages:we(sI)}),aI=qt.extend({method:W("notifications/prompts/list_changed"),params:Zt.optional()}),cI=B({title:A().optional(),readOnlyHint:Qe().optional(),destructiveHint:Qe().optional(),idempotentHint:Qe().optional(),openWorldHint:Qe().optional()}),lI=B({taskSupport:kt(["required","optional","forbidden"]).optional()}),x_=B({...go.shape,...Is.shape,description:A().optional(),inputSchema:B({type:W("object"),properties:Ne(A(),Ye).optional(),required:we(A()).optional()}).catchall(Ze()),outputSchema:B({type:W("object"),properties:Ne(A(),Ye).optional(),required:we(A()).optional()}).catchall(Ze()).optional(),annotations:cI.optional(),execution:lI.optional(),_meta:Ne(A(),Ze()).optional()}),Da=Os.extend({method:W("tools/list")}),uI=Cs.extend({tools:we(x_)}),Ma=ot.extend({content:we(Op).default([]),structuredContent:Ne(A(),Ze()).optional(),isError:Qe().optional()}),Mq=Ma.or(ot.extend({toolResult:Ze()})),dI=Ps.extend({name:A(),arguments:Ne(A(),Ze()).optional()}),wo=nt.extend({method:W("tools/call"),params:dI}),pI=qt.extend({method:W("notifications/tools/list_changed"),params:Zt.optional()}),Uq=B({autoRefresh:Qe().default(!0),debounceMs:Te().int().nonnegative().default(300)}),Ls=kt(["debug","info","notice","warning","error","critical","alert","emergency"]),fI=Ot.extend({level:Ls}),Cp=nt.extend({method:W("logging/setLevel"),params:fI}),hI=Zt.extend({level:Ls,logger:A().optional(),data:Ze()}),mI=qt.extend({method:W("notifications/message"),params:hI}),gI=B({name:A().optional()}),yI=B({hints:we(gI).optional(),costPriority:Te().min(0).max(1).optional(),speedPriority:Te().min(0).max(1).optional(),intelligencePriority:Te().min(0).max(1).optional()}),bI=B({mode:kt(["auto","required","none"]).optional()}),wI=B({type:W("tool_result"),toolUseId:A().describe("The unique identifier for the corresponding tool call."),content:we(Op).default([]),structuredContent:B({}).loose().optional(),isError:Qe().optional(),_meta:Ne(A(),Ze()).optional()}),_I=yp("type",[Pp,Ap,Ip]),_a=yp("type",[Pp,Ap,Ip,rI,wI]),vI=B({role:js,content:je([_a,we(_a)]),_meta:Ne(A(),Ze()).optional()}),xI=Ps.extend({messages:we(vI),modelPreferences:yI.optional(),systemPrompt:A().optional(),includeContext:kt(["none","thisServer","allServers"]).optional(),temperature:Te().optional(),maxTokens:Te().int(),stopSequences:we(A()).optional(),metadata:Ye.optional(),tools:we(x_).optional(),toolChoice:bI.optional()}),kI=nt.extend({method:W("sampling/createMessage"),params:xI}),Ds=ot.extend({model:A(),stopReason:qe(kt(["endTurn","stopSequence","maxTokens"]).or(A())),role:js,content:_I}),zp=ot.extend({model:A(),stopReason:qe(kt(["endTurn","stopSequence","maxTokens","toolUse"]).or(A())),role:js,content:je([_a,we(_a)])}),$I=B({type:W("boolean"),title:A().optional(),description:A().optional(),default:Qe().optional()}),SI=B({type:W("string"),title:A().optional(),description:A().optional(),minLength:Te().optional(),maxLength:Te().optional(),format:kt(["email","uri","date","date-time"]).optional(),default:A().optional()}),TI=B({type:kt(["number","integer"]),title:A().optional(),description:A().optional(),minimum:Te().optional(),maximum:Te().optional(),default:Te().optional()}),EI=B({type:W("string"),title:A().optional(),description:A().optional(),enum:we(A()),default:A().optional()}),RI=B({type:W("string"),title:A().optional(),description:A().optional(),oneOf:we(B({const:A(),title:A()})),default:A().optional()}),PI=B({type:W("string"),title:A().optional(),description:A().optional(),enum:we(A()),enumNames:we(A()).optional(),default:A().optional()}),AI=je([EI,RI]),II=B({type:W("array"),title:A().optional(),description:A().optional(),minItems:Te().optional(),maxItems:Te().optional(),items:B({type:W("string"),enum:we(A())}),default:we(A()).optional()}),OI=B({type:W("array"),title:A().optional(),description:A().optional(),minItems:Te().optional(),maxItems:Te().optional(),items:B({anyOf:we(B({const:A(),title:A()}))}),default:we(A()).optional()}),CI=je([II,OI]),zI=je([PI,AI,CI]),NI=je([zI,$I,SI,TI]),jI=Ps.extend({mode:W("form").optional(),message:A(),requestedSchema:B({type:W("object"),properties:Ne(A(),NI),required:we(A()).optional()})}),LI=Ps.extend({mode:W("url"),message:A(),elicitationId:A(),url:A().url()}),DI=je([jI,LI]),MI=nt.extend({method:W("elicitation/create"),params:DI}),UI=Zt.extend({elicitationId:A()}),ZI=qt.extend({method:W("notifications/elicitation/complete"),params:UI}),_o=ot.extend({action:kt(["accept","decline","cancel"]),content:bp(t=>t===null?void 0:t,Ne(A(),je([A(),Te(),Qe(),we(A())])).optional())}),qI=B({type:W("ref/resource"),uri:A()}),FI=B({type:W("ref/prompt"),name:A()}),BI=Ot.extend({ref:je([FI,qI]),argument:B({name:A(),value:A()}),context:B({arguments:Ne(A(),A()).optional()}).optional()}),Ua=nt.extend({method:W("completion/complete"),params:BI});VI=ot.extend({completion:mt({values:we(A()).max(100),total:qe(Te().int()),hasMore:qe(Qe())})}),HI=B({uri:A().startsWith("file://"),name:A().optional(),_meta:Ne(A(),Ze()).optional()}),KI=nt.extend({method:W("roots/list"),params:Ot.optional()}),Np=ot.extend({roots:we(HI)}),GI=qt.extend({method:W("notifications/roots/list_changed"),params:Zt.optional()}),Zq=je([Sa,Sp,Ua,Cp,La,ja,Ca,za,Na,KA,WA,wo,Da,Ea,Pa,Aa,Oa]),qq=je([$a,Ta,Tp,GI,Ns]),Fq=je([ka,Ds,zp,_o,Np,Ra,Ia,yo]),Bq=je([Sa,kI,MI,KI,Ea,Pa,Aa,Oa]),Vq=je([$a,Ta,mI,YA,VA,pI,aI,Ns,ZI]),Hq=je([ka,zA,VI,iI,eI,ZA,qA,BA,Ma,uI,Ra,Ia,yo]),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 wp(o.elicitations,r)}return new t(e,r,n)}},wp=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 Gr(t){return t==="completed"||t==="failed"||t==="cancelled"}var S_=O(()=>{});var E_,T_,R_,Za=O(()=>{E_=Symbol("Let zodToJsonSchema decide on which parser to use"),T_={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"},R_=t=>typeof t=="string"?{...T_,name:t}:{...T_,...t}});var P_,jp=O(()=>{Za();P_=t=>{let e=R_(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 Lp(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function _e(t,e,r,n,o){t[e]=r,Lp(t,e,n,o)}var Wr=O(()=>{});var qa,Fa=O(()=>{qa=(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 Fe(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?qa(e,t.currentPath):e.join("/")}}var Ft=O(()=>{Fa()});function A_(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==L.ZodAny&&(r.items=re(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&_e(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&_e(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(_e(r,"minItems",t.exactLength.value,t.exactLength.message,e),_e(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var Dp=O(()=>{fs();Wr();We()});function I_(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?_e(r,"minimum",n.value,n.message,e):_e(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),_e(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?_e(r,"maximum",n.value,n.message,e):_e(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),_e(r,"maximum",n.value,n.message,e));break;case"multipleOf":_e(r,"multipleOf",n.value,n.message,e);break}return r}var Mp=O(()=>{Wr()});function O_(){return{type:"boolean"}}var Up=O(()=>{});function Ba(t,e){return re(t.type._def,e)}var Va=O(()=>{We()});var C_,Zp=O(()=>{We();C_=(t,e)=>re(t.innerType._def,e)});function qp(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>qp(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 WI(t,e)}}var WI,Fp=O(()=>{Wr();WI=(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":_e(r,"minimum",n.value,n.message,e);break;case"max":_e(r,"maximum",n.value,n.message,e);break}return r}});function z_(t,e){return{...re(t.innerType._def,e),default:t.defaultValue()}}var Bp=O(()=>{We()});function N_(t,e){return e.effectStrategy==="input"?re(t.schema._def,e):Fe(e)}var Vp=O(()=>{We();Ft()});function j_(t){return{type:"string",enum:Array.from(t.values)}}var Hp=O(()=>{});function L_(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(JI(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 JI,Kp=O(()=>{We();JI=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function D_(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 Gp=O(()=>{});function Ha(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":_e(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":_e(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":Qt(r,"email",n.message,e);break;case"format:idn-email":Qt(r,"idn-email",n.message,e);break;case"pattern:zod":gt(r,Xt.email,n.message,e);break}break;case"url":Qt(r,"uri",n.message,e);break;case"uuid":Qt(r,"uuid",n.message,e);break;case"regex":gt(r,n.regex,n.message,e);break;case"cuid":gt(r,Xt.cuid,n.message,e);break;case"cuid2":gt(r,Xt.cuid2,n.message,e);break;case"startsWith":gt(r,RegExp(`^${Jp(n.value,e)}`),n.message,e);break;case"endsWith":gt(r,RegExp(`${Jp(n.value,e)}$`),n.message,e);break;case"datetime":Qt(r,"date-time",n.message,e);break;case"date":Qt(r,"date",n.message,e);break;case"time":Qt(r,"time",n.message,e);break;case"duration":Qt(r,"duration",n.message,e);break;case"length":_e(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),_e(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{gt(r,RegExp(Jp(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Qt(r,"ipv4",n.message,e),n.version!=="v4"&&Qt(r,"ipv6",n.message,e);break}case"base64url":gt(r,Xt.base64url,n.message,e);break;case"jwt":gt(r,Xt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&gt(r,Xt.ipv4Cidr,n.message,e),n.version!=="v4"&&gt(r,Xt.ipv6Cidr,n.message,e);break}case"emoji":gt(r,Xt.emoji(),n.message,e);break;case"ulid":{gt(r,Xt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Qt(r,"binary",n.message,e);break}case"contentEncoding:base64":{_e(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{gt(r,Xt.base64,n.message,e);break}}break}case"nanoid":gt(r,Xt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Jp(t,e){return e.patternStrategy==="escape"?XI(t):t}function XI(t){let e="";for(let r=0;r<t.length;r++)YI.has(t[r])||(e+="\\"),e+=t[r];return e}function Qt(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}}})):_e(t,"format",e,r,n)}function gt(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:M_(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):_e(t,"pattern",M_(e,n),r,n)}function M_(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
1272
+ 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 w=this.seen.get(u),m=w.def??w.schema,f={...m};if(w.ref===null)return;let b=w.ref;if(w.ref=null,b){a(b,d);let k=this.seen.get(b).schema;k.$ref&&d.target==="draft-7"?(m.allOf=m.allOf??[],m.allOf.push(k)):(Object.assign(m,k),Object.assign(m,f))}w.isParent||this.override({zodSchema:u,jsonSchema:m,path:w.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 qw=O(()=>{});var gt=O(()=>{uo();Ru();vu();Aw();aa();zu();dr();ia();fa();kd();Cu();Uw();Mw();Zw();qw()});var dp=O(()=>{gt()});function pp(t,e){let r={type:"object",get shape(){return be.assignProp(this,"shape",{...t}),this.shape},...be.normalizeParams(e)};return new GP(r)}var KP,GP,Fw=O(()=>{gt();gt();dp();KP=I("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");Ae.init(t,e),t.def=e,t.parse=(r,n)=>ku(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Rn(t,r,n),t.parseAsync=async(r,n)=>Su(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Pn(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)=>Ot(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),GP=I("ZodMiniObject",(t,e)=>{da.init(t,e),KP.init(t,e),be.defineLazy(t,"shape",()=>e.shape)})});var Bw=O(()=>{});var Vw=O(()=>{});var Hw=O(()=>{});var Kw=O(()=>{gt();dp();Fw();Bw();gt();fa();Vw();Hw()});var Gw=O(()=>{Kw()});var fp=O(()=>{Gw()});function pr(t){return!!t._zod}function On(t){let e=Object.values(t);if(e.length===0)return pp({});let r=e.every(pr),n=e.every(o=>!pr(o));if(r)return pp(t);if(n)return gl(t);throw new Error("Mixed Zod versions detected in object shape.")}function Kr(t,e){return pr(t)?Rn(t,e):t.safeParse(e)}async function va(t,e){return pr(t)?await Pn(t,e):await t.safeParseAsync(e)}function Gr(t){if(!t)return;let e;if(pr(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function mo(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 On(t)}}if(pr(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 YP(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function xa(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 ${YP(e.path)}`:e.message).join(`
1273
+ `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function Jw(t){return t.description}function Yw(t){if(pr(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function go(t){if(pr(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 Es=O(()=>{hs();fp()});var hp=O(()=>{gt()});var Rs={};Ho(Rs,{ZodISODate:()=>Qw,ZodISODateTime:()=>Xw,ZodISODuration:()=>t_,ZodISOTime:()=>e_,date:()=>gp,datetime:()=>mp,duration:()=>bp,time:()=>yp});function mp(t){return zw(Xw,t)}function gp(t){return Nw(Qw,t)}function yp(t){return jw(e_,t)}function bp(t){return Lw(t_,t)}var Xw,Qw,e_,t_,wp=O(()=>{gt();_p();Xw=I("ZodISODateTime",(t,e)=>{Sw.init(t,e),Ue.init(t,e)});Qw=I("ZodISODate",(t,e)=>{Tw.init(t,e),Ue.init(t,e)});e_=I("ZodISOTime",(t,e)=>{Ew.init(t,e),Ue.init(t,e)});t_=I("ZodISODuration",(t,e)=>{Rw.init(t,e),Ue.init(t,e)})});var r_,Qq,Ps,vp=O(()=>{gt();gt();r_=(t,e)=>{oa.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>_u(t,r)},flatten:{value:r=>wu(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},Qq=I("ZodError",r_),Ps=I("ZodError",r_,{Parent:Error})});var n_,o_,s_,i_,xp=O(()=>{gt();vp();n_=xu(Ps),o_=$u(Ps),s_=Tu(Ps),i_=Eu(Ps)});function A(t){return $d(sA,t)}function Te(t){return Hd(d_,t)}function c_(t){return Kd(kA,t)}function et(t){return Gd($A,t)}function p_(t){return Wd(SA,t)}function Ze(){return Jd(TA)}function RA(t){return Yd(EA,t)}function we(t,e){return Dw(PA,t,e)}function V(t,e){let r={type:"object",get shape(){return be.assignProp(this,"shape",{...t}),this.shape},...be.normalizeParams(e)};return new f_(r)}function yt(t,e){return new f_({type:"object",get shape(){return be.assignProp(this,"shape",{...t}),this.shape},catchall:Ze(),...be.normalizeParams(e)})}function je(t,e){return new h_({type:"union",options:t,...be.normalizeParams(e)})}function Sp(t,e,r){return new AA({type:"union",options:e,discriminator:t,...be.normalizeParams(r)})}function $a(t,e){return new IA({type:"intersection",left:t,right:e})}function Ne(t,e,r){return new OA({type:"record",keyType:t,valueType:e,...be.normalizeParams(r)})}function St(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new kp({type:"enum",entries:r,...be.normalizeParams(e)})}function W(t,e){return new CA({type:"literal",values:Array.isArray(t)?t:[t],...be.normalizeParams(e)})}function m_(t){return new zA({type:"transform",transform:t})}function qe(t){return new g_({type:"optional",innerType:t})}function l_(t){return new NA({type:"nullable",innerType:t})}function LA(t,e){return new jA({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function MA(t,e){return new DA({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function UA(t,e){return new y_({type:"nonoptional",innerType:t,...be.normalizeParams(e)})}function qA(t,e){return new ZA({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function $p(t,e){return new FA({type:"pipe",in:t,out:e})}function VA(t){return new BA({type:"readonly",innerType:t})}function HA(t){let e=new nt({check:"custom"});return e._zod.check=t,e}function w_(t,e){return cp(b_,t??(()=>!0),e)}function KA(t,e={}){return lp(b_,t,e)}function GA(t){let e=HA(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(be.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(be.issue(o))}},t(r.value,r)));return e}function Tp(t,e){return $p(m_(t),e)}var Be,u_,sA,Ue,iA,a_,ka,aA,cA,lA,uA,dA,pA,fA,hA,mA,gA,yA,bA,wA,_A,vA,xA,d_,kA,$A,SA,TA,EA,PA,f_,h_,AA,IA,OA,kp,CA,zA,g_,NA,jA,DA,y_,ZA,FA,BA,b_,_p=O(()=>{gt();gt();hp();wp();xp();Be=I("ZodType",(t,e)=>(Ae.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)=>Ot(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>n_(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>s_(t,r,n),t.parseAsync=async(r,n)=>o_(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>i_(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(KA(r,n)),t.superRefine=r=>t.check(GA(r)),t.overwrite=r=>t.check(An(r)),t.optional=()=>qe(t),t.nullable=()=>l_(t),t.nullish=()=>qe(l_(t)),t.nonoptional=r=>UA(t,r),t.array=()=>we(t),t.or=r=>je([t,r]),t.and=r=>$a(t,r),t.transform=r=>$p(t,m_(r)),t.default=r=>LA(t,r),t.prefault=r=>MA(t,r),t.catch=r=>qA(t,r),t.pipe=r=>$p(t,r),t.readonly=()=>VA(t),t.describe=r=>{let n=t.clone();return Hr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Hr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Hr.get(t);let n=t.clone();return Hr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),u_=I("_ZodString",(t,e)=>{ks.init(t,e),Be.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(Xd(...n)),t.includes=(...n)=>t.check(tp(...n)),t.startsWith=(...n)=>t.check(rp(...n)),t.endsWith=(...n)=>t.check(np(...n)),t.min=(...n)=>t.check(ho(...n)),t.max=(...n)=>t.check(ba(...n)),t.length=(...n)=>t.check(wa(...n)),t.nonempty=(...n)=>t.check(ho(1,...n)),t.lowercase=n=>t.check(Qd(n)),t.uppercase=n=>t.check(ep(n)),t.trim=()=>t.check(sp()),t.normalize=(...n)=>t.check(op(...n)),t.toLowerCase=()=>t.check(ip()),t.toUpperCase=()=>t.check(ap())}),sA=I("ZodString",(t,e)=>{ks.init(t,e),u_.init(t,e),t.email=r=>t.check(Sd(iA,r)),t.url=r=>t.check(Ad(aA,r)),t.jwt=r=>t.check(Vd(xA,r)),t.emoji=r=>t.check(Id(cA,r)),t.guid=r=>t.check(ha(a_,r)),t.uuid=r=>t.check(Td(ka,r)),t.uuidv4=r=>t.check(Ed(ka,r)),t.uuidv6=r=>t.check(Rd(ka,r)),t.uuidv7=r=>t.check(Pd(ka,r)),t.nanoid=r=>t.check(Od(lA,r)),t.guid=r=>t.check(ha(a_,r)),t.cuid=r=>t.check(Cd(uA,r)),t.cuid2=r=>t.check(zd(dA,r)),t.ulid=r=>t.check(Nd(pA,r)),t.base64=r=>t.check(qd(wA,r)),t.base64url=r=>t.check(Fd(_A,r)),t.xid=r=>t.check(jd(fA,r)),t.ksuid=r=>t.check(Ld(hA,r)),t.ipv4=r=>t.check(Dd(mA,r)),t.ipv6=r=>t.check(Md(gA,r)),t.cidrv4=r=>t.check(Ud(yA,r)),t.cidrv6=r=>t.check(Zd(bA,r)),t.e164=r=>t.check(Bd(vA,r)),t.datetime=r=>t.check(mp(r)),t.date=r=>t.check(gp(r)),t.time=r=>t.check(yp(r)),t.duration=r=>t.check(bp(r))});Ue=I("ZodStringFormat",(t,e)=>{ze.init(t,e),u_.init(t,e)}),iA=I("ZodEmail",(t,e)=>{Du.init(t,e),Ue.init(t,e)}),a_=I("ZodGUID",(t,e)=>{ju.init(t,e),Ue.init(t,e)}),ka=I("ZodUUID",(t,e)=>{Lu.init(t,e),Ue.init(t,e)}),aA=I("ZodURL",(t,e)=>{Mu.init(t,e),Ue.init(t,e)}),cA=I("ZodEmoji",(t,e)=>{Uu.init(t,e),Ue.init(t,e)}),lA=I("ZodNanoID",(t,e)=>{Zu.init(t,e),Ue.init(t,e)}),uA=I("ZodCUID",(t,e)=>{qu.init(t,e),Ue.init(t,e)}),dA=I("ZodCUID2",(t,e)=>{Fu.init(t,e),Ue.init(t,e)}),pA=I("ZodULID",(t,e)=>{Bu.init(t,e),Ue.init(t,e)}),fA=I("ZodXID",(t,e)=>{Vu.init(t,e),Ue.init(t,e)}),hA=I("ZodKSUID",(t,e)=>{Hu.init(t,e),Ue.init(t,e)}),mA=I("ZodIPv4",(t,e)=>{Ku.init(t,e),Ue.init(t,e)}),gA=I("ZodIPv6",(t,e)=>{Gu.init(t,e),Ue.init(t,e)}),yA=I("ZodCIDRv4",(t,e)=>{Wu.init(t,e),Ue.init(t,e)}),bA=I("ZodCIDRv6",(t,e)=>{Ju.init(t,e),Ue.init(t,e)}),wA=I("ZodBase64",(t,e)=>{Yu.init(t,e),Ue.init(t,e)}),_A=I("ZodBase64URL",(t,e)=>{Xu.init(t,e),Ue.init(t,e)}),vA=I("ZodE164",(t,e)=>{Qu.init(t,e),Ue.init(t,e)}),xA=I("ZodJWT",(t,e)=>{ed.init(t,e),Ue.init(t,e)}),d_=I("ZodNumber",(t,e)=>{ua.init(t,e),Be.init(t,e),t.gt=(n,o)=>t.check(ga(n,o)),t.gte=(n,o)=>t.check(Ts(n,o)),t.min=(n,o)=>t.check(Ts(n,o)),t.lt=(n,o)=>t.check(ma(n,o)),t.lte=(n,o)=>t.check(Ss(n,o)),t.max=(n,o)=>t.check(Ss(n,o)),t.int=n=>t.check(c_(n)),t.safe=n=>t.check(c_(n)),t.positive=n=>t.check(ga(0,n)),t.nonnegative=n=>t.check(Ts(0,n)),t.negative=n=>t.check(ma(0,n)),t.nonpositive=n=>t.check(Ss(0,n)),t.multipleOf=(n,o)=>t.check(ya(n,o)),t.step=(n,o)=>t.check(ya(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});kA=I("ZodNumberFormat",(t,e)=>{td.init(t,e),d_.init(t,e)});$A=I("ZodBoolean",(t,e)=>{rd.init(t,e),Be.init(t,e)});SA=I("ZodNull",(t,e)=>{nd.init(t,e),Be.init(t,e)});TA=I("ZodUnknown",(t,e)=>{od.init(t,e),Be.init(t,e)});EA=I("ZodNever",(t,e)=>{sd.init(t,e),Be.init(t,e)});PA=I("ZodArray",(t,e)=>{id.init(t,e),Be.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(ho(r,n)),t.nonempty=r=>t.check(ho(1,r)),t.max=(r,n)=>t.check(ba(r,n)),t.length=(r,n)=>t.check(wa(r,n)),t.unwrap=()=>t.element});f_=I("ZodObject",(t,e)=>{da.init(t,e),Be.init(t,e),be.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>St(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Ze()}),t.loose=()=>t.clone({...t._zod.def,catchall:Ze()}),t.strict=()=>t.clone({...t._zod.def,catchall:RA()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>be.extend(t,r),t.merge=r=>be.merge(t,r),t.pick=r=>be.pick(t,r),t.omit=r=>be.omit(t,r),t.partial=(...r)=>be.partial(g_,t,r[0]),t.required=(...r)=>be.required(y_,t,r[0])});h_=I("ZodUnion",(t,e)=>{pa.init(t,e),Be.init(t,e),t.options=e.options});AA=I("ZodDiscriminatedUnion",(t,e)=>{h_.init(t,e),ad.init(t,e)});IA=I("ZodIntersection",(t,e)=>{cd.init(t,e),Be.init(t,e)});OA=I("ZodRecord",(t,e)=>{ld.init(t,e),Be.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});kp=I("ZodEnum",(t,e)=>{ud.init(t,e),Be.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 kp({...e,checks:[],...be.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 kp({...e,checks:[],...be.normalizeParams(o),entries:s})}});CA=I("ZodLiteral",(t,e)=>{dd.init(t,e),Be.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]}})});zA=I("ZodTransform",(t,e)=>{pd.init(t,e),Be.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(be.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(be.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});g_=I("ZodOptional",(t,e)=>{fd.init(t,e),Be.init(t,e),t.unwrap=()=>t._zod.def.innerType});NA=I("ZodNullable",(t,e)=>{hd.init(t,e),Be.init(t,e),t.unwrap=()=>t._zod.def.innerType});jA=I("ZodDefault",(t,e)=>{md.init(t,e),Be.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});DA=I("ZodPrefault",(t,e)=>{gd.init(t,e),Be.init(t,e),t.unwrap=()=>t._zod.def.innerType});y_=I("ZodNonOptional",(t,e)=>{yd.init(t,e),Be.init(t,e),t.unwrap=()=>t._zod.def.innerType});ZA=I("ZodCatch",(t,e)=>{bd.init(t,e),Be.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});FA=I("ZodPipe",(t,e)=>{wd.init(t,e),Be.init(t,e),t.in=e.in,t.out=e.out});BA=I("ZodReadonly",(t,e)=>{_d.init(t,e),Be.init(t,e)});b_=I("ZodCustom",(t,e)=>{vd.init(t,e),Be.init(t,e)})});var __=O(()=>{});var v_=O(()=>{});var x_=O(()=>{gt();_p();hp();vp();xp();__();gt();Ow();fa();wp();v_();It(Iw())});var k_=O(()=>{x_()});var $_=O(()=>{k_()});function Z_(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function q_(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Rp,S_,Wr,Ta,Xe,T_,E_,mF,YA,XA,Pp,Ct,As,R_,ot,qt,Ft,st,Ea,P_,Ap,A_,I_,Ip,Is,Q,Op,O_,C_,gF,Ra,QA,Pa,eI,Os,yo,z_,tI,rI,nI,oI,sI,iI,Cp,aI,cI,zp,Aa,lI,uI,Ia,dI,Cs,zs,pI,Ns,bo,fI,js,Oa,Ca,za,yF,Na,ja,La,N_,j_,L_,Np,D_,Ls,wo,M_,hI,Da,mI,Ma,gI,jp,yI,Ua,bI,wI,_I,vI,xI,kI,$I,SI,TI,EI,Za,RI,PI,qa,Lp,Dp,Mp,AI,II,OI,Up,CI,zI,NI,jI,LI,U_,Fa,DI,Ba,bF,MI,_o,UI,wF,Ds,ZI,Zp,qI,FI,BI,VI,HI,KI,GI,Sa,WI,JI,YI,Ms,qp,XI,QI,eO,tO,rO,nO,oO,sO,iO,aO,cO,lO,uO,dO,pO,fO,hO,mO,vo,gO,yO,bO,Va,wO,_O,vO,Fp,xO,_F,vF,xF,kF,$F,SF,G,Ep,xo=O(()=>{$_();Rp="2025-11-25",S_=[Rp,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Wr="io.modelcontextprotocol/related-task",Ta="2.0",Xe=w_(t=>t!==null&&(typeof t=="object"||typeof t=="function")),T_=je([A(),Te().int()]),E_=A(),mF=yt({ttl:Te().optional(),pollInterval:Te().optional()}),YA=V({ttl:Te().optional()}),XA=V({taskId:A()}),Pp=yt({progressToken:T_.optional(),[Wr]:XA.optional()}),Ct=V({_meta:Pp.optional()}),As=Ct.extend({task:YA.optional()}),R_=t=>As.safeParse(t).success,ot=V({method:A(),params:Ct.loose().optional()}),qt=V({_meta:Pp.optional()}),Ft=V({method:A(),params:qt.loose().optional()}),st=yt({_meta:Pp.optional()}),Ea=je([A(),Te().int()]),P_=V({jsonrpc:W(Ta),id:Ea,...ot.shape}).strict(),Ap=t=>P_.safeParse(t).success,A_=V({jsonrpc:W(Ta),...Ft.shape}).strict(),I_=t=>A_.safeParse(t).success,Ip=V({jsonrpc:W(Ta),id:Ea,result:st}).strict(),Is=t=>Ip.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"})(Q||(Q={}));Op=V({jsonrpc:W(Ta),id:Ea.optional(),error:V({code:Te().int(),message:A(),data:Ze().optional()})}).strict(),O_=t=>Op.safeParse(t).success,C_=je([P_,A_,Ip,Op]),gF=je([Ip,Op]),Ra=st.strict(),QA=qt.extend({requestId:Ea.optional(),reason:A().optional()}),Pa=Ft.extend({method:W("notifications/cancelled"),params:QA}),eI=V({src:A(),mimeType:A().optional(),sizes:we(A()).optional(),theme:St(["light","dark"]).optional()}),Os=V({icons:we(eI).optional()}),yo=V({name:A(),title:A().optional()}),z_=yo.extend({...yo.shape,...Os.shape,version:A(),websiteUrl:A().optional(),description:A().optional()}),tI=$a(V({applyDefaults:et().optional()}),Ne(A(),Ze())),rI=Tp(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,$a(V({form:tI.optional(),url:Xe.optional()}),Ne(A(),Ze()).optional())),nI=yt({list:Xe.optional(),cancel:Xe.optional(),requests:yt({sampling:yt({createMessage:Xe.optional()}).optional(),elicitation:yt({create:Xe.optional()}).optional()}).optional()}),oI=yt({list:Xe.optional(),cancel:Xe.optional(),requests:yt({tools:yt({call:Xe.optional()}).optional()}).optional()}),sI=V({experimental:Ne(A(),Xe).optional(),sampling:V({context:Xe.optional(),tools:Xe.optional()}).optional(),elicitation:rI.optional(),roots:V({listChanged:et().optional()}).optional(),tasks:nI.optional(),extensions:Ne(A(),Xe).optional()}),iI=Ct.extend({protocolVersion:A(),capabilities:sI,clientInfo:z_}),Cp=ot.extend({method:W("initialize"),params:iI}),aI=V({experimental:Ne(A(),Xe).optional(),logging:Xe.optional(),completions:Xe.optional(),prompts:V({listChanged:et().optional()}).optional(),resources:V({subscribe:et().optional(),listChanged:et().optional()}).optional(),tools:V({listChanged:et().optional()}).optional(),tasks:oI.optional(),extensions:Ne(A(),Xe).optional()}),cI=st.extend({protocolVersion:A(),capabilities:aI,serverInfo:z_,instructions:A().optional()}),zp=Ft.extend({method:W("notifications/initialized"),params:qt.optional()}),Aa=ot.extend({method:W("ping"),params:Ct.optional()}),lI=V({progress:Te(),total:qe(Te()),message:qe(A())}),uI=V({...qt.shape,...lI.shape,progressToken:T_}),Ia=Ft.extend({method:W("notifications/progress"),params:uI}),dI=Ct.extend({cursor:E_.optional()}),Cs=ot.extend({params:dI.optional()}),zs=st.extend({nextCursor:E_.optional()}),pI=St(["working","input_required","completed","failed","cancelled"]),Ns=V({taskId:A(),status:pI,ttl:je([Te(),p_()]),createdAt:A(),lastUpdatedAt:A(),pollInterval:qe(Te()),statusMessage:qe(A())}),bo=st.extend({task:Ns}),fI=qt.merge(Ns),js=Ft.extend({method:W("notifications/tasks/status"),params:fI}),Oa=ot.extend({method:W("tasks/get"),params:Ct.extend({taskId:A()})}),Ca=st.merge(Ns),za=ot.extend({method:W("tasks/result"),params:Ct.extend({taskId:A()})}),yF=st.loose(),Na=Cs.extend({method:W("tasks/list")}),ja=zs.extend({tasks:we(Ns)}),La=ot.extend({method:W("tasks/cancel"),params:Ct.extend({taskId:A()})}),N_=st.merge(Ns),j_=V({uri:A(),mimeType:qe(A()),_meta:Ne(A(),Ze()).optional()}),L_=j_.extend({text:A()}),Np=A().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),D_=j_.extend({blob:Np}),Ls=St(["user","assistant"]),wo=V({audience:we(Ls).optional(),priority:Te().min(0).max(1).optional(),lastModified:Rs.datetime({offset:!0}).optional()}),M_=V({...yo.shape,...Os.shape,uri:A(),description:qe(A()),mimeType:qe(A()),size:qe(Te()),annotations:wo.optional(),_meta:qe(yt({}))}),hI=V({...yo.shape,...Os.shape,uriTemplate:A(),description:qe(A()),mimeType:qe(A()),annotations:wo.optional(),_meta:qe(yt({}))}),Da=Cs.extend({method:W("resources/list")}),mI=zs.extend({resources:we(M_)}),Ma=Cs.extend({method:W("resources/templates/list")}),gI=zs.extend({resourceTemplates:we(hI)}),jp=Ct.extend({uri:A()}),yI=jp,Ua=ot.extend({method:W("resources/read"),params:yI}),bI=st.extend({contents:we(je([L_,D_]))}),wI=Ft.extend({method:W("notifications/resources/list_changed"),params:qt.optional()}),_I=jp,vI=ot.extend({method:W("resources/subscribe"),params:_I}),xI=jp,kI=ot.extend({method:W("resources/unsubscribe"),params:xI}),$I=qt.extend({uri:A()}),SI=Ft.extend({method:W("notifications/resources/updated"),params:$I}),TI=V({name:A(),description:qe(A()),required:qe(et())}),EI=V({...yo.shape,...Os.shape,description:qe(A()),arguments:qe(we(TI)),_meta:qe(yt({}))}),Za=Cs.extend({method:W("prompts/list")}),RI=zs.extend({prompts:we(EI)}),PI=Ct.extend({name:A(),arguments:Ne(A(),A()).optional()}),qa=ot.extend({method:W("prompts/get"),params:PI}),Lp=V({type:W("text"),text:A(),annotations:wo.optional(),_meta:Ne(A(),Ze()).optional()}),Dp=V({type:W("image"),data:Np,mimeType:A(),annotations:wo.optional(),_meta:Ne(A(),Ze()).optional()}),Mp=V({type:W("audio"),data:Np,mimeType:A(),annotations:wo.optional(),_meta:Ne(A(),Ze()).optional()}),AI=V({type:W("tool_use"),name:A(),id:A(),input:Ne(A(),Ze()),_meta:Ne(A(),Ze()).optional()}),II=V({type:W("resource"),resource:je([L_,D_]),annotations:wo.optional(),_meta:Ne(A(),Ze()).optional()}),OI=M_.extend({type:W("resource_link")}),Up=je([Lp,Dp,Mp,OI,II]),CI=V({role:Ls,content:Up}),zI=st.extend({description:A().optional(),messages:we(CI)}),NI=Ft.extend({method:W("notifications/prompts/list_changed"),params:qt.optional()}),jI=V({title:A().optional(),readOnlyHint:et().optional(),destructiveHint:et().optional(),idempotentHint:et().optional(),openWorldHint:et().optional()}),LI=V({taskSupport:St(["required","optional","forbidden"]).optional()}),U_=V({...yo.shape,...Os.shape,description:A().optional(),inputSchema:V({type:W("object"),properties:Ne(A(),Xe).optional(),required:we(A()).optional()}).catchall(Ze()),outputSchema:V({type:W("object"),properties:Ne(A(),Xe).optional(),required:we(A()).optional()}).catchall(Ze()).optional(),annotations:jI.optional(),execution:LI.optional(),_meta:Ne(A(),Ze()).optional()}),Fa=Cs.extend({method:W("tools/list")}),DI=zs.extend({tools:we(U_)}),Ba=st.extend({content:we(Up).default([]),structuredContent:Ne(A(),Ze()).optional(),isError:et().optional()}),bF=Ba.or(st.extend({toolResult:Ze()})),MI=As.extend({name:A(),arguments:Ne(A(),Ze()).optional()}),_o=ot.extend({method:W("tools/call"),params:MI}),UI=Ft.extend({method:W("notifications/tools/list_changed"),params:qt.optional()}),wF=V({autoRefresh:et().default(!0),debounceMs:Te().int().nonnegative().default(300)}),Ds=St(["debug","info","notice","warning","error","critical","alert","emergency"]),ZI=Ct.extend({level:Ds}),Zp=ot.extend({method:W("logging/setLevel"),params:ZI}),qI=qt.extend({level:Ds,logger:A().optional(),data:Ze()}),FI=Ft.extend({method:W("notifications/message"),params:qI}),BI=V({name:A().optional()}),VI=V({hints:we(BI).optional(),costPriority:Te().min(0).max(1).optional(),speedPriority:Te().min(0).max(1).optional(),intelligencePriority:Te().min(0).max(1).optional()}),HI=V({mode:St(["auto","required","none"]).optional()}),KI=V({type:W("tool_result"),toolUseId:A().describe("The unique identifier for the corresponding tool call."),content:we(Up).default([]),structuredContent:V({}).loose().optional(),isError:et().optional(),_meta:Ne(A(),Ze()).optional()}),GI=Sp("type",[Lp,Dp,Mp]),Sa=Sp("type",[Lp,Dp,Mp,AI,KI]),WI=V({role:Ls,content:je([Sa,we(Sa)]),_meta:Ne(A(),Ze()).optional()}),JI=As.extend({messages:we(WI),modelPreferences:VI.optional(),systemPrompt:A().optional(),includeContext:St(["none","thisServer","allServers"]).optional(),temperature:Te().optional(),maxTokens:Te().int(),stopSequences:we(A()).optional(),metadata:Xe.optional(),tools:we(U_).optional(),toolChoice:HI.optional()}),YI=ot.extend({method:W("sampling/createMessage"),params:JI}),Ms=st.extend({model:A(),stopReason:qe(St(["endTurn","stopSequence","maxTokens"]).or(A())),role:Ls,content:GI}),qp=st.extend({model:A(),stopReason:qe(St(["endTurn","stopSequence","maxTokens","toolUse"]).or(A())),role:Ls,content:je([Sa,we(Sa)])}),XI=V({type:W("boolean"),title:A().optional(),description:A().optional(),default:et().optional()}),QI=V({type:W("string"),title:A().optional(),description:A().optional(),minLength:Te().optional(),maxLength:Te().optional(),format:St(["email","uri","date","date-time"]).optional(),default:A().optional()}),eO=V({type:St(["number","integer"]),title:A().optional(),description:A().optional(),minimum:Te().optional(),maximum:Te().optional(),default:Te().optional()}),tO=V({type:W("string"),title:A().optional(),description:A().optional(),enum:we(A()),default:A().optional()}),rO=V({type:W("string"),title:A().optional(),description:A().optional(),oneOf:we(V({const:A(),title:A()})),default:A().optional()}),nO=V({type:W("string"),title:A().optional(),description:A().optional(),enum:we(A()),enumNames:we(A()).optional(),default:A().optional()}),oO=je([tO,rO]),sO=V({type:W("array"),title:A().optional(),description:A().optional(),minItems:Te().optional(),maxItems:Te().optional(),items:V({type:W("string"),enum:we(A())}),default:we(A()).optional()}),iO=V({type:W("array"),title:A().optional(),description:A().optional(),minItems:Te().optional(),maxItems:Te().optional(),items:V({anyOf:we(V({const:A(),title:A()}))}),default:we(A()).optional()}),aO=je([sO,iO]),cO=je([nO,oO,aO]),lO=je([cO,XI,QI,eO]),uO=As.extend({mode:W("form").optional(),message:A(),requestedSchema:V({type:W("object"),properties:Ne(A(),lO),required:we(A()).optional()})}),dO=As.extend({mode:W("url"),message:A(),elicitationId:A(),url:A().url()}),pO=je([uO,dO]),fO=ot.extend({method:W("elicitation/create"),params:pO}),hO=qt.extend({elicitationId:A()}),mO=Ft.extend({method:W("notifications/elicitation/complete"),params:hO}),vo=st.extend({action:St(["accept","decline","cancel"]),content:Tp(t=>t===null?void 0:t,Ne(A(),je([A(),Te(),et(),we(A())])).optional())}),gO=V({type:W("ref/resource"),uri:A()}),yO=V({type:W("ref/prompt"),name:A()}),bO=Ct.extend({ref:je([yO,gO]),argument:V({name:A(),value:A()}),context:V({arguments:Ne(A(),A()).optional()}).optional()}),Va=ot.extend({method:W("completion/complete"),params:bO});wO=st.extend({completion:yt({values:we(A()).max(100),total:qe(Te().int()),hasMore:qe(et())})}),_O=V({uri:A().startsWith("file://"),name:A().optional(),_meta:Ne(A(),Ze()).optional()}),vO=ot.extend({method:W("roots/list"),params:Ct.optional()}),Fp=st.extend({roots:we(_O)}),xO=Ft.extend({method:W("notifications/roots/list_changed"),params:qt.optional()}),_F=je([Aa,Cp,Va,Zp,qa,Za,Da,Ma,Ua,vI,kI,_o,Fa,Oa,za,Na,La]),vF=je([Pa,Ia,zp,xO,js]),xF=je([Ra,Ms,qp,vo,Fp,Ca,ja,bo]),kF=je([Aa,YI,fO,vO,Oa,za,Na,La]),$F=je([Pa,Ia,FI,SI,wI,UI,NI,js,mO]),SF=je([Ra,cI,wO,zI,RI,mI,gI,bI,Ba,DI,Ca,ja,bo]),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===Q.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Ep(o.elicitations,r)}return new t(e,r,n)}},Ep=class extends G{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(Q.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Jr(t){return t==="completed"||t==="failed"||t==="cancelled"}var F_=O(()=>{});var V_,B_,H_,Ha=O(()=>{V_=Symbol("Let zodToJsonSchema decide on which parser to use"),B_={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"},H_=t=>typeof t=="string"?{...B_,name:t}:{...B_,...t}});var K_,Bp=O(()=>{Ha();K_=t=>{let e=H_(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 Vp(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function _e(t,e,r,n,o){t[e]=r,Vp(t,e,n,o)}var Yr=O(()=>{});var Ka,Ga=O(()=>{Ka=(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 Fe(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Ka(e,t.currentPath):e.join("/")}}var Bt=O(()=>{Ga()});function G_(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==D.ZodAny&&(r.items=ne(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&_e(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&_e(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(_e(r,"minItems",t.exactLength.value,t.exactLength.message,e),_e(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var Hp=O(()=>{hs();Yr();Je()});function W_(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?_e(r,"minimum",n.value,n.message,e):_e(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),_e(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?_e(r,"maximum",n.value,n.message,e):_e(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),_e(r,"maximum",n.value,n.message,e));break;case"multipleOf":_e(r,"multipleOf",n.value,n.message,e);break}return r}var Kp=O(()=>{Yr()});function J_(){return{type:"boolean"}}var Gp=O(()=>{});function Wa(t,e){return ne(t.type._def,e)}var Ja=O(()=>{Je()});var Y_,Wp=O(()=>{Je();Y_=(t,e)=>ne(t.innerType._def,e)});function Jp(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Jp(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 kO(t,e)}}var kO,Yp=O(()=>{Yr();kO=(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":_e(r,"minimum",n.value,n.message,e);break;case"max":_e(r,"maximum",n.value,n.message,e);break}return r}});function X_(t,e){return{...ne(t.innerType._def,e),default:t.defaultValue()}}var Xp=O(()=>{Je()});function Q_(t,e){return e.effectStrategy==="input"?ne(t.schema._def,e):Fe(e)}var Qp=O(()=>{Je();Bt()});function ev(t){return{type:"string",enum:Array.from(t.values)}}var ef=O(()=>{});function tv(t,e){let r=[ne(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),ne(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($O(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 $O,tf=O(()=>{Je();$O=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function rv(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 rf=O(()=>{});function Ya(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":_e(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":_e(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":tr(r,"email",n.message,e);break;case"format:idn-email":tr(r,"idn-email",n.message,e);break;case"pattern:zod":bt(r,er.email,n.message,e);break}break;case"url":tr(r,"uri",n.message,e);break;case"uuid":tr(r,"uuid",n.message,e);break;case"regex":bt(r,n.regex,n.message,e);break;case"cuid":bt(r,er.cuid,n.message,e);break;case"cuid2":bt(r,er.cuid2,n.message,e);break;case"startsWith":bt(r,RegExp(`^${of(n.value,e)}`),n.message,e);break;case"endsWith":bt(r,RegExp(`${of(n.value,e)}$`),n.message,e);break;case"datetime":tr(r,"date-time",n.message,e);break;case"date":tr(r,"date",n.message,e);break;case"time":tr(r,"time",n.message,e);break;case"duration":tr(r,"duration",n.message,e);break;case"length":_e(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),_e(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{bt(r,RegExp(of(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&tr(r,"ipv4",n.message,e),n.version!=="v4"&&tr(r,"ipv6",n.message,e);break}case"base64url":bt(r,er.base64url,n.message,e);break;case"jwt":bt(r,er.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&bt(r,er.ipv4Cidr,n.message,e),n.version!=="v4"&&bt(r,er.ipv6Cidr,n.message,e);break}case"emoji":bt(r,er.emoji(),n.message,e);break;case"ulid":{bt(r,er.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{tr(r,"binary",n.message,e);break}case"contentEncoding:base64":{_e(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{bt(r,er.base64,n.message,e);break}}break}case"nanoid":bt(r,er.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function of(t,e){return e.patternStrategy==="escape"?TO(t):t}function TO(t){let e="";for(let r=0;r<t.length;r++)SO.has(t[r])||(e+="\\"),e+=t[r];return e}function tr(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}}})):_e(t,"format",e,r,n)}function bt(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:nv(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):_e(t,"pattern",nv(e,n),r,n)}function nv(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
1129
1274
  ]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
1130
1275
  ]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
1131
1276
  `:`[${n[c]}\r
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 Wp,Xt,YI,Ka=O(()=>{Wr();Xt={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:()=>(Wp===void 0&&(Wp=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Wp),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-_]*$/};YI=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function Ga(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===L.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]})??Fe(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===L.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Ha(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===L.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===L.ZodBranded&&t.keyType._def.type._def.typeName===L.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Ba(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var Wa=O(()=>{fs();We();Ka();Va();Ft()});function U_(t,e){if(e.mapStrategy==="record")return Ga(t,e);let r=re(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Fe(e),n=re(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Fe(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var Yp=O(()=>{We();Wa();Ft()});function Z_(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 Xp=O(()=>{});function q_(t){return t.target==="openAi"?void 0:{not:Fe({...t,currentPath:[...t.currentPath,"not"]})}}var Qp=O(()=>{Ft()});function F_(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ef=O(()=>{});function V_(t,e){if(e.target==="openApi3")return B_(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Ms&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Ms[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 B_(t,e)}var Ms,B_,Ja=O(()=>{We();Ms={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};B_=(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 H_(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:Ms[t.innerType._def.typeName],nullable:!0}:{type:[Ms[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 tf=O(()=>{We();Ja()});function K_(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",Lp(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?_e(r,"minimum",n.value,n.message,e):_e(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),_e(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?_e(r,"maximum",n.value,n.message,e):_e(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),_e(r,"maximum",n.value,n.message,e));break;case"multipleOf":_e(r,"multipleOf",n.value,n.message,e);break}return r}var rf=O(()=>{Wr()});function G_(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=eO(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=QI(t,e);return i!==void 0&&(n.additionalProperties=i),n}function QI(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 eO(t){try{return t.isOptional()}catch{return!0}}var nf=O(()=>{We()});var W_,of=O(()=>{We();Ft();W_=(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:Fe(e)},r]}:Fe(e)}});var J_,sf=O(()=>{We();J_=(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 Y_(t,e){return re(t.type._def,e)}var af=O(()=>{We()});function X_(t,e){let n={type:"array",uniqueItems:!0,items:re(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&_e(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&_e(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var cf=O(()=>{Wr();We()});function Q_(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 lf=O(()=>{We()});function ev(t){return{not:Fe(t)}}var uf=O(()=>{Ft()});function tv(t){return Fe(t)}var df=O(()=>{Ft()});var rv,pf=O(()=>{We();rv=(t,e)=>re(t.innerType._def,e)});var nv,ff=O(()=>{fs();Ft();Dp();Mp();Up();Va();Zp();Fp();Bp();Vp();Hp();Kp();Gp();Yp();Xp();Qp();ef();tf();rf();nf();of();sf();af();Wa();cf();Ka();lf();uf();Ja();df();pf();nv=(t,e,r)=>{switch(e){case L.ZodString:return Ha(t,r);case L.ZodNumber:return K_(t,r);case L.ZodObject:return G_(t,r);case L.ZodBigInt:return I_(t,r);case L.ZodBoolean:return O_();case L.ZodDate:return qp(t,r);case L.ZodUndefined:return ev(r);case L.ZodNull:return F_(r);case L.ZodArray:return A_(t,r);case L.ZodUnion:case L.ZodDiscriminatedUnion:return V_(t,r);case L.ZodIntersection:return L_(t,r);case L.ZodTuple:return Q_(t,r);case L.ZodRecord:return Ga(t,r);case L.ZodLiteral:return D_(t,r);case L.ZodEnum:return j_(t);case L.ZodNativeEnum:return Z_(t);case L.ZodNullable:return H_(t,r);case L.ZodOptional:return W_(t,r);case L.ZodMap:return U_(t,r);case L.ZodSet:return X_(t,r);case L.ZodLazy:return()=>t.getter()._def;case L.ZodPromise:return Y_(t,r);case L.ZodNaN:case L.ZodNever:return q_(r);case L.ZodEffects:return N_(t,r);case L.ZodAny:return Fe(r);case L.ZodUnknown:return tv(r);case L.ZodDefault:return z_(t,r);case L.ZodBranded:return Ba(t,r);case L.ZodReadonly:return rv(t,r);case L.ZodCatch:return C_(t,r);case L.ZodPipeline:return J_(t,r);case L.ZodFunction:case L.ZodVoid:case L.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!==E_)return a}if(n&&!r){let a=tO(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=nv(t,t.typeName,e),i=typeof s=="function"?re(s(),e):s;if(i&&rO(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var tO,rO,We=O(()=>{Za();ff();Fa();Ft();tO=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:qa(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`),Fe(e)):e.$refStrategy==="seen"?Fe(e):void 0}},rO=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var ov=O(()=>{});var hf,mf=O(()=>{We();jp();Ft();hf=(t,e)=>{let r=P_(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)??Fe(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)??Fe(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 sv=O(()=>{Za();jp();Wr();Fa();We();ov();Ft();Dp();Mp();Up();Va();Zp();Fp();Bp();Vp();Hp();Kp();Gp();Yp();Xp();Qp();ef();tf();rf();nf();of();sf();af();pf();Wa();cf();Ka();lf();uf();Ja();df();ff();mf();mf()});function nO(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function gf(t,e){return dr(t)?rp(t,{target:nO(e?.target),io:e?.pipeStrategy??"input"}):hf(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function yf(t){let r=Hr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=mo(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function bf(t,e){let r=Vr(t,e);if(!r.success)throw r.error;return r.data}var wf=O(()=>{sp();Ts();sv()});function iv(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function av(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];iv(i)&&iv(s)?r[o]={...i,...s}:r[o]=s}return r}var oO,Ya,cv=O(()=>{Ts();vo();S_();wf();oO=6e4,Ya=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($a,r=>{this._oncancel(r)}),this.setNotificationHandler(Ta,r=>{this._onprogress(r)}),this.setRequestHandler(Sa,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ea,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(Pa,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(!Gr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Gr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Kr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Aa,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(Oa,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(Gr(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),As(s)||h_(s)?this._onresponse(s):xp(s)?this._onrequest(s,i):f_(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?.[Kr]?.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=u_(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),As(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(As(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),As(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,yo,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},Gr(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=P=>{u(P)};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(P){d(P);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||{},[Kr]:c}});let f=P=>{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(P)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(V=>this._onerror(new Error(`Failed to send cancellation: ${V}`)));let z=P instanceof G?P:new G(X.RequestTimeout,String(P));u(z)};this._responseHandlers.set(b,P=>{if(!n?.signal?.aborted){if(P instanceof Error)return u(P);try{let z=Vr(r,P.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??oO,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 P=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,P),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(P=>{this._cleanupTimeout(b),u(P)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Ra,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},Ia,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},y_,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||{},[Kr]: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||{},[Kr]: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||{},[Kr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=yf(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=bf(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=yf(e);this._notificationHandlers.set(n,o=>{let s=bf(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"&&xp(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=Ns.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Gr(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(Gr(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=Ns.parse({method:"notifications/tasks/status",params:c});await this.notification(l),Gr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var qs=Z(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.regexpCode=Se.getEsmExportName=Se.getProperty=Se.safeStringify=Se.stringify=Se.strConcat=Se.addCodeArg=Se.str=Se._=Se.nil=Se._Code=Se.Name=Se.IDENTIFIER=Se._CodeOrName=void 0;var Us=class{};Se._CodeOrName=Us;Se.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var In=class extends Us{constructor(e){if(super(),!Se.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}}};Se.Name=In;var Bt=class extends Us{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 In&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Se._Code=Bt;Se.nil=new Bt("");function lv(t,...e){let r=[t[0]],n=0;for(;n<e.length;)vf(r,e[n]),r.push(t[++n]);return new Bt(r)}Se._=lv;var _f=new Bt("+");function uv(t,...e){let r=[Zs(t[0])],n=0;for(;n<e.length;)r.push(_f),vf(r,e[n]),r.push(_f,Zs(t[++n]));return sO(r),new Bt(r)}Se.str=uv;function vf(t,e){e instanceof Bt?t.push(...e._items):e instanceof In?t.push(e):t.push(cO(e))}Se.addCodeArg=vf;function sO(t){let e=1;for(;e<t.length-1;){if(t[e]===_f){let r=iO(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function iO(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof In||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 In))return`"${t}${e.slice(1)}`}function aO(t,e){return e.emptyStr()?t:t.emptyStr()?e:uv`${t}${e}`}Se.strConcat=aO;function cO(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Zs(Array.isArray(t)?t.join(","):t)}function lO(t){return new Bt(Zs(t))}Se.stringify=lO;function Zs(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Se.safeStringify=Zs;function uO(t){return typeof t=="string"&&Se.IDENTIFIER.test(t)?new Bt(`.${t}`):lv`[${t}]`}Se.getProperty=uO;function dO(t){if(typeof t=="string"&&Se.IDENTIFIER.test(t))return new Bt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Se.getEsmExportName=dO;function pO(t){return new Bt(t.toString())}Se.regexpCode=pO});var $f=Z(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.ValueScope=St.ValueScopeName=St.Scope=St.varKinds=St.UsedValueState=void 0;var $t=qs(),xf=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Xa;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Xa||(St.UsedValueState=Xa={}));St.varKinds={const:new $t.Name("const"),let:new $t.Name("let"),var:new $t.Name("var")};var Qa=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof $t.Name?e:this.name(e)}name(e){return new $t.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}}};St.Scope=Qa;var ec=class extends $t.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,$t._)`.${new $t.Name(r)}[${n}]`}};St.ValueScopeName=ec;var fO=(0,$t._)`\n`,kf=class extends Qa{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?fO:$t.nil}}get(){return this._scope}name(e){return new ec(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,$t._)`${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=$t.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,Xa.Started);let u=r(l);if(u){let d=this.opts.es5?St.varKinds.var:St.varKinds.const;s=(0,$t._)`${s}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))s=(0,$t._)`${s}${u}${this.opts._n}`;else throw new xf(l);c.set(l,Xa.Completed)})}return s}};St.ValueScope=kf});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 ve=qs(),er=$f(),Jr=qs();Object.defineProperty(fe,"_",{enumerable:!0,get:function(){return Jr._}});Object.defineProperty(fe,"str",{enumerable:!0,get:function(){return Jr.str}});Object.defineProperty(fe,"strConcat",{enumerable:!0,get:function(){return Jr.strConcat}});Object.defineProperty(fe,"nil",{enumerable:!0,get:function(){return Jr.nil}});Object.defineProperty(fe,"getProperty",{enumerable:!0,get:function(){return Jr.getProperty}});Object.defineProperty(fe,"stringify",{enumerable:!0,get:function(){return Jr.stringify}});Object.defineProperty(fe,"regexpCode",{enumerable:!0,get:function(){return Jr.regexpCode}});Object.defineProperty(fe,"Name",{enumerable:!0,get:function(){return Jr.Name}});var oc=$f();Object.defineProperty(fe,"Scope",{enumerable:!0,get:function(){return oc.Scope}});Object.defineProperty(fe,"ValueScope",{enumerable:!0,get:function(){return oc.ValueScope}});Object.defineProperty(fe,"ValueScopeName",{enumerable:!0,get:function(){return oc.ValueScopeName}});Object.defineProperty(fe,"varKinds",{enumerable:!0,get:function(){return oc.varKinds}});fe.operators={GT:new ve._Code(">"),GTE:new ve._Code(">="),LT:new ve._Code("<"),LTE:new ve._Code("<="),EQ:new ve._Code("==="),NEQ:new ve._Code("!=="),NOT:new ve._Code("!"),OR:new ve._Code("||"),AND:new ve._Code("&&"),ADD:new ve._Code("+")};var Tr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Sf=class extends Tr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?er.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=ko(this.rhs,e,r)),this}get names(){return this.rhs instanceof ve._CodeOrName?this.rhs.names:{}}},tc=class extends Tr{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 ve.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=ko(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ve.Name?{}:{...this.lhs.names};return nc(e,this.rhs)}},Tf=class extends tc{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Ef=class extends Tr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Rf=class extends Tr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Pf=class extends Tr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Af=class extends Tr{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=ko(this.code,e,r),this}get names(){return this.code instanceof ve._CodeOrName?this.code.names:{}}},Fs=class extends Tr{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)||(hO(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>zn(e,r.names),{})}},Er=class extends Fs{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},If=class extends Fs{},xo=class extends Er{};xo.kind="else";var On=class t extends Er{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 xo(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(dv(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=ko(this.condition,e,r),this}get names(){let e=super.names;return nc(e,this.condition),this.else&&zn(e,this.else.names),e}};On.kind="if";var Cn=class extends Er{};Cn.kind="for";var Of=class extends Cn{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=ko(this.iteration,e,r),this}get names(){return zn(super.names,this.iteration.names)}},Cf=class extends Cn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?er.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=nc(super.names,this.from);return nc(e,this.to)}},rc=class extends Cn{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=ko(this.iterable,e,r),this}get names(){return zn(super.names,this.iterable.names)}},Bs=class extends Er{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)}};Bs.kind="func";var Vs=class extends Fs{render(e){return"return "+super.render(e)}};Vs.kind="return";var zf=class extends Er{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&&zn(e,this.catch.names),this.finally&&zn(e,this.finally.names),e}},Hs=class extends Er{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Hs.kind="catch";var Ks=class extends Er{render(e){return"finally"+super.render(e)}};Ks.kind="finally";var Nf=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
1133
- `:""},this._extScope=e,this._scope=new er.Scope({parent:e}),this._nodes=[new If]}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 Sf(e,s,n)),s}const(e,r,n){return this._def(er.varKinds.const,e,r,n)}let(e,r,n){return this._def(er.varKinds.let,e,r,n)}var(e,r,n){return this._def(er.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new tc(e,r,n))}add(e,r){return this._leafNode(new Tf(e,fe.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ve.nil&&this._leafNode(new Af(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,ve.addCodeArg)(r,o));return r.push("}"),new ve._Code(r)}if(e,r,n){if(this._blockNode(new On(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 On(e))}else(){return this._elseNode(new xo)}endIf(){return this._endBlockNode(On,xo)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Of(e),r)}forRange(e,r,n,o,s=this.opts.es5?er.varKinds.var:er.varKinds.let){let i=this._scope.toName(e);return this._for(new Cf(s,i,r,n),()=>o(i))}forOf(e,r,n,o=er.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof ve.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ve._)`${i}.length`,a=>{this.var(s,(0,ve._)`${i}[${a}]`),n(s)})}return this._for(new rc("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?er.varKinds.var:er.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ve._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new rc("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Cn)}label(e){return this._leafNode(new Ef(e))}break(e){return this._leafNode(new Rf(e))}return(e){let r=new Vs;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Vs)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new zf;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Hs(s),r(s)}return n&&(this._currNode=o.finally=new Ks,this.code(n)),this._endBlockNode(Hs,Ks)}throw(e){return this._leafNode(new Pf(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=ve.nil,n,o){return this._blockNode(new Bs(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Bs)}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 On))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=Nf;function zn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function nc(t,e){return e instanceof ve._CodeOrName?zn(t,e.names):t}function ko(t,e,r){if(t instanceof ve.Name)return n(t);if(!o(t))return t;return new ve._Code(t._items.reduce((s,i)=>(i instanceof ve.Name&&(i=n(i)),i instanceof ve._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 ve._Code&&s._items.some(i=>i instanceof ve.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function hO(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function dv(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ve._)`!${jf(t)}`}fe.not=dv;var mO=pv(fe.operators.AND);function gO(...t){return t.reduce(mO)}fe.and=gO;var yO=pv(fe.operators.OR);function bO(...t){return t.reduce(yO)}fe.or=bO;function pv(t){return(e,r)=>e===ve.nil?r:r===ve.nil?e:(0,ve._)`${jf(e)} ${t} ${jf(r)}`}function jf(t){return t instanceof ve.Name?t:(0,ve._)`(${t})`}});var xe=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 Oe=pe(),wO=qs();function _O(t){let e={};for(let r of t)e[r]=!0;return e}he.toHash=_O;function vO(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(mv(t,e),!gv(e,t.self.RULES.all))}he.alwaysValidSchema=vO;function mv(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]||wv(t,`unknown keyword: "${s}"`)}he.checkUnknownRules=mv;function gv(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}he.schemaHasRules=gv;function xO(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=xO;function kO({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Oe._)`${r}`}return(0,Oe._)`${t}${e}${(0,Oe.getProperty)(n)}`}he.schemaRefOrVal=kO;function $O(t){return yv(decodeURIComponent(t))}he.unescapeFragment=$O;function SO(t){return encodeURIComponent(Df(t))}he.escapeFragment=SO;function Df(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}he.escapeJsonPointer=Df;function yv(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}he.unescapeJsonPointer=yv;function TO(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}he.eachItem=TO;function fv({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof Oe.Name?(s instanceof Oe.Name?t(o,s,i):e(o,s,i),i):s instanceof Oe.Name?(e(o,i,s),s):r(s,i);return a===Oe.Name&&!(c instanceof Oe.Name)?n(o,c):c}}he.mergeEvaluated={props:fv({mergeNames:(t,e,r)=>t.if((0,Oe._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Oe._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Oe._)`${r} || {}`).code((0,Oe._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Oe._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Oe._)`${r} || {}`),Mf(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:bv}),items:fv({mergeNames:(t,e,r)=>t.if((0,Oe._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Oe._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Oe._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Oe._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function bv(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Oe._)`{}`);return e!==void 0&&Mf(t,r,e),r}he.evaluatedPropsToName=bv;function Mf(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Oe._)`${e}${(0,Oe.getProperty)(n)}`,!0))}he.setEvaluated=Mf;var hv={};function EO(t,e){return t.scopeValue("func",{ref:e,code:hv[e.code]||(hv[e.code]=new wO._Code(e.code))})}he.useFunc=EO;var Lf;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Lf||(he.Type=Lf={}));function RO(t,e,r){if(t instanceof Oe.Name){let n=e===Lf.Num;return r?n?(0,Oe._)`"[" + ${t} + "]"`:(0,Oe._)`"['" + ${t} + "']"`:n?(0,Oe._)`"/" + ${t}`:(0,Oe._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Oe.getProperty)(t).toString():"/"+Df(t)}he.getErrorPath=RO;function wv(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=wv});var Rr=Z(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});var ut=pe(),PO={data:new ut.Name("data"),valCxt:new ut.Name("valCxt"),instancePath:new ut.Name("instancePath"),parentData:new ut.Name("parentData"),parentDataProperty:new ut.Name("parentDataProperty"),rootData:new ut.Name("rootData"),dynamicAnchors:new ut.Name("dynamicAnchors"),vErrors:new ut.Name("vErrors"),errors:new ut.Name("errors"),this:new ut.Name("this"),self:new ut.Name("self"),scope:new ut.Name("scope"),json:new ut.Name("json"),jsonPos:new ut.Name("jsonPos"),jsonLen:new ut.Name("jsonLen"),jsonPart:new ut.Name("jsonPart")};Uf.default=PO});var Gs=Z(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.extendErrors=dt.resetErrorsCount=dt.reportExtraError=dt.reportError=dt.keyword$DataError=dt.keywordError=void 0;var ke=pe(),sc=xe(),yt=Rr();dt.keywordError={message:({keyword:t})=>(0,ke.str)`must pass "${t}" keyword validation`};dt.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ke.str)`"${t}" keyword must be ${e} ($data)`:(0,ke.str)`"${t}" keyword is invalid ($data)`};function AO(t,e=dt.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=xv(t,e,r);n??(i||a)?_v(s,c):vv(o,(0,ke._)`[${c}]`)}dt.reportError=AO;function IO(t,e=dt.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=xv(t,e,r);_v(o,a),s||i||vv(n,yt.default.vErrors)}dt.reportExtraError=IO;function OO(t,e){t.assign(yt.default.errors,e),t.if((0,ke._)`${yt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ke._)`${yt.default.vErrors}.length`,e),()=>t.assign(yt.default.vErrors,null)))}dt.resetErrorsCount=OO;function CO({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,yt.default.errors,a=>{t.const(i,(0,ke._)`${yt.default.vErrors}[${a}]`),t.if((0,ke._)`${i}.instancePath === undefined`,()=>t.assign((0,ke._)`${i}.instancePath`,(0,ke.strConcat)(yt.default.instancePath,s.errorPath))),t.assign((0,ke._)`${i}.schemaPath`,(0,ke.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,ke._)`${i}.schema`,r),t.assign((0,ke._)`${i}.data`,n))})}dt.extendErrors=CO;function _v(t,e){let r=t.const("err",e);t.if((0,ke._)`${yt.default.vErrors} === null`,()=>t.assign(yt.default.vErrors,(0,ke._)`[${r}]`),(0,ke._)`${yt.default.vErrors}.push(${r})`),t.code((0,ke._)`${yt.default.errors}++`)}function vv(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,ke._)`new ${t.ValidationError}(${e})`):(r.assign((0,ke._)`${n}.errors`,e),r.return(!1))}var Nn={keyword:new ke.Name("keyword"),schemaPath:new ke.Name("schemaPath"),params:new ke.Name("params"),propertyName:new ke.Name("propertyName"),message:new ke.Name("message"),schema:new ke.Name("schema"),parentSchema:new ke.Name("parentSchema")};function xv(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,ke._)`{}`:zO(t,e,r)}function zO(t,e,r={}){let{gen:n,it:o}=t,s=[NO(o,r),jO(t,r)];return LO(t,e,s),n.object(...s)}function NO({errorPath:t},{instancePath:e}){let r=e?(0,ke.str)`${t}${(0,sc.getErrorPath)(e,sc.Type.Str)}`:t;return[yt.default.instancePath,(0,ke.strConcat)(yt.default.instancePath,r)]}function jO({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,ke.str)`${e}/${t}`;return r&&(o=(0,ke.str)`${o}${(0,sc.getErrorPath)(r,sc.Type.Str)}`),[Nn.schemaPath,o]}function LO(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([Nn.keyword,o],[Nn.params,typeof e=="function"?e(t):e||(0,ke._)`{}`]),c.messages&&n.push([Nn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Nn.schema,i],[Nn.parentSchema,(0,ke._)`${u}${d}`],[yt.default.data,s]),l&&n.push([Nn.propertyName,l])}});var $v=Z($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});$o.boolOrEmptySchema=$o.topBoolOrEmptySchema=void 0;var DO=Gs(),MO=pe(),UO=Rr(),ZO={message:"boolean schema is false"};function qO(t){let{gen:e,schema:r,validateName:n}=t;r===!1?kv(t,!1):typeof r=="object"&&r.$async===!0?e.return(UO.default.data):(e.assign((0,MO._)`${n}.errors`,null),e.return(!0))}$o.topBoolOrEmptySchema=qO;function FO(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),kv(t)):r.var(e,!0)}$o.boolOrEmptySchema=FO;function kv(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,DO.reportError)(o,ZO,void 0,e)}});var Zf=Z(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.getRules=So.isJSONType=void 0;var BO=["string","number","integer","boolean","null","object","array"],VO=new Set(BO);function HO(t){return typeof t=="string"&&VO.has(t)}So.isJSONType=HO;function KO(){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:{}}}So.getRules=KO});var qf=Z(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.shouldUseRule=Yr.shouldUseGroup=Yr.schemaHasRulesForType=void 0;function GO({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Sv(t,n)}Yr.schemaHasRulesForType=GO;function Sv(t,e){return e.rules.some(r=>Tv(t,r))}Yr.shouldUseGroup=Sv;function Tv(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))}Yr.shouldUseRule=Tv});var Ws=Z(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.reportTypeError=pt.checkDataTypes=pt.checkDataType=pt.coerceAndCheckDataType=pt.getJSONTypes=pt.getSchemaTypes=pt.DataType=void 0;var WO=Zf(),JO=qf(),YO=Gs(),le=pe(),Ev=xe(),To;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(To||(pt.DataType=To={}));function XO(t){let e=Rv(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}pt.getSchemaTypes=XO;function Rv(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(WO.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}pt.getJSONTypes=Rv;function QO(t,e){let{gen:r,data:n,opts:o}=t,s=eC(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,JO.schemaHasRulesForType)(t,e[0]));if(i){let a=Bf(e,n,o.strictNumbers,To.Wrong);r.if(a,()=>{s.length?tC(t,e,s):Vf(t)})}return i}pt.coerceAndCheckDataType=QO;var Pv=new Set(["string","number","integer","boolean","null"]);function eC(t,e){return e?t.filter(r=>Pv.has(r)||e==="array"&&r==="array"):[]}function tC(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,le._)`typeof ${o}`),a=n.let("coerced",(0,le._)`undefined`);s.coerceTypes==="array"&&n.if((0,le._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,le._)`${o}[0]`).assign(i,(0,le._)`typeof ${o}`).if(Bf(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,le._)`${a} !== undefined`);for(let l of r)(Pv.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),Vf(t),n.endIf(),n.if((0,le._)`${a} !== undefined`,()=>{n.assign(o,a),rC(t,a)});function c(l){switch(l){case"string":n.elseIf((0,le._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,le._)`"" + ${o}`).elseIf((0,le._)`${o} === null`).assign(a,(0,le._)`""`);return;case"number":n.elseIf((0,le._)`${i} == "boolean" || ${o} === null
1277
+ ]`;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 nf,er,SO,Xa=O(()=>{Yr();er={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:()=>(nf===void 0&&(nf=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),nf),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-_]*$/};SO=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function Qa(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]:ne(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Fe(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:ne(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}=Ya(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}=Wa(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var ec=O(()=>{hs();Je();Xa();Ja();Bt()});function ov(t,e){if(e.mapStrategy==="record")return Qa(t,e);let r=ne(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Fe(e),n=ne(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Fe(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var sf=O(()=>{Je();ec();Bt()});function sv(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 af=O(()=>{});function iv(t){return t.target==="openAi"?void 0:{not:Fe({...t,currentPath:[...t.currentPath,"not"]})}}var cf=O(()=>{Bt()});function av(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var lf=O(()=>{});function lv(t,e){if(e.target==="openApi3")return cv(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Us&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Us[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 cv(t,e)}var Us,cv,tc=O(()=>{Je();Us={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};cv=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>ne(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 uv(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:Us[t.innerType._def.typeName],nullable:!0}:{type:[Us[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=ne(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=ne(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var uf=O(()=>{Je();tc()});function dv(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",Vp(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?_e(r,"minimum",n.value,n.message,e):_e(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),_e(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?_e(r,"maximum",n.value,n.message,e):_e(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),_e(r,"maximum",n.value,n.message,e));break;case"multipleOf":_e(r,"multipleOf",n.value,n.message,e);break}return r}var df=O(()=>{Yr()});function pv(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=RO(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=ne(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=EO(t,e);return i!==void 0&&(n.additionalProperties=i),n}function EO(t,e){if(t.catchall._def.typeName!=="ZodNever")return ne(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 RO(t){try{return t.isOptional()}catch{return!0}}var pf=O(()=>{Je()});var fv,ff=O(()=>{Je();Bt();fv=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return ne(t.innerType._def,e);let r=ne(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Fe(e)},r]}:Fe(e)}});var hv,hf=O(()=>{Je();hv=(t,e)=>{if(e.pipeStrategy==="input")return ne(t.in._def,e);if(e.pipeStrategy==="output")return ne(t.out._def,e);let r=ne(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=ne(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function mv(t,e){return ne(t.type._def,e)}var mf=O(()=>{Je()});function gv(t,e){let n={type:"array",uniqueItems:!0,items:ne(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&_e(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&_e(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var gf=O(()=>{Yr();Je()});function yv(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>ne(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:ne(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>ne(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var yf=O(()=>{Je()});function bv(t){return{not:Fe(t)}}var bf=O(()=>{Bt()});function wv(t){return Fe(t)}var wf=O(()=>{Bt()});var _v,_f=O(()=>{Je();_v=(t,e)=>ne(t.innerType._def,e)});var vv,vf=O(()=>{hs();Bt();Hp();Kp();Gp();Ja();Wp();Yp();Xp();Qp();ef();tf();rf();sf();af();cf();lf();uf();df();pf();ff();hf();mf();ec();gf();Xa();yf();bf();tc();wf();_f();vv=(t,e,r)=>{switch(e){case D.ZodString:return Ya(t,r);case D.ZodNumber:return dv(t,r);case D.ZodObject:return pv(t,r);case D.ZodBigInt:return W_(t,r);case D.ZodBoolean:return J_();case D.ZodDate:return Jp(t,r);case D.ZodUndefined:return bv(r);case D.ZodNull:return av(r);case D.ZodArray:return G_(t,r);case D.ZodUnion:case D.ZodDiscriminatedUnion:return lv(t,r);case D.ZodIntersection:return tv(t,r);case D.ZodTuple:return yv(t,r);case D.ZodRecord:return Qa(t,r);case D.ZodLiteral:return rv(t,r);case D.ZodEnum:return ev(t);case D.ZodNativeEnum:return sv(t);case D.ZodNullable:return uv(t,r);case D.ZodOptional:return fv(t,r);case D.ZodMap:return ov(t,r);case D.ZodSet:return gv(t,r);case D.ZodLazy:return()=>t.getter()._def;case D.ZodPromise:return mv(t,r);case D.ZodNaN:case D.ZodNever:return iv(r);case D.ZodEffects:return Q_(t,r);case D.ZodAny:return Fe(r);case D.ZodUnknown:return wv(r);case D.ZodDefault:return X_(t,r);case D.ZodBranded:return Wa(t,r);case D.ZodReadonly:return _v(t,r);case D.ZodCatch:return Y_(t,r);case D.ZodPipeline:return hv(t,r);case D.ZodFunction:case D.ZodVoid:case D.ZodSymbol:return;default:return(n=>{})(e)}}});function ne(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==V_)return a}if(n&&!r){let a=PO(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=vv(t,t.typeName,e),i=typeof s=="function"?ne(s(),e):s;if(i&&AO(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var PO,AO,Je=O(()=>{Ha();vf();Ga();Bt();PO=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Ka(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`),Fe(e)):e.$refStrategy==="seen"?Fe(e):void 0}},AO=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var xv=O(()=>{});var xf,kf=O(()=>{Je();Bp();Bt();xf=(t,e)=>{let r=K_(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:ne(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??Fe(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=ne(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Fe(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 kv=O(()=>{Ha();Bp();Yr();Ga();Je();xv();Bt();Hp();Kp();Gp();Ja();Wp();Yp();Xp();Qp();ef();tf();rf();sf();af();cf();lf();uf();df();pf();ff();hf();mf();_f();ec();gf();Xa();yf();bf();tc();wf();vf();kf();kf()});function IO(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function $f(t,e){return pr(t)?up(t,{target:IO(e?.target),io:e?.pipeStrategy??"input"}):xf(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Sf(t){let r=Gr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=go(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Tf(t,e){let r=Kr(t,e);if(!r.success)throw r.error;return r.data}var Ef=O(()=>{fp();Es();kv()});function $v(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Sv(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];$v(i)&&$v(s)?r[o]={...i,...s}:r[o]=s}return r}var OO,rc,Tv=O(()=>{Es();xo();F_();Ef();OO=6e4,rc=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(Pa,r=>{this._oncancel(r)}),this.setNotificationHandler(Ia,r=>{this._onprogress(r)}),this.setRequestHandler(Aa,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Oa,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new G(Q.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(za,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,w=new G(d.error.code,d.error.message,d.error.data);u(w)}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(Q.InvalidParams,`Task not found: ${s}`);if(!Jr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Jr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Wr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Na,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(Q.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(La,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new G(Q.InvalidParams,`Task not found: ${r.params.taskId}`);if(Jr(o.status))throw new G(Q.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(Q.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof G?o:new G(Q.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(Q.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),Is(s)||O_(s)?this._onresponse(s):Ap(s)?this._onrequest(s,i):I_(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(Q.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?.[Wr]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:Q.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=R_(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,w)=>{if(i.signal.aborted)throw new G(Q.ConnectionClosed,"Request was cancelled");let m={...w,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:Q.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),Is(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(Is(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),Is(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(Q.InternalError,String(i))}}return}let s;try{let i=await this.request(e,bo,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new G(Q.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Jr(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(Q.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new G(Q.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(Q.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=P=>{u(P)};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(P){d(P);return}n?.signal?.throwIfAborted();let w=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:w};n?.onprogress&&(this._progressHandlers.set(w,n.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:w}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Wr]:c}});let f=P=>{this._responseHandlers.delete(w),this._progressHandlers.delete(w),this._cleanupTimeout(w),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:w,reason:String(P)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(H=>this._onerror(new Error(`Failed to send cancellation: ${H}`)));let z=P instanceof G?P:new G(Q.RequestTimeout,String(P));u(z)};this._responseHandlers.set(w,P=>{if(!n?.signal?.aborted){if(P instanceof Error)return u(P);try{let z=Kr(r,P.result);z.success?l(z.data):u(z.error)}catch(z){u(z)}}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});let b=n?.timeout??OO,k=()=>f(G.fromError(Q.RequestTimeout,"Request timed out",{timeout:b}));this._setupTimeout(w,b,n?.maxTotalTimeout,k,n?.resetTimeoutOnProgress??!1);let E=c?.taskId;if(E){let P=z=>{let H=this._responseHandlers.get(w);H?H(z):this._onerror(new Error(`Response handler missing for side-channeled request ${w}`))};this._requestResolvers.set(w,P),this._enqueueTaskMessage(E,{type:"request",message:m,timestamp:Date.now()}).catch(z=>{this._cleanupTimeout(w),u(z)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(P=>{this._cleanupTimeout(w),u(P)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Ca,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},ja,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},N_,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||{},[Wr]: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||{},[Wr]: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||{},[Wr]: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=Tf(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=Tf(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"&&Ap(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new G(Q.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(Q.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new G(Q.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(Q.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=js.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Jr(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(Q.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Jr(a.status))throw new G(Q.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=js.parse({method:"notifications/tasks/status",params:c});await this.notification(l),Jr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var Fs=Z(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.regexpCode=Se.getEsmExportName=Se.getProperty=Se.safeStringify=Se.stringify=Se.strConcat=Se.addCodeArg=Se.str=Se._=Se.nil=Se._Code=Se.Name=Se.IDENTIFIER=Se._CodeOrName=void 0;var Zs=class{};Se._CodeOrName=Zs;Se.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Cn=class extends Zs{constructor(e){if(super(),!Se.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}}};Se.Name=Cn;var Vt=class extends Zs{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 Cn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Se._Code=Vt;Se.nil=new Vt("");function Ev(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Pf(r,e[n]),r.push(t[++n]);return new Vt(r)}Se._=Ev;var Rf=new Vt("+");function Rv(t,...e){let r=[qs(t[0])],n=0;for(;n<e.length;)r.push(Rf),Pf(r,e[n]),r.push(Rf,qs(t[++n]));return CO(r),new Vt(r)}Se.str=Rv;function Pf(t,e){e instanceof Vt?t.push(...e._items):e instanceof Cn?t.push(e):t.push(jO(e))}Se.addCodeArg=Pf;function CO(t){let e=1;for(;e<t.length-1;){if(t[e]===Rf){let r=zO(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function zO(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Cn||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 Cn))return`"${t}${e.slice(1)}`}function NO(t,e){return e.emptyStr()?t:t.emptyStr()?e:Rv`${t}${e}`}Se.strConcat=NO;function jO(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:qs(Array.isArray(t)?t.join(","):t)}function LO(t){return new Vt(qs(t))}Se.stringify=LO;function qs(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Se.safeStringify=qs;function DO(t){return typeof t=="string"&&Se.IDENTIFIER.test(t)?new Vt(`.${t}`):Ev`[${t}]`}Se.getProperty=DO;function MO(t){if(typeof t=="string"&&Se.IDENTIFIER.test(t))return new Vt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Se.getEsmExportName=MO;function UO(t){return new Vt(t.toString())}Se.regexpCode=UO});var Of=Z(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.ValueScope=Et.ValueScopeName=Et.Scope=Et.varKinds=Et.UsedValueState=void 0;var Tt=Fs(),Af=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},nc;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(nc||(Et.UsedValueState=nc={}));Et.varKinds={const:new Tt.Name("const"),let:new Tt.Name("let"),var:new Tt.Name("var")};var oc=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Tt.Name?e:this.name(e)}name(e){return new Tt.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}}};Et.Scope=oc;var sc=class extends Tt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Tt._)`.${new Tt.Name(r)}[${n}]`}};Et.ValueScopeName=sc;var ZO=(0,Tt._)`\n`,If=class extends oc{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?ZO:Tt.nil}}get(){return this._scope}name(e){return new sc(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,Tt._)`${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=Tt.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,nc.Started);let u=r(l);if(u){let d=this.opts.es5?Et.varKinds.var:Et.varKinds.const;s=(0,Tt._)`${s}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))s=(0,Tt._)`${s}${u}${this.opts._n}`;else throw new Af(l);c.set(l,nc.Completed)})}return s}};Et.ValueScope=If});var fe=Z(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.or=he.and=he.not=he.CodeGen=he.operators=he.varKinds=he.ValueScopeName=he.ValueScope=he.Scope=he.Name=he.regexpCode=he.stringify=he.getProperty=he.nil=he.strConcat=he.str=he._=void 0;var ve=Fs(),rr=Of(),Xr=Fs();Object.defineProperty(he,"_",{enumerable:!0,get:function(){return Xr._}});Object.defineProperty(he,"str",{enumerable:!0,get:function(){return Xr.str}});Object.defineProperty(he,"strConcat",{enumerable:!0,get:function(){return Xr.strConcat}});Object.defineProperty(he,"nil",{enumerable:!0,get:function(){return Xr.nil}});Object.defineProperty(he,"getProperty",{enumerable:!0,get:function(){return Xr.getProperty}});Object.defineProperty(he,"stringify",{enumerable:!0,get:function(){return Xr.stringify}});Object.defineProperty(he,"regexpCode",{enumerable:!0,get:function(){return Xr.regexpCode}});Object.defineProperty(he,"Name",{enumerable:!0,get:function(){return Xr.Name}});var lc=Of();Object.defineProperty(he,"Scope",{enumerable:!0,get:function(){return lc.Scope}});Object.defineProperty(he,"ValueScope",{enumerable:!0,get:function(){return lc.ValueScope}});Object.defineProperty(he,"ValueScopeName",{enumerable:!0,get:function(){return lc.ValueScopeName}});Object.defineProperty(he,"varKinds",{enumerable:!0,get:function(){return lc.varKinds}});he.operators={GT:new ve._Code(">"),GTE:new ve._Code(">="),LT:new ve._Code("<"),LTE:new ve._Code("<="),EQ:new ve._Code("==="),NEQ:new ve._Code("!=="),NOT:new ve._Code("!"),OR:new ve._Code("||"),AND:new ve._Code("&&"),ADD:new ve._Code("+")};var Rr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Cf=class extends Rr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?rr.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=$o(this.rhs,e,r)),this}get names(){return this.rhs instanceof ve._CodeOrName?this.rhs.names:{}}},ic=class extends Rr{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 ve.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=$o(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ve.Name?{}:{...this.lhs.names};return cc(e,this.rhs)}},zf=class extends ic{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Nf=class extends Rr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},jf=class extends Rr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Lf=class extends Rr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Df=class extends Rr{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=$o(this.code,e,r),this}get names(){return this.code instanceof ve._CodeOrName?this.code.names:{}}},Bs=class extends Rr{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)||(qO(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>jn(e,r.names),{})}},Pr=class extends Bs{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Mf=class extends Bs{},ko=class extends Pr{};ko.kind="else";var zn=class t extends Pr{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 ko(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Pv(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=$o(this.condition,e,r),this}get names(){let e=super.names;return cc(e,this.condition),this.else&&jn(e,this.else.names),e}};zn.kind="if";var Nn=class extends Pr{};Nn.kind="for";var Uf=class extends Nn{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=$o(this.iteration,e,r),this}get names(){return jn(super.names,this.iteration.names)}},Zf=class extends Nn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?rr.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=cc(super.names,this.from);return cc(e,this.to)}},ac=class extends Nn{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=$o(this.iterable,e,r),this}get names(){return jn(super.names,this.iterable.names)}},Vs=class extends Pr{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)}};Vs.kind="func";var Hs=class extends Bs{render(e){return"return "+super.render(e)}};Hs.kind="return";var qf=class extends Pr{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&&jn(e,this.catch.names),this.finally&&jn(e,this.finally.names),e}},Ks=class extends Pr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Ks.kind="catch";var Gs=class extends Pr{render(e){return"finally"+super.render(e)}};Gs.kind="finally";var Ff=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
1278
+ `:""},this._extScope=e,this._scope=new rr.Scope({parent:e}),this._nodes=[new Mf]}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 Cf(e,s,n)),s}const(e,r,n){return this._def(rr.varKinds.const,e,r,n)}let(e,r,n){return this._def(rr.varKinds.let,e,r,n)}var(e,r,n){return this._def(rr.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new ic(e,r,n))}add(e,r){return this._leafNode(new zf(e,he.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ve.nil&&this._leafNode(new Df(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,ve.addCodeArg)(r,o));return r.push("}"),new ve._Code(r)}if(e,r,n){if(this._blockNode(new zn(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 zn(e))}else(){return this._elseNode(new ko)}endIf(){return this._endBlockNode(zn,ko)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Uf(e),r)}forRange(e,r,n,o,s=this.opts.es5?rr.varKinds.var:rr.varKinds.let){let i=this._scope.toName(e);return this._for(new Zf(s,i,r,n),()=>o(i))}forOf(e,r,n,o=rr.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof ve.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ve._)`${i}.length`,a=>{this.var(s,(0,ve._)`${i}[${a}]`),n(s)})}return this._for(new ac("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?rr.varKinds.var:rr.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ve._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new ac("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Nn)}label(e){return this._leafNode(new Nf(e))}break(e){return this._leafNode(new jf(e))}return(e){let r=new Hs;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Hs)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new qf;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Ks(s),r(s)}return n&&(this._currNode=o.finally=new Gs,this.code(n)),this._endBlockNode(Ks,Gs)}throw(e){return this._leafNode(new Lf(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=ve.nil,n,o){return this._blockNode(new Vs(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Vs)}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 zn))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}};he.CodeGen=Ff;function jn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function cc(t,e){return e instanceof ve._CodeOrName?jn(t,e.names):t}function $o(t,e,r){if(t instanceof ve.Name)return n(t);if(!o(t))return t;return new ve._Code(t._items.reduce((s,i)=>(i instanceof ve.Name&&(i=n(i)),i instanceof ve._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 ve._Code&&s._items.some(i=>i instanceof ve.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function qO(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Pv(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ve._)`!${Bf(t)}`}he.not=Pv;var FO=Av(he.operators.AND);function BO(...t){return t.reduce(FO)}he.and=BO;var VO=Av(he.operators.OR);function HO(...t){return t.reduce(VO)}he.or=HO;function Av(t){return(e,r)=>e===ve.nil?r:r===ve.nil?e:(0,ve._)`${Bf(e)} ${t} ${Bf(r)}`}function Bf(t){return t instanceof ve.Name?t:(0,ve._)`(${t})`}});var xe=Z(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.checkStrictMode=me.getErrorPath=me.Type=me.useFunc=me.setEvaluated=me.evaluatedPropsToName=me.mergeEvaluated=me.eachItem=me.unescapeJsonPointer=me.escapeJsonPointer=me.escapeFragment=me.unescapeFragment=me.schemaRefOrVal=me.schemaHasRulesButRef=me.schemaHasRules=me.checkUnknownRules=me.alwaysValidSchema=me.toHash=void 0;var Oe=fe(),KO=Fs();function GO(t){let e={};for(let r of t)e[r]=!0;return e}me.toHash=GO;function WO(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Cv(t,e),!zv(e,t.self.RULES.all))}me.alwaysValidSchema=WO;function Cv(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]||Lv(t,`unknown keyword: "${s}"`)}me.checkUnknownRules=Cv;function zv(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}me.schemaHasRules=zv;function JO(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}me.schemaHasRulesButRef=JO;function YO({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Oe._)`${r}`}return(0,Oe._)`${t}${e}${(0,Oe.getProperty)(n)}`}me.schemaRefOrVal=YO;function XO(t){return Nv(decodeURIComponent(t))}me.unescapeFragment=XO;function QO(t){return encodeURIComponent(Hf(t))}me.escapeFragment=QO;function Hf(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}me.escapeJsonPointer=Hf;function Nv(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}me.unescapeJsonPointer=Nv;function eC(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}me.eachItem=eC;function Iv({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof Oe.Name?(s instanceof Oe.Name?t(o,s,i):e(o,s,i),i):s instanceof Oe.Name?(e(o,i,s),s):r(s,i);return a===Oe.Name&&!(c instanceof Oe.Name)?n(o,c):c}}me.mergeEvaluated={props:Iv({mergeNames:(t,e,r)=>t.if((0,Oe._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Oe._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Oe._)`${r} || {}`).code((0,Oe._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Oe._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Oe._)`${r} || {}`),Kf(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:jv}),items:Iv({mergeNames:(t,e,r)=>t.if((0,Oe._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Oe._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Oe._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Oe._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function jv(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Oe._)`{}`);return e!==void 0&&Kf(t,r,e),r}me.evaluatedPropsToName=jv;function Kf(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Oe._)`${e}${(0,Oe.getProperty)(n)}`,!0))}me.setEvaluated=Kf;var Ov={};function tC(t,e){return t.scopeValue("func",{ref:e,code:Ov[e.code]||(Ov[e.code]=new KO._Code(e.code))})}me.useFunc=tC;var Vf;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Vf||(me.Type=Vf={}));function rC(t,e,r){if(t instanceof Oe.Name){let n=e===Vf.Num;return r?n?(0,Oe._)`"[" + ${t} + "]"`:(0,Oe._)`"['" + ${t} + "']"`:n?(0,Oe._)`"/" + ${t}`:(0,Oe._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Oe.getProperty)(t).toString():"/"+Hf(t)}me.getErrorPath=rC;function Lv(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}me.checkStrictMode=Lv});var Ar=Z(Gf=>{"use strict";Object.defineProperty(Gf,"__esModule",{value:!0});var dt=fe(),nC={data:new dt.Name("data"),valCxt:new dt.Name("valCxt"),instancePath:new dt.Name("instancePath"),parentData:new dt.Name("parentData"),parentDataProperty:new dt.Name("parentDataProperty"),rootData:new dt.Name("rootData"),dynamicAnchors:new dt.Name("dynamicAnchors"),vErrors:new dt.Name("vErrors"),errors:new dt.Name("errors"),this:new dt.Name("this"),self:new dt.Name("self"),scope:new dt.Name("scope"),json:new dt.Name("json"),jsonPos:new dt.Name("jsonPos"),jsonLen:new dt.Name("jsonLen"),jsonPart:new dt.Name("jsonPart")};Gf.default=nC});var Ws=Z(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.extendErrors=pt.resetErrorsCount=pt.reportExtraError=pt.reportError=pt.keyword$DataError=pt.keywordError=void 0;var ke=fe(),uc=xe(),wt=Ar();pt.keywordError={message:({keyword:t})=>(0,ke.str)`must pass "${t}" keyword validation`};pt.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ke.str)`"${t}" keyword must be ${e} ($data)`:(0,ke.str)`"${t}" keyword is invalid ($data)`};function oC(t,e=pt.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Uv(t,e,r);n??(i||a)?Dv(s,c):Mv(o,(0,ke._)`[${c}]`)}pt.reportError=oC;function sC(t,e=pt.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Uv(t,e,r);Dv(o,a),s||i||Mv(n,wt.default.vErrors)}pt.reportExtraError=sC;function iC(t,e){t.assign(wt.default.errors,e),t.if((0,ke._)`${wt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ke._)`${wt.default.vErrors}.length`,e),()=>t.assign(wt.default.vErrors,null)))}pt.resetErrorsCount=iC;function aC({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,wt.default.errors,a=>{t.const(i,(0,ke._)`${wt.default.vErrors}[${a}]`),t.if((0,ke._)`${i}.instancePath === undefined`,()=>t.assign((0,ke._)`${i}.instancePath`,(0,ke.strConcat)(wt.default.instancePath,s.errorPath))),t.assign((0,ke._)`${i}.schemaPath`,(0,ke.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,ke._)`${i}.schema`,r),t.assign((0,ke._)`${i}.data`,n))})}pt.extendErrors=aC;function Dv(t,e){let r=t.const("err",e);t.if((0,ke._)`${wt.default.vErrors} === null`,()=>t.assign(wt.default.vErrors,(0,ke._)`[${r}]`),(0,ke._)`${wt.default.vErrors}.push(${r})`),t.code((0,ke._)`${wt.default.errors}++`)}function Mv(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,ke._)`new ${t.ValidationError}(${e})`):(r.assign((0,ke._)`${n}.errors`,e),r.return(!1))}var Ln={keyword:new ke.Name("keyword"),schemaPath:new ke.Name("schemaPath"),params:new ke.Name("params"),propertyName:new ke.Name("propertyName"),message:new ke.Name("message"),schema:new ke.Name("schema"),parentSchema:new ke.Name("parentSchema")};function Uv(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,ke._)`{}`:cC(t,e,r)}function cC(t,e,r={}){let{gen:n,it:o}=t,s=[lC(o,r),uC(t,r)];return dC(t,e,s),n.object(...s)}function lC({errorPath:t},{instancePath:e}){let r=e?(0,ke.str)`${t}${(0,uc.getErrorPath)(e,uc.Type.Str)}`:t;return[wt.default.instancePath,(0,ke.strConcat)(wt.default.instancePath,r)]}function uC({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,ke.str)`${e}/${t}`;return r&&(o=(0,ke.str)`${o}${(0,uc.getErrorPath)(r,uc.Type.Str)}`),[Ln.schemaPath,o]}function dC(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([Ln.keyword,o],[Ln.params,typeof e=="function"?e(t):e||(0,ke._)`{}`]),c.messages&&n.push([Ln.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Ln.schema,i],[Ln.parentSchema,(0,ke._)`${u}${d}`],[wt.default.data,s]),l&&n.push([Ln.propertyName,l])}});var qv=Z(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.boolOrEmptySchema=So.topBoolOrEmptySchema=void 0;var pC=Ws(),fC=fe(),hC=Ar(),mC={message:"boolean schema is false"};function gC(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Zv(t,!1):typeof r=="object"&&r.$async===!0?e.return(hC.default.data):(e.assign((0,fC._)`${n}.errors`,null),e.return(!0))}So.topBoolOrEmptySchema=gC;function yC(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Zv(t)):r.var(e,!0)}So.boolOrEmptySchema=yC;function Zv(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,pC.reportError)(o,mC,void 0,e)}});var Wf=Z(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});To.getRules=To.isJSONType=void 0;var bC=["string","number","integer","boolean","null","object","array"],wC=new Set(bC);function _C(t){return typeof t=="string"&&wC.has(t)}To.isJSONType=_C;function vC(){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:{}}}To.getRules=vC});var Jf=Z(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});Qr.shouldUseRule=Qr.shouldUseGroup=Qr.schemaHasRulesForType=void 0;function xC({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Fv(t,n)}Qr.schemaHasRulesForType=xC;function Fv(t,e){return e.rules.some(r=>Bv(t,r))}Qr.shouldUseGroup=Fv;function Bv(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))}Qr.shouldUseRule=Bv});var Js=Z(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.reportTypeError=ft.checkDataTypes=ft.checkDataType=ft.coerceAndCheckDataType=ft.getJSONTypes=ft.getSchemaTypes=ft.DataType=void 0;var kC=Wf(),$C=Jf(),SC=Ws(),le=fe(),Vv=xe(),Eo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Eo||(ft.DataType=Eo={}));function TC(t){let e=Hv(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}ft.getSchemaTypes=TC;function Hv(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(kC.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ft.getJSONTypes=Hv;function EC(t,e){let{gen:r,data:n,opts:o}=t,s=RC(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,$C.schemaHasRulesForType)(t,e[0]));if(i){let a=Xf(e,n,o.strictNumbers,Eo.Wrong);r.if(a,()=>{s.length?PC(t,e,s):Qf(t)})}return i}ft.coerceAndCheckDataType=EC;var Kv=new Set(["string","number","integer","boolean","null"]);function RC(t,e){return e?t.filter(r=>Kv.has(r)||e==="array"&&r==="array"):[]}function PC(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,le._)`typeof ${o}`),a=n.let("coerced",(0,le._)`undefined`);s.coerceTypes==="array"&&n.if((0,le._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,le._)`${o}[0]`).assign(i,(0,le._)`typeof ${o}`).if(Xf(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,le._)`${a} !== undefined`);for(let l of r)(Kv.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),Qf(t),n.endIf(),n.if((0,le._)`${a} !== undefined`,()=>{n.assign(o,a),AC(t,a)});function c(l){switch(l){case"string":n.elseIf((0,le._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,le._)`"" + ${o}`).elseIf((0,le._)`${o} === null`).assign(a,(0,le._)`""`);return;case"number":n.elseIf((0,le._)`${i} == "boolean" || ${o} === null
1134
1279
  || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,le._)`+${o}`);return;case"integer":n.elseIf((0,le._)`${i} === "boolean" || ${o} === null
1135
1280
  || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,le._)`+${o}`);return;case"boolean":n.elseIf((0,le._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,le._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,le._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,le._)`${i} === "string" || ${i} === "number"
1136
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,le._)`[${o}]`)}}}function rC({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,le._)`${e} !== undefined`,()=>t.assign((0,le._)`${e}[${r}]`,n))}function Ff(t,e,r,n=To.Correct){let o=n===To.Correct?le.operators.EQ:le.operators.NEQ,s;switch(t){case"null":return(0,le._)`${e} ${o} null`;case"array":s=(0,le._)`Array.isArray(${e})`;break;case"object":s=(0,le._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,le._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,le._)`typeof ${e} ${o} ${t}`}return n===To.Correct?s:(0,le.not)(s);function i(a=le.nil){return(0,le.and)((0,le._)`typeof ${e} == "number"`,a,r?(0,le._)`isFinite(${e})`:le.nil)}}pt.checkDataType=Ff;function Bf(t,e,r,n){if(t.length===1)return Ff(t[0],e,r,n);let o,s=(0,Ev.toHash)(t);if(s.array&&s.object){let i=(0,le._)`typeof ${e} != "object"`;o=s.null?i:(0,le._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=le.nil;s.number&&delete s.integer;for(let i in s)o=(0,le.and)(o,Ff(i,e,r,n));return o}pt.checkDataTypes=Bf;var nC={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,le._)`{type: ${t}}`:(0,le._)`{type: ${e}}`};function Vf(t){let e=oC(t);(0,YO.reportError)(e,nC)}pt.reportTypeError=Vf;function oC(t){let{gen:e,data:r,schema:n}=t,o=(0,Ev.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Iv=Z(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});ic.assignDefaults=void 0;var Eo=pe(),sC=xe();function iC(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))}ic.assignDefaults=iC;function Av(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Eo._)`${s}${(0,Eo.getProperty)(e)}`;if(o){(0,sC.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Eo._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Eo._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Eo._)`${a} = ${(0,Eo.stringify)(r)}`)}});var Vt=Z(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.validateUnion=Ie.validateArray=Ie.usePattern=Ie.callValidateCode=Ie.schemaProperties=Ie.allSchemaProperties=Ie.noPropertyInData=Ie.propertyInData=Ie.isOwnProperty=Ie.hasPropFunc=Ie.reportMissingProp=Ie.checkMissingProp=Ie.checkReportMissingProp=void 0;var Le=pe(),Hf=xe(),Xr=Rr(),aC=xe();function cC(t,e){let{gen:r,data:n,it:o}=t;r.if(Gf(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Le._)`${e}`},!0),t.error()})}Ie.checkReportMissingProp=cC;function lC({gen:t,data:e,it:{opts:r}},n,o){return(0,Le.or)(...n.map(s=>(0,Le.and)(Gf(t,e,s,r.ownProperties),(0,Le._)`${o} = ${s}`)))}Ie.checkMissingProp=lC;function uC(t,e){t.setParams({missingProperty:e},!0),t.error()}Ie.reportMissingProp=uC;function Ov(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Le._)`Object.prototype.hasOwnProperty`})}Ie.hasPropFunc=Ov;function Kf(t,e,r){return(0,Le._)`${Ov(t)}.call(${e}, ${r})`}Ie.isOwnProperty=Kf;function dC(t,e,r,n){let o=(0,Le._)`${e}${(0,Le.getProperty)(r)} !== undefined`;return n?(0,Le._)`${o} && ${Kf(t,e,r)}`:o}Ie.propertyInData=dC;function Gf(t,e,r,n){let o=(0,Le._)`${e}${(0,Le.getProperty)(r)} === undefined`;return n?(0,Le.or)(o,(0,Le.not)(Kf(t,e,r))):o}Ie.noPropertyInData=Gf;function Cv(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Ie.allSchemaProperties=Cv;function pC(t,e){return Cv(e).filter(r=>!(0,Hf.alwaysValidSchema)(t,e[r]))}Ie.schemaProperties=pC;function fC({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,l){let u=l?(0,Le._)`${t}, ${e}, ${n}${o}`:e,d=[[Xr.default.instancePath,(0,Le.strConcat)(Xr.default.instancePath,s)],[Xr.default.parentData,i.parentData],[Xr.default.parentDataProperty,i.parentDataProperty],[Xr.default.rootData,Xr.default.rootData]];i.opts.dynamicRef&&d.push([Xr.default.dynamicAnchors,Xr.default.dynamicAnchors]);let b=(0,Le._)`${u}, ${r.object(...d)}`;return c!==Le.nil?(0,Le._)`${a}.call(${c}, ${b})`:(0,Le._)`${a}(${b})`}Ie.callValidateCode=fC;var hC=(0,Le._)`new RegExp`;function mC({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,Le._)`${o.code==="new RegExp"?hC:(0,aC.useFunc)(t,o)}(${r}, ${n})`})}Ie.usePattern=mC;function gC(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,Le._)`${r}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:n,dataProp:l,dataPropType:Hf.Type.Num},s),e.if((0,Le.not)(s),a)})}}Ie.validateArray=gC;function yC(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,Hf.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,Le._)`${i} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,Le.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Ie.validateUnion=yC});var jv=Z(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.validateKeywordUsage=pr.validSchemaType=pr.funcKeywordCode=pr.macroKeywordCode=void 0;var bt=pe(),jn=Rr(),bC=Vt(),wC=Gs();function _C(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Nv(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=r.name("valid");t.subschema({schema:a,schemaPath:bt.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}pr.macroKeywordCode=_C;function vC(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;kC(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,u=Nv(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&&zv(t),v(()=>t.error());else{let E=e.async?m():f();e.modifying&&zv(t),v(()=>xC(t,E))}}function m(){let E=n.let("ruleErrs",null);return n.try(()=>y((0,bt._)`await `),P=>n.assign(d,!1).if((0,bt._)`${P} instanceof ${c.ValidationError}`,()=>n.assign(E,(0,bt._)`${P}.errors`),()=>n.throw(P))),E}function f(){let E=(0,bt._)`${u}.errors`;return n.assign(E,null),y(bt.nil),E}function y(E=e.async?(0,bt._)`await `:bt.nil){let P=c.opts.passContext?jn.default.this:jn.default.self,z=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,bt._)`${E}${(0,bC.callValidateCode)(t,u,P,z)}`,e.modifying)}function v(E){var P;n.if((0,bt.not)((P=e.valid)!==null&&P!==void 0?P:d),E)}}pr.funcKeywordCode=vC;function zv(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,bt._)`${n.parentData}[${n.parentDataProperty}]`))}function xC(t,e){let{gen:r}=t;r.if((0,bt._)`Array.isArray(${e})`,()=>{r.assign(jn.default.vErrors,(0,bt._)`${jn.default.vErrors} === null ? ${e} : ${jn.default.vErrors}.concat(${e})`).assign(jn.default.errors,(0,bt._)`${jn.default.vErrors}.length`),(0,wC.extendErrors)(t)},()=>t.error())}function kC({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Nv(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,bt.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")}pr.validSchemaType=$C;function SC({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)}}pr.validateKeywordUsage=SC});var Dv=Z(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});Qr.extendSubschemaMode=Qr.extendSubschemaData=Qr.getSubschema=void 0;var fr=pe(),Lv=xe();function TC(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,fr._)`${t.schemaPath}${(0,fr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,fr._)`${t.schemaPath}${(0,fr.getProperty)(e)}${(0,fr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Lv.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')}Qr.getSubschema=TC;function EC(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,fr._)`${e.data}${(0,fr.getProperty)(r)}`,!0);c(b),t.errorPath=(0,fr.str)`${l}${(0,Lv.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,fr._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(o!==void 0){let l=o instanceof fr.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]}}Qr.extendSubschemaData=EC;function RC(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}Qr.extendSubschemaMode=RC});var Wf=Z((c2,Mv)=>{"use strict";Mv.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 Zv=Z((l2,Uv)=>{"use strict";var en=Uv.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(){};ac(e,n,o,t,"",t)};en.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};en.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};en.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};en.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 ac(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 en.arrayKeywords)for(var b=0;b<d.length;b++)ac(t,e,r,d[b],o+"/"+u+"/"+b,s,o,u,n,b)}else if(u in en.propsKeywords){if(d&&typeof d=="object")for(var m in d)ac(t,e,r,d[m],o+"/"+u+"/"+PC(m),s,o,u,n,m)}else(u in en.keywords||t.allKeys&&!(u in en.skipKeywords))&&ac(t,e,r,d,o+"/"+u,s,o,u,n)}r(n,o,s,i,a,c,l)}}function PC(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Js=Z(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.getSchemaRefs=Tt.resolveUrl=Tt.normalizeId=Tt._getFullPath=Tt.getFullPath=Tt.inlineRef=void 0;var AC=xe(),IC=Wf(),OC=Zv(),CC=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function zC(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Jf(t):e?qv(t)<=e:!1}Tt.inlineRef=zC;var NC=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Jf(t){for(let e in t){if(NC.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Jf)||typeof r=="object"&&Jf(r))return!0}return!1}function qv(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!CC.has(r)&&(typeof t[r]=="object"&&(0,AC.eachItem)(t[r],n=>e+=qv(n)),e===1/0))return 1/0}return e}function Fv(t,e="",r){r!==!1&&(e=Ro(e));let n=t.parse(e);return Bv(t,n)}Tt.getFullPath=Fv;function Bv(t,e){return t.serialize(e).split("#")[0]+"#"}Tt._getFullPath=Bv;var jC=/#\/?$/;function Ro(t){return t?t.replace(jC,""):""}Tt.normalizeId=Ro;function LC(t,e,r){return r=Ro(r),t.resolve(e,r)}Tt.resolveUrl=LC;var DC=/^[a-z_][-a-z0-9._]*$/i;function MC(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Ro(t[r]||e),s={"":o},i=Fv(n,o,!1),a={},c=new Set;return OC(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])),P.call(this,d.$anchor),P.call(this,d.$dynamicAnchor),s[b]=v;function E(z){let V=this.opts.uriResolver.resolve;if(z=Ro(v?V(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!==Ro(y)&&(z[0]==="#"?(l(d,a[z],z),a[z]=d):this.refs[z]=y),z}function P(z){if(typeof z=="string"){if(!DC.test(z))throw new Error(`invalid anchor "${z}"`);E.call(this,`#${z}`)}}}),a;function l(d,b,m){if(b!==void 0&&!IC(d,b))throw u(m)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Tt.getSchemaRefs=MC});var Qs=Z(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.getData=tn.KeywordCxt=tn.validateFunctionCode=void 0;var Wv=$v(),Vv=Ws(),Xf=qf(),cc=Ws(),UC=Iv(),Xs=jv(),Yf=Dv(),J=pe(),ie=Rr(),ZC=Js(),Pr=xe(),Ys=Gs();function qC(t){if(Xv(t)&&(Qv(t),Yv(t))){VC(t);return}Jv(t,()=>(0,Wv.topBoolOrEmptySchema)(t))}tn.validateFunctionCode=qC;function Jv({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"; ${Hv(r,o)}`),BC(t,o),t.code(s)}):t.func(e,(0,J._)`${ie.default.data}, ${FC(o)}`,n.$async,()=>t.code(Hv(r,o)).code(s))}function FC(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 BC(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 VC(t){let{schema:e,opts:r,gen:n}=t;Jv(t,()=>{r.$comment&&e.$comment&&tx(t),JC(t),n.let(ie.default.vErrors,null),n.let(ie.default.errors,0),r.unevaluated&&HC(t),ex(t),QC(t)})}function HC(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 Hv(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 KC(t,e){if(Xv(t)&&(Qv(t),Yv(t))){GC(t,e);return}(0,Wv.boolOrEmptySchema)(t,e)}function Yv({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 Xv(t){return typeof t.schema!="boolean"}function GC(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&tx(t),YC(t),XC(t);let s=n.const("_errs",ie.default.errors);ex(t,s),n.var(e,(0,J._)`${s} === ${ie.default.errors}`)}function Qv(t){(0,Pr.checkUnknownRules)(t),WC(t)}function ex(t,e){if(t.opts.jtd)return Kv(t,[],!1,e);let r=(0,Vv.getSchemaTypes)(t.schema),n=(0,Vv.coerceAndCheckDataType)(t,r);Kv(t,r,!n,e)}function WC(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Pr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function JC(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Pr.checkStrictMode)(t,"default is ignored in the schema root")}function YC(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,ZC.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function XC(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function tx({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 QC(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&&ez(t),e.return((0,J._)`${ie.default.errors} === 0`))}function ez({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 Kv(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,Pr.schemaHasRulesButRef)(s,u))){o.block(()=>nx(t,"$ref",u.all.$ref.definition));return}c.jtd||tz(t,e),o.block(()=>{for(let b of u.rules)d(b);d(u.post)});function d(b){(0,Xf.shouldUseGroup)(s,b)&&(b.type?(o.if((0,cc.checkDataType)(b.type,i,c.strictNumbers)),Gv(t,b),e.length===1&&e[0]===b.type&&r&&(o.else(),(0,cc.reportTypeError)(t)),o.endIf()):Gv(t,b),a||o.if((0,J._)`${ie.default.errors} === ${n||0}`))}}function Gv(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,UC.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Xf.shouldUseRule)(n,s)&&nx(t,s.keyword,s.definition,e.type)})}function tz(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(rz(t,e),t.opts.allowUnionTypes||nz(t,e),oz(t,t.dataTypes))}function rz(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{rx(t.dataTypes,r)||Qf(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),iz(t,e)}}function nz(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Qf(t,"use allowUnionTypes to allow union type keyword")}function oz(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Xf.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>sz(e,i))&&Qf(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function sz(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function rx(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function iz(t,e){let r=[];for(let n of t.dataTypes)rx(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,Pr.checkStrictMode)(t,e,t.opts.strictTypes)}var lc=class{constructor(e,r,n){if((0,Xs.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,Pr.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",ox(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Xs.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?Ys.reportExtraError:Ys.reportError)(this,this.def.error,r)}$dataError(){(0,Ys.reportError)(this,this.def.$dataError||Ys.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Ys.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,cc.checkDataTypes)(c,r,s.opts.strictNumbers,cc.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,Yf.getSubschema)(this.it,e);(0,Yf.extendSubschemaData)(n,this.it,e),(0,Yf.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return KC(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Pr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Pr.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}};tn.KeywordCxt=lc;function nx(t,e,r,n){let o=new lc(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Xs.funcKeywordCode)(o,r):"macro"in r?(0,Xs.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Xs.funcKeywordCode)(o,r)}var az=/^\/(?:[^~]|~0|~1)*$/,cz=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ox(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return ie.default.rootData;if(t[0]==="/"){if(!az.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ie.default.rootData}else{let l=cz.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,Pr.unescapeJsonPointer)(l))}`,i=(0,J._)`${i} && ${s}`);return i;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}tn.getData=ox});var uc=Z(th=>{"use strict";Object.defineProperty(th,"__esModule",{value:!0});var eh=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};th.default=eh});var ei=Z(oh=>{"use strict";Object.defineProperty(oh,"__esModule",{value:!0});var rh=Js(),nh=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,rh.resolveUrl)(e,r,n),this.missingSchema=(0,rh.normalizeId)((0,rh.getFullPath)(e,this.missingRef))}};oh.default=nh});var pc=Z(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.resolveSchema=Ht.getCompilingSchema=Ht.resolveRef=Ht.compileSchema=Ht.SchemaEnv=void 0;var tr=pe(),lz=uc(),Ln=Rr(),rr=Js(),sx=xe(),uz=Qs(),Po=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,rr.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Ht.SchemaEnv=Po;function ih(t){let e=ix.call(this,t);if(e)return e;let r=(0,rr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new tr.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:lz.default,code:(0,tr._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:Ln.default.data,parentData:Ln.default.parentData,parentDataProperty:Ln.default.parentDataProperty,dataNames:[Ln.default.data],dataPathArr:[tr.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,tr.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:tr.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,tr._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,uz.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let d=i.toString();u=`${i.scopeRefs(Ln.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let m=new Function(`${Ln.default.self}`,`${Ln.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 tr.Name?void 0:f,items:y instanceof tr.Name?void 0:y,dynamicProps:f instanceof tr.Name,dynamicItems:y instanceof tr.Name},m.source&&(m.source.evaluated=(0,tr.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)}}Ht.compileSchema=ih;function dz(t,e,r){var n;r=(0,rr.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=hz.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 Po({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=pz.call(this,s)}Ht.resolveRef=dz;function pz(t){return(0,rr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:ih.call(this,t)}function ix(t){for(let e of this._compilations)if(fz(e,t))return e}Ht.getCompilingSchema=ix;function fz(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function hz(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||dc.call(this,t,e)}function dc(t,e){let r=this.opts.uriResolver.parse(e),n=(0,rr._getFullPath)(this.opts.uriResolver,r),o=(0,rr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return sh.call(this,r,t);let s=(0,rr.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=dc.call(this,t,i);return typeof a?.schema!="object"?void 0:sh.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||ih.call(this,i),s===(0,rr.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,rr.resolveUrl)(this.opts.uriResolver,o,l)),new Po({schema:a,schemaId:c,root:t,baseId:o})}return sh.call(this,r,i)}}Ht.resolveSchema=dc;var mz=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function sh(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,sx.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!mz.has(a)&&l&&(e=(0,rr.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,sx.schemaHasRulesButRef)(r,this.RULES)){let a=(0,rr.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=dc.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Po({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var ax=Z((m2,gz)=>{gz.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 lh=Z((g2,fx)=>{"use strict";var yz=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),lx=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),ah=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),ux=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),bz=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function ch(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 wz=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function cx(t){return t.length=0,!0}function _z(t,e,r){if(t.length){let n=ch(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function vz(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=_z;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=cx}else{o.push(l);continue}}return o.length&&(a===cx?r.zone=o.join(""):i?n.push(o.join("")):n.push(ch(o))),r.address=n.join(""),r}function dx(t){if(xz(t,":")<2)return{host:t,isIPV6:!1};let e=vz(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 xz(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function kz(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"},Sz=/[@/?#:]/g,Tz=/[@/?#]/g;function px(t,e){let r=e?Tz:Sz;return r.lastIndex=0,t.replace(r,n=>$z[n])}function Ez(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(ah(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&ux(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function Rz(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(ah(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&ux(s)?e+=s:e+="%"+o,r+=2;continue}}bz(t[r])?e+=t[r]:e+=escape(t[r])}return e}function Pz(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(ah(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function Az(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!lx(r)){let n=dx(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=px(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}fx.exports={nonSimpleDomain:wz,recomposeAuthority:Az,reescapeHostDelimiters:px,normalizePercentEncoding:Ez,normalizePathEncoding:Rz,escapePreservingEscapes:Pz,removeDotSegments:kz,isIPv4:lx,isUUID:yz,normalizeIPv6:dx,stringArrayToHexStripped:ch}});var bx=Z((y2,yx)=>{"use strict";var{isUUID:Iz}=lh(),Oz=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Cz=["http","https","ws","wss","urn","urn:uuid"];function zz(t){return Cz.indexOf(t)!==-1}function uh(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 hx(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function mx(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 Nz(t){return t.secure=uh(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function jz(t){if((t.port===(uh(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 Lz(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(Oz);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=dh(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function Dz(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=dh(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 Mz(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!Iz(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Uz(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var gx={scheme:"http",domainHost:!0,parse:hx,serialize:mx},Zz={scheme:"https",domainHost:gx.domainHost,parse:hx,serialize:mx},fc={scheme:"ws",domainHost:!0,parse:Nz,serialize:jz},qz={scheme:"wss",domainHost:fc.domainHost,parse:fc.parse,serialize:fc.serialize},Fz={scheme:"urn",parse:Lz,serialize:Dz,skipNormalize:!0},Bz={scheme:"urn:uuid",parse:Mz,serialize:Uz,skipNormalize:!0},hc={http:gx,https:Zz,ws:fc,wss:qz,urn:Fz,"urn:uuid":Bz};Object.setPrototypeOf(hc,null);function dh(t){return t&&(hc[t]||hc[t.toLowerCase()])||void 0}yx.exports={wsIsSecure:uh,SCHEMES:hc,isValidSchemeName:zz,getSchemeHandler:dh}});var kx=Z((b2,yc)=>{"use strict";var{normalizeIPv6:Vz,removeDotSegments:ti,recomposeAuthority:Hz,normalizePercentEncoding:Kz,normalizePathEncoding:Gz,escapePreservingEscapes:Wz,reescapeHostDelimiters:Jz,isIPv4:Yz,nonSimpleDomain:Xz}=lh(),{SCHEMES:Qz,getSchemeHandler:_x}=bx();function eN(t,e){return typeof t=="string"?t=aN(t,e):typeof t=="object"&&(t=gc(Dn(t,e),e)),t}function tN(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=mc(t,n),{parsed:i,malformedAuthorityOrPort:a}=mc(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let c=vx(o,i,n,!0);return n.skipEscape=!0,Dn(c,n)}function vx(t,e,r,n){let o={};return n||(t=gc(Dn(t,r),r),e=gc(Dn(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=ti(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=ti(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=ti(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=ti(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 rN(t,e,r){let n=wx(t,r),o=wx(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Dn(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=_x(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=Kz(r.path):(r.path=Wz(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=Hz(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=ti(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 nN=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,oN=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,sN=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function iN(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 mc(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(oN);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(sN);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(nN);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=iN(n,c);if(l!==void 0&&(n.error=n.error||l,o=!0),n.host)if(Yz(n.host)===!1){let b=Vz(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=_x(r.scheme||n.scheme);if(!r.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(r.domainHost||u&&u.domainHost)&&s===!1&&Xz(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=Jz(unescape(n.host),s))),n.path&&(n.path=Gz(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 gc(t,e){return mc(t,e).parsed}function aN(t,e){return xx(t,e).normalized}function xx(t,e){let{parsed:r,malformedAuthorityOrPort:n}=mc(t,e);return{normalized:n?t:Dn(r,e),malformedAuthorityOrPort:n}}function wx(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=xx(t,e);return n?void 0:r}if(typeof t=="object")return Dn(t,e)}var ph={SCHEMES:Qz,normalize:eN,resolve:tN,resolveComponent:vx,equal:rN,serialize:Dn,parse:gc};yc.exports=ph;yc.exports.default=ph;yc.exports.fastUri=ph});var Sx=Z(fh=>{"use strict";Object.defineProperty(fh,"__esModule",{value:!0});var $x=kx();$x.code='require("ajv/dist/runtime/uri").default';fh.default=$x});var Cx=Z(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.CodeGen=st.Name=st.nil=st.stringify=st.str=st._=st.KeywordCxt=void 0;var cN=Qs();Object.defineProperty(st,"KeywordCxt",{enumerable:!0,get:function(){return cN.KeywordCxt}});var Ao=pe();Object.defineProperty(st,"_",{enumerable:!0,get:function(){return Ao._}});Object.defineProperty(st,"str",{enumerable:!0,get:function(){return Ao.str}});Object.defineProperty(st,"stringify",{enumerable:!0,get:function(){return Ao.stringify}});Object.defineProperty(st,"nil",{enumerable:!0,get:function(){return Ao.nil}});Object.defineProperty(st,"Name",{enumerable:!0,get:function(){return Ao.Name}});Object.defineProperty(st,"CodeGen",{enumerable:!0,get:function(){return Ao.CodeGen}});var lN=uc(),Ax=ei(),uN=Zf(),ri=pc(),dN=pe(),ni=Js(),bc=Ws(),mh=xe(),Tx=ax(),pN=Sx(),Ix=(t,e)=>new RegExp(t,e);Ix.code="new RegExp";var fN=["removeAdditional","useDefaults","coerceTypes"],hN=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),mN={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."},gN={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Ex=200;function yN(t){var e,r,n,o,s,i,a,c,l,u,d,b,m,f,y,v,E,P,z,V,Y,Ke,et,Ar,sr;let sn=t.strict,Zo=(e=t.code)===null||e===void 0?void 0:e.optimize,Ir=Zo===!0||Zo===void 0?1:Zo||0,qn=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Ix,qo=(o=t.uriResolver)!==null&&o!==void 0?o:pN.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:sn)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:sn)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:sn)!==null&&u!==void 0?u:"log",strictTuples:(b=(d=t.strictTuples)!==null&&d!==void 0?d:sn)!==null&&b!==void 0?b:"log",strictRequired:(f=(m=t.strictRequired)!==null&&m!==void 0?m:sn)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:Ir,regExp:qn}:{optimize:Ir,regExp:qn},loopRequired:(y=t.loopRequired)!==null&&y!==void 0?y:Ex,loopEnum:(v=t.loopEnum)!==null&&v!==void 0?v:Ex,meta:(E=t.meta)!==null&&E!==void 0?E:!0,messages:(P=t.messages)!==null&&P!==void 0?P:!0,inlineRefs:(z=t.inlineRefs)!==null&&z!==void 0?z:!0,schemaId:(V=t.schemaId)!==null&&V!==void 0?V:"$id",addUsedSchema:(Y=t.addUsedSchema)!==null&&Y!==void 0?Y:!0,validateSchema:(Ke=t.validateSchema)!==null&&Ke!==void 0?Ke:!0,validateFormats:(et=t.validateFormats)!==null&&et!==void 0?et:!0,unicodeRegExp:(Ar=t.unicodeRegExp)!==null&&Ar!==void 0?Ar:!0,int32range:(sr=t.int32range)!==null&&sr!==void 0?sr:!0,uriResolver:qo}}var oi=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,...yN(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new dN.ValueScope({scope:{},prefixes:hN,es5:r,lines:n}),this.logger=kN(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,uN.getRules)(),Rx.call(this,mN,e,"NOT SUPPORTED"),Rx.call(this,gN,e,"DEPRECATED","warn"),this._metaOpts=vN.call(this),e.formats&&wN.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&_N.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),bN.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=Tx;n==="id"&&(o={...Tx},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,ni.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=Px.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new ri.SchemaEnv({schema:{},schemaId:n});if(r=ri.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=Px.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,ni.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(SN.call(this,n,r),!r)return(0,mh.eachItem)(n,s=>hh.call(this,s)),this;EN.call(this,r);let o={...r,type:(0,bc.getJSONTypes)(r.type),schemaType:(0,bc.getJSONTypes)(r.schemaType)};return(0,mh.eachItem)(n,o.type.length===0?s=>hh.call(this,s,o):s=>o.type.forEach(i=>hh.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]=Ox(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,ni.normalizeId)(i||n);let l=ni.getSchemaRefs.call(this,e,n);return c=new ri.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):ri.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{ri.compileSchema.call(this,e)}finally{this.opts=r}}};oi.ValidationError=lN.default;oi.MissingRefError=Ax.default;st.default=oi;function Rx(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 Px(t){return t=(0,ni.normalizeId)(t),this.schemas[t]||this.refs[t]}function bN(){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 wN(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function _N(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 vN(){let t={...this.opts};for(let e of fN)delete t[e];return t}var xN={log(){},warn(){},error(){}};function kN(t){if(t===!1)return xN;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 SN(t,e){let{RULES:r}=this;if((0,mh.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 hh(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,bc.getJSONTypes)(e.type),schemaType:(0,bc.getJSONTypes)(e.schemaType)}};e.before?TN.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 TN(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 EN(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Ox(e)),t.validateSchema=this.compile(e,!0))}var RN={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Ox(t){return{anyOf:[t,RN]}}});var zx=Z(gh=>{"use strict";Object.defineProperty(gh,"__esModule",{value:!0});var PN={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};gh.default=PN});var Dx=Z(Mn=>{"use strict";Object.defineProperty(Mn,"__esModule",{value:!0});Mn.callRef=Mn.getValidate=void 0;var AN=ei(),Nx=Vt(),Et=pe(),Io=Rr(),jx=pc(),wc=xe(),IN={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=jx.resolveRef.call(c,l,o,r);if(u===void 0)throw new AN.default(n.opts.uriResolver,o,r);if(u instanceof jx.SchemaEnv)return b(u);return m(u);function d(){if(s===l)return _c(t,i,s,s.$async);let f=e.scopeValue("root",{ref:l});return _c(t,(0,Et._)`${f}.validate`,l,l.$async)}function b(f){let y=Lx(t,f);_c(t,y,f,f.$async)}function m(f){let y=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,Et.stringify)(f)}:{ref:f}),v=e.name("valid"),E=t.subschema({schema:f,dataTypes:[],schemaPath:Et.nil,topSchemaRef:y,errSchemaPath:r},v);t.mergeEvaluated(E),t.ok(v)}}};function Lx(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Et._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Mn.getValidate=Lx;function _c(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?Io.default.this:Et.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,Et._)`await ${(0,Nx.callValidateCode)(t,e,l)}`),m(e),i||o.assign(f,!0)},y=>{o.if((0,Et._)`!(${y} instanceof ${s.ValidationError})`,()=>o.throw(y)),b(y),i||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,Nx.callValidateCode)(t,e,l),()=>m(e),()=>b(e))}function b(f){let y=(0,Et._)`${f}.errors`;o.assign(Io.default.vErrors,(0,Et._)`${Io.default.vErrors} === null ? ${y} : ${Io.default.vErrors}.concat(${y})`),o.assign(Io.default.errors,(0,Et._)`${Io.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=wc.mergeEvaluated.props(o,v.props,s.props));else{let E=o.var("props",(0,Et._)`${f}.evaluated.props`);s.props=wc.mergeEvaluated.props(o,E,s.props,Et.Name)}if(s.items!==!0)if(v&&!v.dynamicItems)v.items!==void 0&&(s.items=wc.mergeEvaluated.items(o,v.items,s.items));else{let E=o.var("items",(0,Et._)`${f}.evaluated.items`);s.items=wc.mergeEvaluated.items(o,E,s.items,Et.Name)}}}Mn.callRef=_c;Mn.default=IN});var Mx=Z(yh=>{"use strict";Object.defineProperty(yh,"__esModule",{value:!0});var ON=zx(),CN=Dx(),zN=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",ON.default,CN.default];yh.default=zN});var Ux=Z(bh=>{"use strict";Object.defineProperty(bh,"__esModule",{value:!0});var vc=pe(),rn=vc.operators,xc={maximum:{okStr:"<=",ok:rn.LTE,fail:rn.GT},minimum:{okStr:">=",ok:rn.GTE,fail:rn.LT},exclusiveMaximum:{okStr:"<",ok:rn.LT,fail:rn.GTE},exclusiveMinimum:{okStr:">",ok:rn.GT,fail:rn.LTE}},NN={message:({keyword:t,schemaCode:e})=>(0,vc.str)`must be ${xc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,vc._)`{comparison: ${xc[t].okStr}, limit: ${e}}`},jN={keyword:Object.keys(xc),type:"number",schemaType:"number",$data:!0,error:NN,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,vc._)`${r} ${xc[e].fail} ${n} || isNaN(${r})`)}};bh.default=jN});var Zx=Z(wh=>{"use strict";Object.defineProperty(wh,"__esModule",{value:!0});var si=pe(),LN={message:({schemaCode:t})=>(0,si.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,si._)`{multipleOf: ${t}}`},DN={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:LN,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,si._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,si._)`${i} !== parseInt(${i})`;t.fail$data((0,si._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};wh.default=DN});var Fx=Z(_h=>{"use strict";Object.defineProperty(_h,"__esModule",{value:!0});function qx(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}_h.default=qx;qx.code='require("ajv/dist/runtime/ucs2length").default'});var Bx=Z(vh=>{"use strict";Object.defineProperty(vh,"__esModule",{value:!0});var Un=pe(),MN=xe(),UN=Fx(),ZN={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Un.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Un._)`{limit: ${t}}`},qN={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:ZN,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Un.operators.GT:Un.operators.LT,i=o.opts.unicode===!1?(0,Un._)`${r}.length`:(0,Un._)`${(0,MN.useFunc)(t.gen,UN.default)}(${r})`;t.fail$data((0,Un._)`${i} ${s} ${n}`)}};vh.default=qN});var Vx=Z(xh=>{"use strict";Object.defineProperty(xh,"__esModule",{value:!0});var FN=Vt(),BN=xe(),Oo=pe(),VN={message:({schemaCode:t})=>(0,Oo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Oo._)`{pattern: ${t}}`},HN={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:VN,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,Oo._)`new RegExp`:(0,BN.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,Oo._)`${l}(${s}, ${a}).test(${r})`),()=>e.assign(u,!1)),t.fail$data((0,Oo._)`!${u}`)}else{let c=(0,FN.usePattern)(t,o);t.fail$data((0,Oo._)`!${c}.test(${r})`)}}};xh.default=HN});var Hx=Z(kh=>{"use strict";Object.defineProperty(kh,"__esModule",{value:!0});var ii=pe(),KN={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,ii.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,ii._)`{limit: ${t}}`},GN={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:KN,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?ii.operators.GT:ii.operators.LT;t.fail$data((0,ii._)`Object.keys(${r}).length ${o} ${n}`)}};kh.default=GN});var Kx=Z($h=>{"use strict";Object.defineProperty($h,"__esModule",{value:!0});var ai=Vt(),ci=pe(),WN=xe(),JN={message:({params:{missingProperty:t}})=>(0,ci.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,ci._)`{missingProperty: ${t}}`},YN={keyword:"required",type:"object",schemaType:"array",$data:!0,error:JN,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,WN.checkStrictMode)(i,E,i.opts.strictRequired)}}function l(){if(c||s)t.block$data(ci.nil,d);else for(let m of r)(0,ai.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,ai.checkMissingProp)(t,r,m)),(0,ai.reportMissingProp)(t,m),e.else()}function d(){e.forOf("prop",n,m=>{t.setParams({missingProperty:m}),e.if((0,ai.noPropertyInData)(e,o,m,a.ownProperties),()=>t.error())})}function b(m,f){t.setParams({missingProperty:m}),e.forOf(m,n,()=>{e.assign(f,(0,ai.propertyInData)(e,o,m,a.ownProperties)),e.if((0,ci.not)(f),()=>{t.error(),e.break()})},ci.nil)}}};$h.default=YN});var Gx=Z(Sh=>{"use strict";Object.defineProperty(Sh,"__esModule",{value:!0});var li=pe(),XN={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,li.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,li._)`{limit: ${t}}`},QN={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:XN,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?li.operators.GT:li.operators.LT;t.fail$data((0,li._)`${r}.length ${o} ${n}`)}};Sh.default=QN});var kc=Z(Th=>{"use strict";Object.defineProperty(Th,"__esModule",{value:!0});var Wx=Wf();Wx.code='require("ajv/dist/runtime/equal").default';Th.default=Wx});var Jx=Z(Rh=>{"use strict";Object.defineProperty(Rh,"__esModule",{value:!0});var Eh=Ws(),it=pe(),e1=xe(),t1=kc(),r1={message:({params:{i:t,j:e}})=>(0,it.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,it._)`{i: ${t}, j: ${e}}`},n1={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:r1,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,Eh.getSchemaTypes)(s.items):[];t.block$data(c,u,(0,it._)`${i} === false`),t.ok(c);function u(){let f=e.let("i",(0,it._)`${r}.length`),y=e.let("j");t.setParams({i:f,j:y}),e.assign(c,!0),e.if((0,it._)`${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,Eh.checkDataTypes)(l,v,a.opts.strictNumbers,Eh.DataType.Wrong),P=e.const("indices",(0,it._)`{}`);e.for((0,it._)`;${f}--;`,()=>{e.let(v,(0,it._)`${r}[${f}]`),e.if(E,(0,it._)`continue`),l.length>1&&e.if((0,it._)`typeof ${v} == "string"`,(0,it._)`${v} += "_"`),e.if((0,it._)`typeof ${P}[${v}] == "number"`,()=>{e.assign(y,(0,it._)`${P}[${v}]`),t.error(),e.assign(c,!1).break()}).code((0,it._)`${P}[${v}] = ${f}`)})}function m(f,y){let v=(0,e1.useFunc)(e,t1.default),E=e.name("outer");e.label(E).for((0,it._)`;${f}--;`,()=>e.for((0,it._)`${y} = ${f}; ${y}--;`,()=>e.if((0,it._)`${v}(${r}[${f}], ${r}[${y}])`,()=>{t.error(),e.assign(c,!1).break(E)})))}}};Rh.default=n1});var Yx=Z(Ah=>{"use strict";Object.defineProperty(Ah,"__esModule",{value:!0});var Ph=pe(),o1=xe(),s1=kc(),i1={message:"must be equal to constant",params:({schemaCode:t})=>(0,Ph._)`{allowedValue: ${t}}`},a1={keyword:"const",$data:!0,error:i1,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Ph._)`!${(0,o1.useFunc)(e,s1.default)}(${r}, ${o})`):t.fail((0,Ph._)`${s} !== ${r}`)}};Ah.default=a1});var Xx=Z(Ih=>{"use strict";Object.defineProperty(Ih,"__esModule",{value:!0});var ui=pe(),c1=xe(),l1=kc(),u1={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,ui._)`{allowedValues: ${t}}`},d1={keyword:"enum",schemaType:"array",$data:!0,error:u1,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,c1.useFunc)(e,l1.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,ui.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,ui._)`${l()}(${r}, ${m})`,()=>e.assign(u,!0).break()))}function b(m,f){let y=o[f];return typeof y=="object"&&y!==null?(0,ui._)`${l()}(${r}, ${m}[${f}])`:(0,ui._)`${r} === ${y}`}}};Ih.default=d1});var Qx=Z(Oh=>{"use strict";Object.defineProperty(Oh,"__esModule",{value:!0});var p1=Ux(),f1=Zx(),h1=Bx(),m1=Vx(),g1=Hx(),y1=Kx(),b1=Gx(),w1=Jx(),_1=Yx(),v1=Xx(),x1=[p1.default,f1.default,h1.default,m1.default,g1.default,y1.default,b1.default,w1.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},_1.default,v1.default];Oh.default=x1});var zh=Z(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});di.validateAdditionalItems=void 0;var Zn=pe(),Ch=xe(),k1={message:({params:{len:t}})=>(0,Zn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Zn._)`{limit: ${t}}`},$1={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:k1,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Ch.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}ek(t,n)}};function ek(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Zn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Zn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Ch.alwaysValidSchema)(i,n)){let l=r.var("valid",(0,Zn._)`${a} <= ${e.length}`);r.if((0,Zn.not)(l),()=>c(l)),t.ok(l)}function c(l){r.forRange("i",e.length,a,u=>{t.subschema({keyword:s,dataProp:u,dataPropType:Ch.Type.Num},l),i.allErrors||r.if((0,Zn.not)(l),()=>r.break())})}}di.validateAdditionalItems=ek;di.default=$1});var Nh=Z(pi=>{"use strict";Object.defineProperty(pi,"__esModule",{value:!0});pi.validateTuple=void 0;var tk=pe(),$c=xe(),S1=Vt(),T1={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return rk(t,"additionalItems",e);r.items=!0,!(0,$c.alwaysValidSchema)(r,e)&&t.ok((0,S1.validateArray)(t))}};function rk(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=$c.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,tk._)`${s}.length`);r.forEach((d,b)=>{(0,$c.alwaysValidSchema)(a,d)||(n.if((0,tk._)`${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,$c.checkStrictMode)(a,v,b.strictTuples)}}}pi.validateTuple=rk;pi.default=T1});var nk=Z(jh=>{"use strict";Object.defineProperty(jh,"__esModule",{value:!0});var E1=Nh(),R1={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,E1.validateTuple)(t,"items")};jh.default=R1});var sk=Z(Lh=>{"use strict";Object.defineProperty(Lh,"__esModule",{value:!0});var ok=pe(),P1=xe(),A1=Vt(),I1=zh(),O1={message:({params:{len:t}})=>(0,ok.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,ok._)`{limit: ${t}}`},C1={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:O1,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,P1.alwaysValidSchema)(n,e)&&(o?(0,I1.validateAdditionalItems)(t,o):t.ok((0,A1.validateArray)(t)))}};Lh.default=C1});var ik=Z(Dh=>{"use strict";Object.defineProperty(Dh,"__esModule",{value:!0});var Kt=pe(),Sc=xe(),z1={message:({params:{min:t,max:e}})=>e===void 0?(0,Kt.str)`must contain at least ${t} valid item(s)`:(0,Kt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Kt._)`{minContains: ${t}}`:(0,Kt._)`{minContains: ${t}, maxContains: ${e}}`},N1={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:z1,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,Kt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Sc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Sc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Sc.alwaysValidSchema)(s,r)){let y=(0,Kt._)`${u} >= ${i}`;a!==void 0&&(y=(0,Kt._)`${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,Kt._)`${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:Sc.Type.Num,compositeRule:!0},y),v()})}function f(y){e.code((0,Kt._)`${y}++`),a===void 0?e.if((0,Kt._)`${y} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,Kt._)`${y} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,Kt._)`${y} >= ${i}`,()=>e.assign(d,!0)))}}};Dh.default=N1});var lk=Z(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.validateSchemaDeps=hr.validatePropertyDeps=hr.error=void 0;var Mh=pe(),j1=xe(),fi=Vt();hr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Mh.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Mh._)`{property: ${t},
1281
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,le._)`[${o}]`)}}}function AC({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,le._)`${e} !== undefined`,()=>t.assign((0,le._)`${e}[${r}]`,n))}function Yf(t,e,r,n=Eo.Correct){let o=n===Eo.Correct?le.operators.EQ:le.operators.NEQ,s;switch(t){case"null":return(0,le._)`${e} ${o} null`;case"array":s=(0,le._)`Array.isArray(${e})`;break;case"object":s=(0,le._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,le._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,le._)`typeof ${e} ${o} ${t}`}return n===Eo.Correct?s:(0,le.not)(s);function i(a=le.nil){return(0,le.and)((0,le._)`typeof ${e} == "number"`,a,r?(0,le._)`isFinite(${e})`:le.nil)}}ft.checkDataType=Yf;function Xf(t,e,r,n){if(t.length===1)return Yf(t[0],e,r,n);let o,s=(0,Vv.toHash)(t);if(s.array&&s.object){let i=(0,le._)`typeof ${e} != "object"`;o=s.null?i:(0,le._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=le.nil;s.number&&delete s.integer;for(let i in s)o=(0,le.and)(o,Yf(i,e,r,n));return o}ft.checkDataTypes=Xf;var IC={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,le._)`{type: ${t}}`:(0,le._)`{type: ${e}}`};function Qf(t){let e=OC(t);(0,SC.reportError)(e,IC)}ft.reportTypeError=Qf;function OC(t){let{gen:e,data:r,schema:n}=t,o=(0,Vv.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Wv=Z(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});dc.assignDefaults=void 0;var Ro=fe(),CC=xe();function zC(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Gv(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Gv(t,s,o.default))}dc.assignDefaults=zC;function Gv(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Ro._)`${s}${(0,Ro.getProperty)(e)}`;if(o){(0,CC.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Ro._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Ro._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Ro._)`${a} = ${(0,Ro.stringify)(r)}`)}});var Ht=Z(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.validateUnion=Ie.validateArray=Ie.usePattern=Ie.callValidateCode=Ie.schemaProperties=Ie.allSchemaProperties=Ie.noPropertyInData=Ie.propertyInData=Ie.isOwnProperty=Ie.hasPropFunc=Ie.reportMissingProp=Ie.checkMissingProp=Ie.checkReportMissingProp=void 0;var Le=fe(),eh=xe(),en=Ar(),NC=xe();function jC(t,e){let{gen:r,data:n,it:o}=t;r.if(rh(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Le._)`${e}`},!0),t.error()})}Ie.checkReportMissingProp=jC;function LC({gen:t,data:e,it:{opts:r}},n,o){return(0,Le.or)(...n.map(s=>(0,Le.and)(rh(t,e,s,r.ownProperties),(0,Le._)`${o} = ${s}`)))}Ie.checkMissingProp=LC;function DC(t,e){t.setParams({missingProperty:e},!0),t.error()}Ie.reportMissingProp=DC;function Jv(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Le._)`Object.prototype.hasOwnProperty`})}Ie.hasPropFunc=Jv;function th(t,e,r){return(0,Le._)`${Jv(t)}.call(${e}, ${r})`}Ie.isOwnProperty=th;function MC(t,e,r,n){let o=(0,Le._)`${e}${(0,Le.getProperty)(r)} !== undefined`;return n?(0,Le._)`${o} && ${th(t,e,r)}`:o}Ie.propertyInData=MC;function rh(t,e,r,n){let o=(0,Le._)`${e}${(0,Le.getProperty)(r)} === undefined`;return n?(0,Le.or)(o,(0,Le.not)(th(t,e,r))):o}Ie.noPropertyInData=rh;function Yv(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Ie.allSchemaProperties=Yv;function UC(t,e){return Yv(e).filter(r=>!(0,eh.alwaysValidSchema)(t,e[r]))}Ie.schemaProperties=UC;function ZC({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,l){let u=l?(0,Le._)`${t}, ${e}, ${n}${o}`:e,d=[[en.default.instancePath,(0,Le.strConcat)(en.default.instancePath,s)],[en.default.parentData,i.parentData],[en.default.parentDataProperty,i.parentDataProperty],[en.default.rootData,en.default.rootData]];i.opts.dynamicRef&&d.push([en.default.dynamicAnchors,en.default.dynamicAnchors]);let w=(0,Le._)`${u}, ${r.object(...d)}`;return c!==Le.nil?(0,Le._)`${a}.call(${c}, ${w})`:(0,Le._)`${a}(${w})`}Ie.callValidateCode=ZC;var qC=(0,Le._)`new RegExp`;function FC({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,Le._)`${o.code==="new RegExp"?qC:(0,NC.useFunc)(t,o)}(${r}, ${n})`})}Ie.usePattern=FC;function BC(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,Le._)`${r}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:n,dataProp:l,dataPropType:eh.Type.Num},s),e.if((0,Le.not)(s),a)})}}Ie.validateArray=BC;function VC(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,eh.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,Le._)`${i} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,Le.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Ie.validateUnion=VC});var ex=Z(fr=>{"use strict";Object.defineProperty(fr,"__esModule",{value:!0});fr.validateKeywordUsage=fr.validSchemaType=fr.funcKeywordCode=fr.macroKeywordCode=void 0;var _t=fe(),Dn=Ar(),HC=Ht(),KC=Ws();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=Qv(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=r.name("valid");t.subschema({schema:a,schemaPath:_t.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}fr.macroKeywordCode=GC;function WC(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;YC(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,u=Qv(n,o,l),d=n.let("valid");t.block$data(d,w),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function w(){if(e.errors===!1)b(),e.modifying&&Xv(t),k(()=>t.error());else{let E=e.async?m():f();e.modifying&&Xv(t),k(()=>JC(t,E))}}function m(){let E=n.let("ruleErrs",null);return n.try(()=>b((0,_t._)`await `),P=>n.assign(d,!1).if((0,_t._)`${P} instanceof ${c.ValidationError}`,()=>n.assign(E,(0,_t._)`${P}.errors`),()=>n.throw(P))),E}function f(){let E=(0,_t._)`${u}.errors`;return n.assign(E,null),b(_t.nil),E}function b(E=e.async?(0,_t._)`await `:_t.nil){let P=c.opts.passContext?Dn.default.this:Dn.default.self,z=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,_t._)`${E}${(0,HC.callValidateCode)(t,u,P,z)}`,e.modifying)}function k(E){var P;n.if((0,_t.not)((P=e.valid)!==null&&P!==void 0?P:d),E)}}fr.funcKeywordCode=WC;function Xv(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,_t._)`${n.parentData}[${n.parentDataProperty}]`))}function JC(t,e){let{gen:r}=t;r.if((0,_t._)`Array.isArray(${e})`,()=>{r.assign(Dn.default.vErrors,(0,_t._)`${Dn.default.vErrors} === null ? ${e} : ${Dn.default.vErrors}.concat(${e})`).assign(Dn.default.errors,(0,_t._)`${Dn.default.vErrors}.length`),(0,KC.extendErrors)(t)},()=>t.error())}function YC({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Qv(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,_t.stringify)(r)})}function XC(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")}fr.validSchemaType=XC;function QC({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)}}fr.validateKeywordUsage=QC});var rx=Z(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.extendSubschemaMode=tn.extendSubschemaData=tn.getSubschema=void 0;var hr=fe(),tx=xe();function ez(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,hr._)`${t.schemaPath}${(0,hr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,hr._)`${t.schemaPath}${(0,hr.getProperty)(e)}${(0,hr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,tx.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')}tn.getSubschema=ez;function tz(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,w=a.let("data",(0,hr._)`${e.data}${(0,hr.getProperty)(r)}`,!0);c(w),t.errorPath=(0,hr.str)`${l}${(0,tx.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,hr._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(o!==void 0){let l=o instanceof hr.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]}}tn.extendSubschemaData=tz;function rz(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}tn.extendSubschemaMode=rz});var nh=Z((Z2,nx)=>{"use strict";nx.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 sx=Z((q2,ox)=>{"use strict";var rn=ox.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(){};pc(e,n,o,t,"",t)};rn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};rn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};rn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};rn.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 pc(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 rn.arrayKeywords)for(var w=0;w<d.length;w++)pc(t,e,r,d[w],o+"/"+u+"/"+w,s,o,u,n,w)}else if(u in rn.propsKeywords){if(d&&typeof d=="object")for(var m in d)pc(t,e,r,d[m],o+"/"+u+"/"+nz(m),s,o,u,n,m)}else(u in rn.keywords||t.allKeys&&!(u in rn.skipKeywords))&&pc(t,e,r,d,o+"/"+u,s,o,u,n)}r(n,o,s,i,a,c,l)}}function nz(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Ys=Z(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.getSchemaRefs=Rt.resolveUrl=Rt.normalizeId=Rt._getFullPath=Rt.getFullPath=Rt.inlineRef=void 0;var oz=xe(),sz=nh(),iz=sx(),az=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function cz(t,e=!0){return typeof t=="boolean"?!0:e===!0?!oh(t):e?ix(t)<=e:!1}Rt.inlineRef=cz;var lz=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function oh(t){for(let e in t){if(lz.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(oh)||typeof r=="object"&&oh(r))return!0}return!1}function ix(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!az.has(r)&&(typeof t[r]=="object"&&(0,oz.eachItem)(t[r],n=>e+=ix(n)),e===1/0))return 1/0}return e}function ax(t,e="",r){r!==!1&&(e=Po(e));let n=t.parse(e);return cx(t,n)}Rt.getFullPath=ax;function cx(t,e){return t.serialize(e).split("#")[0]+"#"}Rt._getFullPath=cx;var uz=/#\/?$/;function Po(t){return t?t.replace(uz,""):""}Rt.normalizeId=Po;function dz(t,e,r){return r=Po(r),t.resolve(e,r)}Rt.resolveUrl=dz;var pz=/^[a-z_][-a-z0-9._]*$/i;function fz(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Po(t[r]||e),s={"":o},i=ax(n,o,!1),a={},c=new Set;return iz(t,{allKeys:!0},(d,w,m,f)=>{if(f===void 0)return;let b=i+w,k=s[f];typeof d[r]=="string"&&(k=E.call(this,d[r])),P.call(this,d.$anchor),P.call(this,d.$dynamicAnchor),s[w]=k;function E(z){let H=this.opts.uriResolver.resolve;if(z=Po(k?H(k,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!==Po(b)&&(z[0]==="#"?(l(d,a[z],z),a[z]=d):this.refs[z]=b),z}function P(z){if(typeof z=="string"){if(!pz.test(z))throw new Error(`invalid anchor "${z}"`);E.call(this,`#${z}`)}}}),a;function l(d,w,m){if(w!==void 0&&!sz(d,w))throw u(m)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Rt.getSchemaRefs=fz});var ei=Z(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});nn.getData=nn.KeywordCxt=nn.validateFunctionCode=void 0;var fx=qv(),lx=Js(),ih=Jf(),fc=Js(),hz=Wv(),Qs=ex(),sh=rx(),J=fe(),ae=Ar(),mz=Ys(),Ir=xe(),Xs=Ws();function gz(t){if(gx(t)&&(yx(t),mx(t))){wz(t);return}hx(t,()=>(0,fx.topBoolOrEmptySchema)(t))}nn.validateFunctionCode=gz;function hx({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,J._)`${ae.default.data}, ${ae.default.valCxt}`,n.$async,()=>{t.code((0,J._)`"use strict"; ${ux(r,o)}`),bz(t,o),t.code(s)}):t.func(e,(0,J._)`${ae.default.data}, ${yz(o)}`,n.$async,()=>t.code(ux(r,o)).code(s))}function yz(t){return(0,J._)`{${ae.default.instancePath}="", ${ae.default.parentData}, ${ae.default.parentDataProperty}, ${ae.default.rootData}=${ae.default.data}${t.dynamicRef?(0,J._)`, ${ae.default.dynamicAnchors}={}`:J.nil}}={}`}function bz(t,e){t.if(ae.default.valCxt,()=>{t.var(ae.default.instancePath,(0,J._)`${ae.default.valCxt}.${ae.default.instancePath}`),t.var(ae.default.parentData,(0,J._)`${ae.default.valCxt}.${ae.default.parentData}`),t.var(ae.default.parentDataProperty,(0,J._)`${ae.default.valCxt}.${ae.default.parentDataProperty}`),t.var(ae.default.rootData,(0,J._)`${ae.default.valCxt}.${ae.default.rootData}`),e.dynamicRef&&t.var(ae.default.dynamicAnchors,(0,J._)`${ae.default.valCxt}.${ae.default.dynamicAnchors}`)},()=>{t.var(ae.default.instancePath,(0,J._)`""`),t.var(ae.default.parentData,(0,J._)`undefined`),t.var(ae.default.parentDataProperty,(0,J._)`undefined`),t.var(ae.default.rootData,ae.default.data),e.dynamicRef&&t.var(ae.default.dynamicAnchors,(0,J._)`{}`)})}function wz(t){let{schema:e,opts:r,gen:n}=t;hx(t,()=>{r.$comment&&e.$comment&&wx(t),$z(t),n.let(ae.default.vErrors,null),n.let(ae.default.errors,0),r.unevaluated&&_z(t),bx(t),Ez(t)})}function _z(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 ux(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 vz(t,e){if(gx(t)&&(yx(t),mx(t))){xz(t,e);return}(0,fx.boolOrEmptySchema)(t,e)}function mx({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 gx(t){return typeof t.schema!="boolean"}function xz(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&wx(t),Sz(t),Tz(t);let s=n.const("_errs",ae.default.errors);bx(t,s),n.var(e,(0,J._)`${s} === ${ae.default.errors}`)}function yx(t){(0,Ir.checkUnknownRules)(t),kz(t)}function bx(t,e){if(t.opts.jtd)return dx(t,[],!1,e);let r=(0,lx.getSchemaTypes)(t.schema),n=(0,lx.coerceAndCheckDataType)(t,r);dx(t,r,!n,e)}function kz(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Ir.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function $z(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Ir.checkStrictMode)(t,"default is ignored in the schema root")}function Sz(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,mz.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Tz(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function wx({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,J._)`${ae.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._)`${ae.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function Ez(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,J._)`${ae.default.errors} === 0`,()=>e.return(ae.default.data),()=>e.throw((0,J._)`new ${o}(${ae.default.vErrors})`)):(e.assign((0,J._)`${n}.errors`,ae.default.vErrors),s.unevaluated&&Rz(t),e.return((0,J._)`${ae.default.errors} === 0`))}function Rz({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 dx(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,Ir.schemaHasRulesButRef)(s,u))){o.block(()=>vx(t,"$ref",u.all.$ref.definition));return}c.jtd||Pz(t,e),o.block(()=>{for(let w of u.rules)d(w);d(u.post)});function d(w){(0,ih.shouldUseGroup)(s,w)&&(w.type?(o.if((0,fc.checkDataType)(w.type,i,c.strictNumbers)),px(t,w),e.length===1&&e[0]===w.type&&r&&(o.else(),(0,fc.reportTypeError)(t)),o.endIf()):px(t,w),a||o.if((0,J._)`${ae.default.errors} === ${n||0}`))}}function px(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,hz.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,ih.shouldUseRule)(n,s)&&vx(t,s.keyword,s.definition,e.type)})}function Pz(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Az(t,e),t.opts.allowUnionTypes||Iz(t,e),Oz(t,t.dataTypes))}function Az(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{_x(t.dataTypes,r)||ah(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),zz(t,e)}}function Iz(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&ah(t,"use allowUnionTypes to allow union type keyword")}function Oz(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,ih.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>Cz(e,i))&&ah(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function Cz(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function _x(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function zz(t,e){let r=[];for(let n of t.dataTypes)_x(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function ah(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Ir.checkStrictMode)(t,e,t.opts.strictTypes)}var hc=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,Ir.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",xx(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",ae.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?Xs.reportExtraError:Xs.reportError)(this,this.def.error,r)}$dataError(){(0,Xs.reportError)(this,this.def.$dataError||Xs.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Xs.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,fc.checkDataTypes)(c,r,s.opts.strictNumbers,fc.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,sh.getSubschema)(this.it,e);(0,sh.extendSubschemaData)(n,this.it,e),(0,sh.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return vz(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Ir.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Ir.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}};nn.KeywordCxt=hc;function vx(t,e,r,n){let o=new hc(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 Nz=/^\/(?:[^~]|~0|~1)*$/,jz=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function xx(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return ae.default.rootData;if(t[0]==="/"){if(!Nz.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ae.default.rootData}else{let l=jz.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,Ir.unescapeJsonPointer)(l))}`,i=(0,J._)`${i} && ${s}`);return i;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}nn.getData=xx});var mc=Z(lh=>{"use strict";Object.defineProperty(lh,"__esModule",{value:!0});var ch=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};lh.default=ch});var ti=Z(ph=>{"use strict";Object.defineProperty(ph,"__esModule",{value:!0});var uh=Ys(),dh=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,uh.resolveUrl)(e,r,n),this.missingSchema=(0,uh.normalizeId)((0,uh.getFullPath)(e,this.missingRef))}};ph.default=dh});var yc=Z(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.resolveSchema=Kt.getCompilingSchema=Kt.resolveRef=Kt.compileSchema=Kt.SchemaEnv=void 0;var nr=fe(),Lz=mc(),Mn=Ar(),or=Ys(),kx=xe(),Dz=ei(),Ao=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,or.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Kt.SchemaEnv=Ao;function hh(t){let e=$x.call(this,t);if(e)return e;let r=(0,or.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new nr.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:Lz.default,code:(0,nr._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:Mn.default.data,parentData:Mn.default.parentData,parentDataProperty:Mn.default.parentDataProperty,dataNames:[Mn.default.data],dataPathArr:[nr.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,nr.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:nr.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,nr._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,Dz.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let d=i.toString();u=`${i.scopeRefs(Mn.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let m=new Function(`${Mn.default.self}`,`${Mn.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:b}=l;m.evaluated={props:f instanceof nr.Name?void 0:f,items:b instanceof nr.Name?void 0:b,dynamicProps:f instanceof nr.Name,dynamicItems:b instanceof nr.Name},m.source&&(m.source.evaluated=(0,nr.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)}}Kt.compileSchema=hh;function Mz(t,e,r){var n;r=(0,or.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=qz.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 Ao({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=Uz.call(this,s)}Kt.resolveRef=Mz;function Uz(t){return(0,or.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:hh.call(this,t)}function $x(t){for(let e of this._compilations)if(Zz(e,t))return e}Kt.getCompilingSchema=$x;function Zz(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function qz(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||gc.call(this,t,e)}function gc(t,e){let r=this.opts.uriResolver.parse(e),n=(0,or._getFullPath)(this.opts.uriResolver,r),o=(0,or.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return fh.call(this,r,t);let s=(0,or.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=gc.call(this,t,i);return typeof a?.schema!="object"?void 0:fh.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||hh.call(this,i),s===(0,or.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,or.resolveUrl)(this.opts.uriResolver,o,l)),new Ao({schema:a,schemaId:c,root:t,baseId:o})}return fh.call(this,r,i)}}Kt.resolveSchema=gc;var Fz=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function fh(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,kx.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!Fz.has(a)&&l&&(e=(0,or.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,kx.schemaHasRulesButRef)(r,this.RULES)){let a=(0,or.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=gc.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Ao({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Sx=Z((G2,Bz)=>{Bz.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 yh=Z((W2,Ix)=>{"use strict";var Vz=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Ex=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),mh=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Rx=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Hz=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function gh(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 Kz=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Tx(t){return t.length=0,!0}function Gz(t,e,r){if(t.length){let n=gh(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function Wz(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=Tx}else{o.push(l);continue}}return o.length&&(a===Tx?r.zone=o.join(""):i?n.push(o.join("")):n.push(gh(o))),r.address=n.join(""),r}function Px(t){if(Jz(t,":")<2)return{host:t,isIPV6:!1};let e=Wz(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 Jz(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function Yz(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 Xz={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Qz=/[@/?#:]/g,eN=/[@/?#]/g;function Ax(t,e){let r=e?eN:Qz;return r.lastIndex=0,t.replace(r,n=>Xz[n])}function tN(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(mh(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Rx(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function rN(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(mh(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Rx(s)?e+=s:e+="%"+o,r+=2;continue}}Hz(t[r])?e+=t[r]:e+=escape(t[r])}return e}function nN(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(mh(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function oN(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!Ex(r)){let n=Px(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Ax(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}Ix.exports={nonSimpleDomain:Kz,recomposeAuthority:oN,reescapeHostDelimiters:Ax,normalizePercentEncoding:tN,normalizePathEncoding:rN,escapePreservingEscapes:nN,removeDotSegments:Yz,isIPv4:Ex,isUUID:Vz,normalizeIPv6:Px,stringArrayToHexStripped:gh}});var jx=Z((J2,Nx)=>{"use strict";var{isUUID:sN}=yh(),iN=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,aN=["http","https","ws","wss","urn","urn:uuid"];function cN(t){return aN.indexOf(t)!==-1}function bh(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 Ox(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Cx(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 lN(t){return t.secure=bh(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function uN(t){if((t.port===(bh(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 dN(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(iN);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=wh(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function pN(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=wh(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 fN(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!sN(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function hN(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var zx={scheme:"http",domainHost:!0,parse:Ox,serialize:Cx},mN={scheme:"https",domainHost:zx.domainHost,parse:Ox,serialize:Cx},bc={scheme:"ws",domainHost:!0,parse:lN,serialize:uN},gN={scheme:"wss",domainHost:bc.domainHost,parse:bc.parse,serialize:bc.serialize},yN={scheme:"urn",parse:dN,serialize:pN,skipNormalize:!0},bN={scheme:"urn:uuid",parse:fN,serialize:hN,skipNormalize:!0},wc={http:zx,https:mN,ws:bc,wss:gN,urn:yN,"urn:uuid":bN};Object.setPrototypeOf(wc,null);function wh(t){return t&&(wc[t]||wc[t.toLowerCase()])||void 0}Nx.exports={wsIsSecure:bh,SCHEMES:wc,isValidSchemeName:cN,getSchemeHandler:wh}});var Zx=Z((Y2,xc)=>{"use strict";var{normalizeIPv6:wN,removeDotSegments:ri,recomposeAuthority:_N,normalizePercentEncoding:vN,normalizePathEncoding:xN,escapePreservingEscapes:kN,reescapeHostDelimiters:$N,isIPv4:SN,nonSimpleDomain:TN}=yh(),{SCHEMES:EN,getSchemeHandler:Dx}=jx();function RN(t,e){return typeof t=="string"?t=NN(t,e):typeof t=="object"&&(t=vc(Un(t,e),e)),t}function PN(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=_c(t,n),{parsed:i,malformedAuthorityOrPort:a}=_c(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let c=Mx(o,i,n,!0);return n.skipEscape=!0,Un(c,n)}function Mx(t,e,r,n){let o={};return n||(t=vc(Un(t,r),r),e=vc(Un(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=ri(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=ri(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=ri(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=ri(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 AN(t,e,r){let n=Lx(t,r),o=Lx(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Un(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=Dx(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=vN(r.path):(r.path=kN(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=_N(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=ri(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 IN=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,ON=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,CN=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function zN(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 _c(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(ON);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(CN);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(IN);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=zN(n,c);if(l!==void 0&&(n.error=n.error||l,o=!0),n.host)if(SN(n.host)===!1){let w=wN(n.host);n.host=w.host.toLowerCase(),s=w.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=Dx(r.scheme||n.scheme);if(!r.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(r.domainHost||u&&u.domainHost)&&s===!1&&TN(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=$N(unescape(n.host),s))),n.path&&(n.path=xN(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 vc(t,e){return _c(t,e).parsed}function NN(t,e){return Ux(t,e).normalized}function Ux(t,e){let{parsed:r,malformedAuthorityOrPort:n}=_c(t,e);return{normalized:n?t:Un(r,e),malformedAuthorityOrPort:n}}function Lx(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Ux(t,e);return n?void 0:r}if(typeof t=="object")return Un(t,e)}var _h={SCHEMES:EN,normalize:RN,resolve:PN,resolveComponent:Mx,equal:AN,serialize:Un,parse:vc};xc.exports=_h;xc.exports.default=_h;xc.exports.fastUri=_h});var Fx=Z(vh=>{"use strict";Object.defineProperty(vh,"__esModule",{value:!0});var qx=Zx();qx.code='require("ajv/dist/runtime/uri").default';vh.default=qx});var Yx=Z(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.CodeGen=it.Name=it.nil=it.stringify=it.str=it._=it.KeywordCxt=void 0;var jN=ei();Object.defineProperty(it,"KeywordCxt",{enumerable:!0,get:function(){return jN.KeywordCxt}});var Io=fe();Object.defineProperty(it,"_",{enumerable:!0,get:function(){return Io._}});Object.defineProperty(it,"str",{enumerable:!0,get:function(){return Io.str}});Object.defineProperty(it,"stringify",{enumerable:!0,get:function(){return Io.stringify}});Object.defineProperty(it,"nil",{enumerable:!0,get:function(){return Io.nil}});Object.defineProperty(it,"Name",{enumerable:!0,get:function(){return Io.Name}});Object.defineProperty(it,"CodeGen",{enumerable:!0,get:function(){return Io.CodeGen}});var LN=mc(),Gx=ti(),DN=Wf(),ni=yc(),MN=fe(),oi=Ys(),kc=Js(),kh=xe(),Bx=Sx(),UN=Fx(),Wx=(t,e)=>new RegExp(t,e);Wx.code="new RegExp";var ZN=["removeAdditional","useDefaults","coerceTypes"],qN=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),FN={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."},BN={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Vx=200;function VN(t){var e,r,n,o,s,i,a,c,l,u,d,w,m,f,b,k,E,P,z,H,Y,Ge,tt,Or,Cr;let At=t.strict,qo=(e=t.code)===null||e===void 0?void 0:e.optimize,bi=qo===!0||qo===void 0?1:qo||0,zr=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Wx,Fo=(o=t.uriResolver)!==null&&o!==void 0?o:UN.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:At)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:At)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:At)!==null&&u!==void 0?u:"log",strictTuples:(w=(d=t.strictTuples)!==null&&d!==void 0?d:At)!==null&&w!==void 0?w:"log",strictRequired:(f=(m=t.strictRequired)!==null&&m!==void 0?m:At)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:bi,regExp:zr}:{optimize:bi,regExp:zr},loopRequired:(b=t.loopRequired)!==null&&b!==void 0?b:Vx,loopEnum:(k=t.loopEnum)!==null&&k!==void 0?k:Vx,meta:(E=t.meta)!==null&&E!==void 0?E:!0,messages:(P=t.messages)!==null&&P!==void 0?P:!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:(Ge=t.validateSchema)!==null&&Ge!==void 0?Ge:!0,validateFormats:(tt=t.validateFormats)!==null&&tt!==void 0?tt:!0,unicodeRegExp:(Or=t.unicodeRegExp)!==null&&Or!==void 0?Or:!0,int32range:(Cr=t.int32range)!==null&&Cr!==void 0?Cr:!0,uriResolver:Fo}}var si=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,...VN(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new MN.ValueScope({scope:{},prefixes:qN,es5:r,lines:n}),this.logger=YN(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,DN.getRules)(),Hx.call(this,FN,e,"NOT SUPPORTED"),Hx.call(this,BN,e,"DEPRECATED","warn"),this._metaOpts=WN.call(this),e.formats&&KN.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=Bx;n==="id"&&(o={...Bx},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 w=this._addSchema(u,d);return w.validate||i.call(this,w)}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 Gx.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,oi.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=Kx.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new ni.SchemaEnv({schema:{},schemaId:n});if(r=ni.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=Kx.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,oi.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(QN.call(this,n,r),!r)return(0,kh.eachItem)(n,s=>xh.call(this,s)),this;t1.call(this,r);let o={...r,type:(0,kc.getJSONTypes)(r.type),schemaType:(0,kc.getJSONTypes)(r.schemaType)};return(0,kh.eachItem)(n,o.type.length===0?s=>xh.call(this,s,o):s=>o.type.forEach(i=>xh.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]=Jx(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,oi.normalizeId)(i||n);let l=oi.getSchemaRefs.call(this,e,n);return c=new ni.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):ni.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{ni.compileSchema.call(this,e)}finally{this.opts=r}}};si.ValidationError=LN.default;si.MissingRefError=Gx.default;it.default=si;function Hx(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 Kx(t){return t=(0,oi.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 KN(){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 WN(){let t={...this.opts};for(let e of ZN)delete t[e];return t}var JN={log(){},warn(){},error(){}};function YN(t){if(t===!1)return JN;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 XN=/^[a-z_$][a-z0-9_$:-]*$/i;function QN(t,e){let{RULES:r}=this;if((0,kh.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!XN.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 xh(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,kc.getJSONTypes)(e.type),schemaType:(0,kc.getJSONTypes)(e.schemaType)}};e.before?e1.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 e1(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 t1(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Jx(e)),t.validateSchema=this.compile(e,!0))}var r1={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Jx(t){return{anyOf:[t,r1]}}});var Xx=Z($h=>{"use strict";Object.defineProperty($h,"__esModule",{value:!0});var n1={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};$h.default=n1});var rk=Z(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.callRef=Zn.getValidate=void 0;var o1=ti(),Qx=Ht(),Pt=fe(),Oo=Ar(),ek=yc(),$c=xe(),s1={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=ek.resolveRef.call(c,l,o,r);if(u===void 0)throw new o1.default(n.opts.uriResolver,o,r);if(u instanceof ek.SchemaEnv)return w(u);return m(u);function d(){if(s===l)return Sc(t,i,s,s.$async);let f=e.scopeValue("root",{ref:l});return Sc(t,(0,Pt._)`${f}.validate`,l,l.$async)}function w(f){let b=tk(t,f);Sc(t,b,f,f.$async)}function m(f){let b=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,Pt.stringify)(f)}:{ref:f}),k=e.name("valid"),E=t.subschema({schema:f,dataTypes:[],schemaPath:Pt.nil,topSchemaRef:b,errSchemaPath:r},k);t.mergeEvaluated(E),t.ok(k)}}};function tk(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Pt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Zn.getValidate=tk;function Sc(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?Oo.default.this:Pt.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,Pt._)`await ${(0,Qx.callValidateCode)(t,e,l)}`),m(e),i||o.assign(f,!0)},b=>{o.if((0,Pt._)`!(${b} instanceof ${s.ValidationError})`,()=>o.throw(b)),w(b),i||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,Qx.callValidateCode)(t,e,l),()=>m(e),()=>w(e))}function w(f){let b=(0,Pt._)`${f}.errors`;o.assign(Oo.default.vErrors,(0,Pt._)`${Oo.default.vErrors} === null ? ${b} : ${Oo.default.vErrors}.concat(${b})`),o.assign(Oo.default.errors,(0,Pt._)`${Oo.default.vErrors}.length`)}function m(f){var b;if(!s.opts.unevaluated)return;let k=(b=r?.validate)===null||b===void 0?void 0:b.evaluated;if(s.props!==!0)if(k&&!k.dynamicProps)k.props!==void 0&&(s.props=$c.mergeEvaluated.props(o,k.props,s.props));else{let E=o.var("props",(0,Pt._)`${f}.evaluated.props`);s.props=$c.mergeEvaluated.props(o,E,s.props,Pt.Name)}if(s.items!==!0)if(k&&!k.dynamicItems)k.items!==void 0&&(s.items=$c.mergeEvaluated.items(o,k.items,s.items));else{let E=o.var("items",(0,Pt._)`${f}.evaluated.items`);s.items=$c.mergeEvaluated.items(o,E,s.items,Pt.Name)}}}Zn.callRef=Sc;Zn.default=s1});var nk=Z(Sh=>{"use strict";Object.defineProperty(Sh,"__esModule",{value:!0});var i1=Xx(),a1=rk(),c1=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",i1.default,a1.default];Sh.default=c1});var ok=Z(Th=>{"use strict";Object.defineProperty(Th,"__esModule",{value:!0});var Tc=fe(),on=Tc.operators,Ec={maximum:{okStr:"<=",ok:on.LTE,fail:on.GT},minimum:{okStr:">=",ok:on.GTE,fail:on.LT},exclusiveMaximum:{okStr:"<",ok:on.LT,fail:on.GTE},exclusiveMinimum:{okStr:">",ok:on.GT,fail:on.LTE}},l1={message:({keyword:t,schemaCode:e})=>(0,Tc.str)`must be ${Ec[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Tc._)`{comparison: ${Ec[t].okStr}, limit: ${e}}`},u1={keyword:Object.keys(Ec),type:"number",schemaType:"number",$data:!0,error:l1,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Tc._)`${r} ${Ec[e].fail} ${n} || isNaN(${r})`)}};Th.default=u1});var sk=Z(Eh=>{"use strict";Object.defineProperty(Eh,"__esModule",{value:!0});var ii=fe(),d1={message:({schemaCode:t})=>(0,ii.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ii._)`{multipleOf: ${t}}`},p1={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:d1,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,ii._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,ii._)`${i} !== parseInt(${i})`;t.fail$data((0,ii._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Eh.default=p1});var ak=Z(Rh=>{"use strict";Object.defineProperty(Rh,"__esModule",{value:!0});function ik(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}Rh.default=ik;ik.code='require("ajv/dist/runtime/ucs2length").default'});var ck=Z(Ph=>{"use strict";Object.defineProperty(Ph,"__esModule",{value:!0});var qn=fe(),f1=xe(),h1=ak(),m1={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,qn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,qn._)`{limit: ${t}}`},g1={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:m1,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?qn.operators.GT:qn.operators.LT,i=o.opts.unicode===!1?(0,qn._)`${r}.length`:(0,qn._)`${(0,f1.useFunc)(t.gen,h1.default)}(${r})`;t.fail$data((0,qn._)`${i} ${s} ${n}`)}};Ph.default=g1});var lk=Z(Ah=>{"use strict";Object.defineProperty(Ah,"__esModule",{value:!0});var y1=Ht(),b1=xe(),Co=fe(),w1={message:({schemaCode:t})=>(0,Co.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Co._)`{pattern: ${t}}`},_1={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:w1,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,Co._)`new RegExp`:(0,b1.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,Co._)`${l}(${s}, ${a}).test(${r})`),()=>e.assign(u,!1)),t.fail$data((0,Co._)`!${u}`)}else{let c=(0,y1.usePattern)(t,o);t.fail$data((0,Co._)`!${c}.test(${r})`)}}};Ah.default=_1});var uk=Z(Ih=>{"use strict";Object.defineProperty(Ih,"__esModule",{value:!0});var ai=fe(),v1={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,ai.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,ai._)`{limit: ${t}}`},x1={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:v1,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?ai.operators.GT:ai.operators.LT;t.fail$data((0,ai._)`Object.keys(${r}).length ${o} ${n}`)}};Ih.default=x1});var dk=Z(Oh=>{"use strict";Object.defineProperty(Oh,"__esModule",{value:!0});var ci=Ht(),li=fe(),k1=xe(),$1={message:({params:{missingProperty:t}})=>(0,li.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,li._)`{missingProperty: ${t}}`},S1={keyword:"required",type:"object",schemaType:"array",$data:!0,error:$1,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 b of r)if(m?.[b]===void 0&&!f.has(b)){let k=i.schemaEnv.baseId+i.errSchemaPath,E=`required property "${b}" is not defined at "${k}" (strictRequired)`;(0,k1.checkStrictMode)(i,E,i.opts.strictRequired)}}function l(){if(c||s)t.block$data(li.nil,d);else for(let m of r)(0,ci.checkReportMissingProp)(t,m)}function u(){let m=e.let("missing");if(c||s){let f=e.let("valid",!0);t.block$data(f,()=>w(m,f)),t.ok(f)}else e.if((0,ci.checkMissingProp)(t,r,m)),(0,ci.reportMissingProp)(t,m),e.else()}function d(){e.forOf("prop",n,m=>{t.setParams({missingProperty:m}),e.if((0,ci.noPropertyInData)(e,o,m,a.ownProperties),()=>t.error())})}function w(m,f){t.setParams({missingProperty:m}),e.forOf(m,n,()=>{e.assign(f,(0,ci.propertyInData)(e,o,m,a.ownProperties)),e.if((0,li.not)(f),()=>{t.error(),e.break()})},li.nil)}}};Oh.default=S1});var pk=Z(Ch=>{"use strict";Object.defineProperty(Ch,"__esModule",{value:!0});var ui=fe(),T1={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,ui.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,ui._)`{limit: ${t}}`},E1={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:T1,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?ui.operators.GT:ui.operators.LT;t.fail$data((0,ui._)`${r}.length ${o} ${n}`)}};Ch.default=E1});var Rc=Z(zh=>{"use strict";Object.defineProperty(zh,"__esModule",{value:!0});var fk=nh();fk.code='require("ajv/dist/runtime/equal").default';zh.default=fk});var hk=Z(jh=>{"use strict";Object.defineProperty(jh,"__esModule",{value:!0});var Nh=Js(),at=fe(),R1=xe(),P1=Rc(),A1={message:({params:{i:t,j:e}})=>(0,at.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,at._)`{i: ${t}, j: ${e}}`},I1={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:A1,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,Nh.getSchemaTypes)(s.items):[];t.block$data(c,u,(0,at._)`${i} === false`),t.ok(c);function u(){let f=e.let("i",(0,at._)`${r}.length`),b=e.let("j");t.setParams({i:f,j:b}),e.assign(c,!0),e.if((0,at._)`${f} > 1`,()=>(d()?w:m)(f,b))}function d(){return l.length>0&&!l.some(f=>f==="object"||f==="array")}function w(f,b){let k=e.name("item"),E=(0,Nh.checkDataTypes)(l,k,a.opts.strictNumbers,Nh.DataType.Wrong),P=e.const("indices",(0,at._)`{}`);e.for((0,at._)`;${f}--;`,()=>{e.let(k,(0,at._)`${r}[${f}]`),e.if(E,(0,at._)`continue`),l.length>1&&e.if((0,at._)`typeof ${k} == "string"`,(0,at._)`${k} += "_"`),e.if((0,at._)`typeof ${P}[${k}] == "number"`,()=>{e.assign(b,(0,at._)`${P}[${k}]`),t.error(),e.assign(c,!1).break()}).code((0,at._)`${P}[${k}] = ${f}`)})}function m(f,b){let k=(0,R1.useFunc)(e,P1.default),E=e.name("outer");e.label(E).for((0,at._)`;${f}--;`,()=>e.for((0,at._)`${b} = ${f}; ${b}--;`,()=>e.if((0,at._)`${k}(${r}[${f}], ${r}[${b}])`,()=>{t.error(),e.assign(c,!1).break(E)})))}}};jh.default=I1});var mk=Z(Dh=>{"use strict";Object.defineProperty(Dh,"__esModule",{value:!0});var Lh=fe(),O1=xe(),C1=Rc(),z1={message:"must be equal to constant",params:({schemaCode:t})=>(0,Lh._)`{allowedValue: ${t}}`},N1={keyword:"const",$data:!0,error:z1,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Lh._)`!${(0,O1.useFunc)(e,C1.default)}(${r}, ${o})`):t.fail((0,Lh._)`${s} !== ${r}`)}};Dh.default=N1});var gk=Z(Mh=>{"use strict";Object.defineProperty(Mh,"__esModule",{value:!0});var di=fe(),j1=xe(),L1=Rc(),D1={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,di._)`{allowedValues: ${t}}`},M1={keyword:"enum",schemaType:"array",$data:!0,error:D1,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,j1.useFunc)(e,L1.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,di.or)(...o.map((f,b)=>w(m,b)))}t.pass(u);function d(){e.assign(u,!1),e.forOf("v",s,m=>e.if((0,di._)`${l()}(${r}, ${m})`,()=>e.assign(u,!0).break()))}function w(m,f){let b=o[f];return typeof b=="object"&&b!==null?(0,di._)`${l()}(${r}, ${m}[${f}])`:(0,di._)`${r} === ${b}`}}};Mh.default=M1});var yk=Z(Uh=>{"use strict";Object.defineProperty(Uh,"__esModule",{value:!0});var U1=ok(),Z1=sk(),q1=ck(),F1=lk(),B1=uk(),V1=dk(),H1=pk(),K1=hk(),G1=mk(),W1=gk(),J1=[U1.default,Z1.default,q1.default,F1.default,B1.default,V1.default,H1.default,K1.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},G1.default,W1.default];Uh.default=J1});var qh=Z(pi=>{"use strict";Object.defineProperty(pi,"__esModule",{value:!0});pi.validateAdditionalItems=void 0;var Fn=fe(),Zh=xe(),Y1={message:({params:{len:t}})=>(0,Fn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Fn._)`{limit: ${t}}`},X1={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Y1,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Zh.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}bk(t,n)}};function bk(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Fn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Fn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Zh.alwaysValidSchema)(i,n)){let l=r.var("valid",(0,Fn._)`${a} <= ${e.length}`);r.if((0,Fn.not)(l),()=>c(l)),t.ok(l)}function c(l){r.forRange("i",e.length,a,u=>{t.subschema({keyword:s,dataProp:u,dataPropType:Zh.Type.Num},l),i.allErrors||r.if((0,Fn.not)(l),()=>r.break())})}}pi.validateAdditionalItems=bk;pi.default=X1});var Fh=Z(fi=>{"use strict";Object.defineProperty(fi,"__esModule",{value:!0});fi.validateTuple=void 0;var wk=fe(),Pc=xe(),Q1=Ht(),ej={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return _k(t,"additionalItems",e);r.items=!0,!(0,Pc.alwaysValidSchema)(r,e)&&t.ok((0,Q1.validateArray)(t))}};function _k(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=Pc.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,wk._)`${s}.length`);r.forEach((d,w)=>{(0,Pc.alwaysValidSchema)(a,d)||(n.if((0,wk._)`${l} > ${w}`,()=>t.subschema({keyword:i,schemaProp:w,dataProp:w},c)),t.ok(c))});function u(d){let{opts:w,errSchemaPath:m}=a,f=r.length,b=f===d.minItems&&(f===d.maxItems||d[e]===!1);if(w.strictTuples&&!b){let k=`"${i}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${m}"`;(0,Pc.checkStrictMode)(a,k,w.strictTuples)}}}fi.validateTuple=_k;fi.default=ej});var vk=Z(Bh=>{"use strict";Object.defineProperty(Bh,"__esModule",{value:!0});var tj=Fh(),rj={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,tj.validateTuple)(t,"items")};Bh.default=rj});var kk=Z(Vh=>{"use strict";Object.defineProperty(Vh,"__esModule",{value:!0});var xk=fe(),nj=xe(),oj=Ht(),sj=qh(),ij={message:({params:{len:t}})=>(0,xk.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,xk._)`{limit: ${t}}`},aj={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:ij,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,nj.alwaysValidSchema)(n,e)&&(o?(0,sj.validateAdditionalItems)(t,o):t.ok((0,oj.validateArray)(t)))}};Vh.default=aj});var $k=Z(Hh=>{"use strict";Object.defineProperty(Hh,"__esModule",{value:!0});var Gt=fe(),Ac=xe(),cj={message:({params:{min:t,max:e}})=>e===void 0?(0,Gt.str)`must contain at least ${t} valid item(s)`:(0,Gt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Gt._)`{minContains: ${t}}`:(0,Gt._)`{minContains: ${t}, maxContains: ${e}}`},lj={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:cj,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,Gt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Ac.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Ac.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Ac.alwaysValidSchema)(s,r)){let b=(0,Gt._)`${u} >= ${i}`;a!==void 0&&(b=(0,Gt._)`${b} && ${u} <= ${a}`),t.pass(b);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,Gt._)`${o}.length > 0`,w)):(e.let(d,!1),w()),t.result(d,()=>t.reset());function w(){let b=e.name("_valid"),k=e.let("count",0);m(b,()=>e.if(b,()=>f(k)))}function m(b,k){e.forRange("i",0,u,E=>{t.subschema({keyword:"contains",dataProp:E,dataPropType:Ac.Type.Num,compositeRule:!0},b),k()})}function f(b){e.code((0,Gt._)`${b}++`),a===void 0?e.if((0,Gt._)`${b} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,Gt._)`${b} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,Gt._)`${b} >= ${i}`,()=>e.assign(d,!0)))}}};Hh.default=lj});var Ek=Z(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.validateSchemaDeps=mr.validatePropertyDeps=mr.error=void 0;var Kh=fe(),uj=xe(),hi=Ht();mr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Kh.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Kh._)`{property: ${t},
1137
1282
  missingProperty: ${n},
1138
1283
  depsCount: ${e},
1139
- deps: ${r}}`};var L1={keyword:"dependencies",type:"object",schemaType:"object",error:hr.error,code(t){let[e,r]=D1(t);ak(t,e),ck(t,r)}};function D1({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 ak(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,fi.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,fi.checkReportMissingProp)(t,l)}):(r.if((0,Mh._)`${c} && (${(0,fi.checkMissingProp)(t,a,s)})`),(0,fi.reportMissingProp)(t,s),r.else())}}hr.validatePropertyDeps=ak;function ck(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,j1.alwaysValidSchema)(s,e[a])||(r.if((0,fi.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))}hr.validateSchemaDeps=ck;hr.default=L1});var dk=Z(Uh=>{"use strict";Object.defineProperty(Uh,"__esModule",{value:!0});var uk=pe(),M1=xe(),U1={message:"property name must be valid",params:({params:t})=>(0,uk._)`{propertyName: ${t.propertyName}}`},Z1={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:U1,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,M1.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,uk.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Uh.default=Z1});var qh=Z(Zh=>{"use strict";Object.defineProperty(Zh,"__esModule",{value:!0});var Tc=Vt(),nr=pe(),q1=Rr(),Ec=xe(),F1={message:"must NOT have additional properties",params:({params:t})=>(0,nr._)`{additionalProperty: ${t.additionalProperty}}`},B1={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:F1,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,Ec.alwaysValidSchema)(i,r))return;let l=(0,Tc.allSchemaProperties)(n.properties),u=(0,Tc.allSchemaProperties)(n.patternProperties);d(),t.ok((0,nr._)`${s} === ${q1.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 P=(0,Ec.schemaRefOrVal)(i,n.properties,"properties");E=(0,Tc.isOwnProperty)(e,P,v)}else l.length?E=(0,nr.or)(...l.map(P=>(0,nr._)`${v} === ${P}`)):E=nr.nil;return u.length&&(E=(0,nr.or)(E,...u.map(P=>(0,nr._)`${(0,Tc.usePattern)(t,P)}.test(${v})`))),(0,nr.not)(E)}function m(v){e.code((0,nr._)`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,Ec.alwaysValidSchema)(i,r)){let E=e.name("valid");c.removeAdditional==="failing"?(y(v,E,!1),e.if((0,nr.not)(E),()=>{t.reset(),m(v)})):(y(v,E),a||e.if((0,nr.not)(E),()=>e.break()))}}function y(v,E,P){let z={keyword:"additionalProperties",dataProp:v,dataPropType:Ec.Type.Str};P===!1&&Object.assign(z,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(z,E)}}};Zh.default=B1});var hk=Z(Bh=>{"use strict";Object.defineProperty(Bh,"__esModule",{value:!0});var V1=Qs(),pk=Vt(),Fh=xe(),fk=qh(),H1={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&&fk.default.code(new V1.KeywordCxt(s,fk.default,"additionalProperties"));let i=(0,pk.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Fh.mergeEvaluated.props(e,(0,Fh.toHash)(i),s.props));let a=i.filter(d=>!(0,Fh.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,pk.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)}}};Bh.default=H1});var bk=Z(Vh=>{"use strict";Object.defineProperty(Vh,"__esModule",{value:!0});var mk=Vt(),Rc=pe(),gk=xe(),yk=xe(),K1={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,mk.allSchemaProperties)(r),c=a.filter(y=>(0,gk.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 Rc.Name)&&(s.props=(0,yk.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,gk.checkStrictMode)(s,`property ${v} matches pattern ${y} (use allowMatchingProperties)`)}function f(y){e.forIn("key",n,v=>{e.if((0,Rc._)`${(0,mk.usePattern)(t,y)}.test(${v})`,()=>{let E=c.includes(y);E||t.subschema({keyword:"patternProperties",schemaProp:y,dataProp:v,dataPropType:yk.Type.Str},u),s.opts.unevaluated&&d!==!0?e.assign((0,Rc._)`${d}[${v}]`,!0):!E&&!s.allErrors&&e.if((0,Rc.not)(u),()=>e.break())})})}}};Vh.default=K1});var wk=Z(Hh=>{"use strict";Object.defineProperty(Hh,"__esModule",{value:!0});var G1=xe(),W1={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,G1.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"}};Hh.default=W1});var _k=Z(Kh=>{"use strict";Object.defineProperty(Kh,"__esModule",{value:!0});var J1=Vt(),Y1={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:J1.validateUnion,error:{message:"must match a schema in anyOf"}};Kh.default=Y1});var vk=Z(Gh=>{"use strict";Object.defineProperty(Gh,"__esModule",{value:!0});var Pc=pe(),X1=xe(),Q1={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Pc._)`{passingSchemas: ${t.passing}}`},ej={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Q1,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,X1.alwaysValidSchema)(o,u)?e.var(c,!0):b=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Pc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Pc._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),b&&t.mergeEvaluated(b,Pc.Name)})})}}};Gh.default=ej});var xk=Z(Wh=>{"use strict";Object.defineProperty(Wh,"__esModule",{value:!0});var tj=xe(),rj={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,tj.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Wh.default=rj});var Sk=Z(Jh=>{"use strict";Object.defineProperty(Jh,"__esModule",{value:!0});var Ac=pe(),$k=xe(),nj={message:({params:t})=>(0,Ac.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Ac._)`{failingKeyword: ${t.ifClause}}`},oj={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:nj,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,$k.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=kk(n,"then"),s=kk(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,Ac.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,Ac._)`${u}`):t.setParams({ifClause:u})}}}};function kk(t,e){let r=t.schema[e];return r!==void 0&&!(0,$k.alwaysValidSchema)(t,r)}Jh.default=oj});var Tk=Z(Yh=>{"use strict";Object.defineProperty(Yh,"__esModule",{value:!0});var sj=xe(),ij={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,sj.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Yh.default=ij});var Ek=Z(Xh=>{"use strict";Object.defineProperty(Xh,"__esModule",{value:!0});var aj=zh(),cj=nk(),lj=Nh(),uj=sk(),dj=ik(),pj=lk(),fj=dk(),hj=qh(),mj=hk(),gj=bk(),yj=wk(),bj=_k(),wj=vk(),_j=xk(),vj=Sk(),xj=Tk();function kj(t=!1){let e=[yj.default,bj.default,wj.default,_j.default,vj.default,xj.default,fj.default,hj.default,pj.default,mj.default,gj.default];return t?e.push(cj.default,uj.default):e.push(aj.default,lj.default),e.push(dj.default),e}Xh.default=kj});var Rk=Z(Qh=>{"use strict";Object.defineProperty(Qh,"__esModule",{value:!0});var Ve=pe(),$j={message:({schemaCode:t})=>(0,Ve.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ve._)`{format: ${t}}`},Sj={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,Ve._)`${f}[${i}]`),v=r.let("fType"),E=r.let("format");r.if((0,Ve._)`typeof ${y} == "object" && !(${y} instanceof RegExp)`,()=>r.assign(v,(0,Ve._)`${y}.type || "string"`).assign(E,(0,Ve._)`${y}.validate`),()=>r.assign(v,(0,Ve._)`"string"`).assign(E,y)),t.fail$data((0,Ve.or)(P(),z()));function P(){return c.strictSchema===!1?Ve.nil:(0,Ve._)`${i} && !${E}`}function z(){let V=u.$async?(0,Ve._)`(${y}.async ? await ${E}(${n}) : ${E}(${n}))`:(0,Ve._)`${E}(${n})`,Y=(0,Ve._)`(typeof ${E} == "function" ? ${V} : ${E}.test(${n}))`;return(0,Ve._)`${E} && ${E} !== true && ${v} === ${e} && !${Y}`}}function m(){let f=d.formats[s];if(!f){P();return}if(f===!0)return;let[y,v,E]=z(f);y===e&&t.pass(V());function P(){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 Ke=Y instanceof RegExp?(0,Ve.regexpCode)(Y):c.code.formats?(0,Ve._)`${c.code.formats}${(0,Ve.getProperty)(s)}`:void 0,et=r.scopeValue("formats",{key:s,ref:Y,code:Ke});return typeof Y=="object"&&!(Y instanceof RegExp)?[Y.type||"string",Y.validate,(0,Ve._)`${et}.validate`]:["string",Y,et]}function V(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Ve._)`await ${E}(${n})`}return typeof v=="function"?(0,Ve._)`${E}(${n})`:(0,Ve._)`${E}.test(${n})`}}}};Qh.default=Sj});var Pk=Z(em=>{"use strict";Object.defineProperty(em,"__esModule",{value:!0});var Tj=Rk(),Ej=[Tj.default];em.default=Ej});var Ak=Z(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});Co.contentVocabulary=Co.metadataVocabulary=void 0;Co.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Co.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Ok=Z(tm=>{"use strict";Object.defineProperty(tm,"__esModule",{value:!0});var Rj=Mx(),Pj=Qx(),Aj=Ek(),Ij=Pk(),Ik=Ak(),Oj=[Rj.default,Pj.default,(0,Aj.default)(),Ij.default,Ik.metadataVocabulary,Ik.contentVocabulary];tm.default=Oj});var zk=Z(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});Ic.DiscrError=void 0;var Ck;(function(t){t.Tag="tag",t.Mapping="mapping"})(Ck||(Ic.DiscrError=Ck={}))});var jk=Z(nm=>{"use strict";Object.defineProperty(nm,"__esModule",{value:!0});var zo=pe(),rm=zk(),Nk=pc(),Cj=ei(),zj=xe(),Nj={message:({params:{discrError:t,tagName:e}})=>t===rm.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,zo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},jj={keyword:"discriminator",type:"object",schemaType:"object",error:Nj,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,zo._)`${r}${(0,zo.getProperty)(a)}`);e.if((0,zo._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:rm.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,zo._)`${l} === ${f}`),e.assign(c,d(m[f]));e.else(),t.error(!1,{discrError:rm.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,zo.Name),f}function b(){var m;let f={},y=E(o),v=!0;for(let V=0;V<i.length;V++){let Y=i[V];if(Y?.$ref&&!(0,zj.schemaHasRulesButRef)(Y,s.self.RULES)){let et=Y.$ref;if(Y=Nk.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,et),Y instanceof Nk.SchemaEnv&&(Y=Y.schema),Y===void 0)throw new Cj.default(s.opts.uriResolver,s.baseId,et)}let Ke=(m=Y?.properties)===null||m===void 0?void 0:m[a];if(typeof Ke!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);v=v&&(y||E(Y)),P(Ke,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 P(V,Y){if(V.const)z(V.const,Y);else if(V.enum)for(let Ke of V.enum)z(Ke,Y);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function z(V,Y){if(typeof V!="string"||V in f)throw new Error(`discriminator: "${a}" values must be unique strings`);f[V]=Y}}}};nm.default=jj});var Lk=Z((i9,Lj)=>{Lj.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 sm=Z((De,om)=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.MissingRefError=De.ValidationError=De.CodeGen=De.Name=De.nil=De.stringify=De.str=De._=De.KeywordCxt=De.Ajv=void 0;var Dj=Cx(),Mj=Ok(),Uj=jk(),Dk=Lk(),Zj=["/properties"],Oc="http://json-schema.org/draft-07/schema",No=class extends Dj.default{_addVocabularies(){super._addVocabularies(),Mj.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Uj.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Dk,Zj):Dk;this.addMetaSchema(e,Oc,!1),this.refs["http://json-schema.org/schema"]=Oc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Oc)?Oc:void 0)}};De.Ajv=No;om.exports=De=No;om.exports.Ajv=No;Object.defineProperty(De,"__esModule",{value:!0});De.default=No;var qj=Qs();Object.defineProperty(De,"KeywordCxt",{enumerable:!0,get:function(){return qj.KeywordCxt}});var jo=pe();Object.defineProperty(De,"_",{enumerable:!0,get:function(){return jo._}});Object.defineProperty(De,"str",{enumerable:!0,get:function(){return jo.str}});Object.defineProperty(De,"stringify",{enumerable:!0,get:function(){return jo.stringify}});Object.defineProperty(De,"nil",{enumerable:!0,get:function(){return jo.nil}});Object.defineProperty(De,"Name",{enumerable:!0,get:function(){return jo.Name}});Object.defineProperty(De,"CodeGen",{enumerable:!0,get:function(){return jo.CodeGen}});var Fj=uc();Object.defineProperty(De,"ValidationError",{enumerable:!0,get:function(){return Fj.default}});var Bj=ei();Object.defineProperty(De,"MissingRefError",{enumerable:!0,get:function(){return Bj.default}})});var Hk=Z(gr=>{"use strict";Object.defineProperty(gr,"__esModule",{value:!0});gr.formatNames=gr.fastFormats=gr.fullFormats=void 0;function mr(t,e){return{validate:t,compare:e}}gr.fullFormats={date:mr(qk,lm),time:mr(am(!0),um),"date-time":mr(Mk(!0),Bk),"iso-time":mr(am(),Fk),"iso-date-time":mr(Mk(),Vk),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Jj,"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:nL,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:Yj,int32:{type:"number",validate:eL},int64:{type:"number",validate:tL},float:{type:"number",validate:Zk},double:{type:"number",validate:Zk},password:!0,binary:!0};gr.fastFormats={...gr.fullFormats,date:mr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,lm),time:mr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,um),"date-time":mr(/^\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,Bk),"iso-time":mr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Fk),"iso-date-time":mr(/^\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,Vk),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};gr.formatNames=Object.keys(gr.fullFormats);function Vj(t){return t%4===0&&(t%100!==0||t%400===0)}var Hj=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Kj=[0,31,28,31,30,31,30,31,31,30,31,30,31];function qk(t){let e=Hj.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&&Vj(r)?29:Kj[n])}function lm(t,e){if(t&&e)return t>e?1:t<e?-1:0}var im=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function am(t){return function(r){let n=im.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 um(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 Fk(t,e){if(!(t&&e))return;let r=im.exec(t),n=im.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 cm=/t|\s/i;function Mk(t){let e=am(t);return function(n){let o=n.split(cm);return o.length===2&&qk(o[0])&&e(o[1])}}function Bk(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function Vk(t,e){if(!(t&&e))return;let[r,n]=t.split(cm),[o,s]=e.split(cm),i=lm(r,o);if(i!==void 0)return i||um(n,s)}var Gj=/\/|:/,Wj=/^(?:[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 Jj(t){return Gj.test(t)&&Wj.test(t)}var Uk=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function Yj(t){return Uk.lastIndex=0,Uk.test(t)}var Xj=-(2**31),Qj=2**31-1;function eL(t){return Number.isInteger(t)&&t<=Qj&&t>=Xj}function tL(t){return Number.isInteger(t)}function Zk(){return!0}var rL=/[^\\]\\Z/;function nL(t){if(rL.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Kk=Z(Lo=>{"use strict";Object.defineProperty(Lo,"__esModule",{value:!0});Lo.formatLimitDefinition=void 0;var oL=sm(),or=pe(),nn=or.operators,Cc={formatMaximum:{okStr:"<=",ok:nn.LTE,fail:nn.GT},formatMinimum:{okStr:">=",ok:nn.GTE,fail:nn.LT},formatExclusiveMaximum:{okStr:"<",ok:nn.LT,fail:nn.GTE},formatExclusiveMinimum:{okStr:">",ok:nn.GT,fail:nn.LTE}},sL={message:({keyword:t,schemaCode:e})=>(0,or.str)`should be ${Cc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,or._)`{comparison: ${Cc[t].okStr}, limit: ${e}}`};Lo.formatLimitDefinition={keyword:Object.keys(Cc),type:"string",schemaType:"string",$data:!0,error:sL,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 oL.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,or._)`${b}[${c.schemaCode}]`);t.fail$data((0,or.or)((0,or._)`typeof ${m} != "object"`,(0,or._)`${m} instanceof RegExp`,(0,or._)`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,or._)`${i.code.formats}${(0,or.getProperty)(b)}`:void 0});t.fail$data(d(f))}function d(b){return(0,or._)`${b}.compare(${r}, ${n}) ${Cc[o].fail} 0`}},dependencies:["format"]};var iL=t=>(t.addKeyword(Lo.formatLimitDefinition),t);Lo.default=iL});var Yk=Z((hi,Jk)=>{"use strict";Object.defineProperty(hi,"__esModule",{value:!0});var Do=Hk(),aL=Kk(),dm=pe(),Gk=new dm.Name("fullFormats"),cL=new dm.Name("fastFormats"),pm=(t,e={keywords:!0})=>{if(Array.isArray(e))return Wk(t,e,Do.fullFormats,Gk),t;let[r,n]=e.mode==="fast"?[Do.fastFormats,cL]:[Do.fullFormats,Gk],o=e.formats||Do.formatNames;return Wk(t,o,r,n),e.keywords&&(0,aL.default)(t),t};pm.get=(t,e="full")=>{let n=(e==="fast"?Do.fastFormats:Do.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Wk(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,dm._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}Jk.exports=hi=pm;Object.defineProperty(hi,"__esModule",{value:!0});hi.default=pm});function lL(){let t=new Xk.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Qk.default)(t),t}var Xk,Qk,zc,e$=O(()=>{Xk=Bc(sm(),1),Qk=Bc(Yk(),1);zc=class{constructor(e){this._ajv=e??lL()}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 Nc,t$=O(()=>{vo();Nc=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},Ds,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},_o,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 r$(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 n$(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 o$=O(()=>{});var jc,s$=O(()=>{cv();vo();e$();Ts();t$();o$();jc=class extends Ya{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ls.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 zc,this.setRequestHandler(Sp,n=>this._oninitialize(n)),this.setNotificationHandler(Tp,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Cp,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Ls.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Nc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=av(this._capabilities,e)}setRequestHandler(e,r){let o=Hr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=mo(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=Vr(wo,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=Vr(yo,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=Vr(Ma,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){n$(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&r$(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:a_.includes(r)?r:_p,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"},ka)}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},zp,r):this.request({method:"sampling/createMessage",params:e},Ds,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},_o,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},_o,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},Np,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 fm(t){return!!t&&typeof t=="object"&&a$ in t}function c$(t){return t[a$]?.complete}var a$,i$,l$=O(()=>{a$=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(i$||(i$={}))});var u$=O(()=>{});function dL(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"),!uL.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 pL(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 hm(t){let e=dL(t);return pL(t,e.warnings),e.isValid}var uL,d$=O(()=>{uL=/^[A-Za-z0-9._-]{1,128}$/});var Lc,p$=O(()=>{Lc=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 m$(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function g$(t){return"_def"in t||"_zod"in t||m$(t)}function mm(t){return typeof t!="object"||t===null||g$(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(m$)}function f$(t){if(t){if(mm(t))return An(t);if(!g$(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function hL(t){let e=Hr(t);return e?Object.entries(e).map(([r,n])=>{let o=Ow(n),s=Cw(n);return{name:r,description:o,required:!s}}):[]}function on(t){let r=Hr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=mo(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function h$(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Dc,fL,mi,y$=O(()=>{s$();Ts();wf();vo();l$();u$();d$();p$();Xn();Dc=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 jc(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Lc(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(on(Da)),this.server.assertCanSetRequestHandler(on(wo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Da,()=>({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=ho(r.inputSchema);return o?gf(o,{strictUnions:!0,pipeStrategy:"input"}):fL})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=ho(r.outputSchema);o&&(n.outputSchema=gf(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(wo,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=ho(e.inputSchema)??e.inputSchema,i=await ga(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=ya(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=ho(e.outputSchema),s=await ga(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=ya(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(on(Ua)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ua,async e=>{switch(e.params.ref.type){case"ref/prompt":return k_(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return $_(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 mi;let s=Hr(n.argsSchema)?.[e.params.argument.name];if(!fm(s))return mi;let i=c$(s);if(!i)return mi;let a=await i(e.params.argument.value,e.params.context);return h$(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 mi;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 mi;let s=await o(e.params.argument.value,e.params.context);return h$(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(on(Ca)),this.server.assertCanSetRequestHandler(on(za)),this.server.assertCanSetRequestHandler(on(Na)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ca,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(za,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Na,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(on(ja)),this.server.assertCanSetRequestHandler(on(La)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ja,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?hL(r.argsSchema):void 0}))})),this.server.setRequestHandler(La,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=ho(n.argsSchema),s=await ga(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",l=ya(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:An(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=An(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 _t?c._def?.innerType:c;return fm(l)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,l){hm(e);let u={title:r,description:n,inputSchema:f$(o),outputSchema:f$(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"&&hm(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=An(d.paramsSchema)),typeof d.outputSchema<"u"&&(u.outputSchema=An(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(mm(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!mm(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()}},fL={type:"object",properties:{}};mi={completion:{values:[],hasMore:!1}}});function gL(t){return m_.parse(JSON.parse(t))}function b$(t){return JSON.stringify(t)+`
1140
- `}var mL,Mc,w$=O(()=>{vo();mL=10*1024*1024,Mc=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??mL}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),gL(r)}clear(){this._buffer=void 0}}});import _$ from"node:process";var Uc,v$=O(()=>{w$();Uc=class{constructor(e=_$.stdin,r=_$.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 Mc({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=b$(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var x$,k$=O(()=>{x$=[]});var O$={};Vo(O$,{AUTHORING_MCP_SERVER_NAME:()=>R$,AUTHORING_MCP_SERVER_VERSION:()=>P$,AUTHORING_RESOURCES:()=>_L,AUTHORING_TOOLS:()=>wL,AUTHORING_TOOLS_PUBLIC:()=>I$,buildAuthoringMcpServer:()=>A$,runAuthoringMcpServer:()=>vL});import{promises as yL}from"node:fs";import{resolve as $$}from"node:path";function E$(){return T$??=import("../mcp/grounding.js").then(e=>e,()=>null),T$}function He(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function bL(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 Jt(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 E$(),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 bL(o,r):null,u=new Dc({name:R$,version:P$},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(`
1284
+ deps: ${r}}`};var dj={keyword:"dependencies",type:"object",schemaType:"object",error:mr.error,code(t){let[e,r]=pj(t);Sk(t,e),Tk(t,r)}};function pj({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 Sk(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,hi.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,hi.checkReportMissingProp)(t,l)}):(r.if((0,Kh._)`${c} && (${(0,hi.checkMissingProp)(t,a,s)})`),(0,hi.reportMissingProp)(t,s),r.else())}}mr.validatePropertyDeps=Sk;function Tk(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,uj.alwaysValidSchema)(s,e[a])||(r.if((0,hi.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))}mr.validateSchemaDeps=Tk;mr.default=dj});var Pk=Z(Gh=>{"use strict";Object.defineProperty(Gh,"__esModule",{value:!0});var Rk=fe(),fj=xe(),hj={message:"property name must be valid",params:({params:t})=>(0,Rk._)`{propertyName: ${t.propertyName}}`},mj={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:hj,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,fj.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,Rk.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Gh.default=mj});var Jh=Z(Wh=>{"use strict";Object.defineProperty(Wh,"__esModule",{value:!0});var Ic=Ht(),sr=fe(),gj=Ar(),Oc=xe(),yj={message:"must NOT have additional properties",params:({params:t})=>(0,sr._)`{additionalProperty: ${t.additionalProperty}}`},bj={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:yj,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,Oc.alwaysValidSchema)(i,r))return;let l=(0,Ic.allSchemaProperties)(n.properties),u=(0,Ic.allSchemaProperties)(n.patternProperties);d(),t.ok((0,sr._)`${s} === ${gj.default.errors}`);function d(){e.forIn("key",o,k=>{!l.length&&!u.length?f(k):e.if(w(k),()=>f(k))})}function w(k){let E;if(l.length>8){let P=(0,Oc.schemaRefOrVal)(i,n.properties,"properties");E=(0,Ic.isOwnProperty)(e,P,k)}else l.length?E=(0,sr.or)(...l.map(P=>(0,sr._)`${k} === ${P}`)):E=sr.nil;return u.length&&(E=(0,sr.or)(E,...u.map(P=>(0,sr._)`${(0,Ic.usePattern)(t,P)}.test(${k})`))),(0,sr.not)(E)}function m(k){e.code((0,sr._)`delete ${o}[${k}]`)}function f(k){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){m(k);return}if(r===!1){t.setParams({additionalProperty:k}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Oc.alwaysValidSchema)(i,r)){let E=e.name("valid");c.removeAdditional==="failing"?(b(k,E,!1),e.if((0,sr.not)(E),()=>{t.reset(),m(k)})):(b(k,E),a||e.if((0,sr.not)(E),()=>e.break()))}}function b(k,E,P){let z={keyword:"additionalProperties",dataProp:k,dataPropType:Oc.Type.Str};P===!1&&Object.assign(z,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(z,E)}}};Wh.default=bj});var Ok=Z(Xh=>{"use strict";Object.defineProperty(Xh,"__esModule",{value:!0});var wj=ei(),Ak=Ht(),Yh=xe(),Ik=Jh(),_j={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&&Ik.default.code(new wj.KeywordCxt(s,Ik.default,"additionalProperties"));let i=(0,Ak.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Yh.mergeEvaluated.props(e,(0,Yh.toHash)(i),s.props));let a=i.filter(d=>!(0,Yh.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,Ak.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)}}};Xh.default=_j});var jk=Z(Qh=>{"use strict";Object.defineProperty(Qh,"__esModule",{value:!0});var Ck=Ht(),Cc=fe(),zk=xe(),Nk=xe(),vj={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,Ck.allSchemaProperties)(r),c=a.filter(b=>(0,zk.alwaysValidSchema)(s,r[b]));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 Cc.Name)&&(s.props=(0,Nk.evaluatedPropsToName)(e,s.props));let{props:d}=s;w();function w(){for(let b of a)l&&m(b),s.allErrors?f(b):(e.var(u,!0),f(b),e.if(u))}function m(b){for(let k in l)new RegExp(b).test(k)&&(0,zk.checkStrictMode)(s,`property ${k} matches pattern ${b} (use allowMatchingProperties)`)}function f(b){e.forIn("key",n,k=>{e.if((0,Cc._)`${(0,Ck.usePattern)(t,b)}.test(${k})`,()=>{let E=c.includes(b);E||t.subschema({keyword:"patternProperties",schemaProp:b,dataProp:k,dataPropType:Nk.Type.Str},u),s.opts.unevaluated&&d!==!0?e.assign((0,Cc._)`${d}[${k}]`,!0):!E&&!s.allErrors&&e.if((0,Cc.not)(u),()=>e.break())})})}}};Qh.default=vj});var Lk=Z(em=>{"use strict";Object.defineProperty(em,"__esModule",{value:!0});var xj=xe(),kj={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,xj.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"}};em.default=kj});var Dk=Z(tm=>{"use strict";Object.defineProperty(tm,"__esModule",{value:!0});var $j=Ht(),Sj={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:$j.validateUnion,error:{message:"must match a schema in anyOf"}};tm.default=Sj});var Mk=Z(rm=>{"use strict";Object.defineProperty(rm,"__esModule",{value:!0});var zc=fe(),Tj=xe(),Ej={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,zc._)`{passingSchemas: ${t.passing}}`},Rj={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Ej,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 w;(0,Tj.alwaysValidSchema)(o,u)?e.var(c,!0):w=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,zc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,zc._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),w&&t.mergeEvaluated(w,zc.Name)})})}}};rm.default=Rj});var Uk=Z(nm=>{"use strict";Object.defineProperty(nm,"__esModule",{value:!0});var Pj=xe(),Aj={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,Pj.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};nm.default=Aj});var Fk=Z(om=>{"use strict";Object.defineProperty(om,"__esModule",{value:!0});var Nc=fe(),qk=xe(),Ij={message:({params:t})=>(0,Nc.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Nc._)`{failingKeyword: ${t.ifClause}}`},Oj={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Ij,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,qk.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Zk(n,"then"),s=Zk(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,Nc.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 w=t.subschema({keyword:u},a);e.assign(i,a),t.mergeValidEvaluated(w,i),d?e.assign(d,(0,Nc._)`${u}`):t.setParams({ifClause:u})}}}};function Zk(t,e){let r=t.schema[e];return r!==void 0&&!(0,qk.alwaysValidSchema)(t,r)}om.default=Oj});var Bk=Z(sm=>{"use strict";Object.defineProperty(sm,"__esModule",{value:!0});var Cj=xe(),zj={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,Cj.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};sm.default=zj});var Vk=Z(im=>{"use strict";Object.defineProperty(im,"__esModule",{value:!0});var Nj=qh(),jj=vk(),Lj=Fh(),Dj=kk(),Mj=$k(),Uj=Ek(),Zj=Pk(),qj=Jh(),Fj=Ok(),Bj=jk(),Vj=Lk(),Hj=Dk(),Kj=Mk(),Gj=Uk(),Wj=Fk(),Jj=Bk();function Yj(t=!1){let e=[Vj.default,Hj.default,Kj.default,Gj.default,Wj.default,Jj.default,Zj.default,qj.default,Uj.default,Fj.default,Bj.default];return t?e.push(jj.default,Dj.default):e.push(Nj.default,Lj.default),e.push(Mj.default),e}im.default=Yj});var Hk=Z(am=>{"use strict";Object.defineProperty(am,"__esModule",{value:!0});var He=fe(),Xj={message:({schemaCode:t})=>(0,He.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,He._)`{format: ${t}}`},Qj={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Xj,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?w():m();function w(){let f=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),b=r.const("fDef",(0,He._)`${f}[${i}]`),k=r.let("fType"),E=r.let("format");r.if((0,He._)`typeof ${b} == "object" && !(${b} instanceof RegExp)`,()=>r.assign(k,(0,He._)`${b}.type || "string"`).assign(E,(0,He._)`${b}.validate`),()=>r.assign(k,(0,He._)`"string"`).assign(E,b)),t.fail$data((0,He.or)(P(),z()));function P(){return c.strictSchema===!1?He.nil:(0,He._)`${i} && !${E}`}function z(){let H=u.$async?(0,He._)`(${b}.async ? await ${E}(${n}) : ${E}(${n}))`:(0,He._)`${E}(${n})`,Y=(0,He._)`(typeof ${E} == "function" ? ${H} : ${E}.test(${n}))`;return(0,He._)`${E} && ${E} !== true && ${k} === ${e} && !${Y}`}}function m(){let f=d.formats[s];if(!f){P();return}if(f===!0)return;let[b,k,E]=z(f);b===e&&t.pass(H());function P(){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 Ge=Y instanceof RegExp?(0,He.regexpCode)(Y):c.code.formats?(0,He._)`${c.code.formats}${(0,He.getProperty)(s)}`:void 0,tt=r.scopeValue("formats",{key:s,ref:Y,code:Ge});return typeof Y=="object"&&!(Y instanceof RegExp)?[Y.type||"string",Y.validate,(0,He._)`${tt}.validate`]:["string",Y,tt]}function H(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!u.$async)throw new Error("async format in sync schema");return(0,He._)`await ${E}(${n})`}return typeof k=="function"?(0,He._)`${E}(${n})`:(0,He._)`${E}.test(${n})`}}}};am.default=Qj});var Kk=Z(cm=>{"use strict";Object.defineProperty(cm,"__esModule",{value:!0});var eL=Hk(),tL=[eL.default];cm.default=tL});var Gk=Z(zo=>{"use strict";Object.defineProperty(zo,"__esModule",{value:!0});zo.contentVocabulary=zo.metadataVocabulary=void 0;zo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];zo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Jk=Z(lm=>{"use strict";Object.defineProperty(lm,"__esModule",{value:!0});var rL=nk(),nL=yk(),oL=Vk(),sL=Kk(),Wk=Gk(),iL=[rL.default,nL.default,(0,oL.default)(),sL.default,Wk.metadataVocabulary,Wk.contentVocabulary];lm.default=iL});var Xk=Z(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});jc.DiscrError=void 0;var Yk;(function(t){t.Tag="tag",t.Mapping="mapping"})(Yk||(jc.DiscrError=Yk={}))});var e$=Z(dm=>{"use strict";Object.defineProperty(dm,"__esModule",{value:!0});var No=fe(),um=Xk(),Qk=yc(),aL=ti(),cL=xe(),lL={message:({params:{discrError:t,tagName:e}})=>t===um.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,No._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},uL={keyword:"discriminator",type:"object",schemaType:"object",error:lL,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,No._)`${r}${(0,No.getProperty)(a)}`);e.if((0,No._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:um.DiscrError.Tag,tag:l,tagName:a})),t.ok(c);function u(){let m=w();e.if(!1);for(let f in m)e.elseIf((0,No._)`${l} === ${f}`),e.assign(c,d(m[f]));e.else(),t.error(!1,{discrError:um.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function d(m){let f=e.name("valid"),b=t.subschema({keyword:"oneOf",schemaProp:m},f);return t.mergeEvaluated(b,No.Name),f}function w(){var m;let f={},b=E(o),k=!0;for(let H=0;H<i.length;H++){let Y=i[H];if(Y?.$ref&&!(0,cL.schemaHasRulesButRef)(Y,s.self.RULES)){let tt=Y.$ref;if(Y=Qk.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,tt),Y instanceof Qk.SchemaEnv&&(Y=Y.schema),Y===void 0)throw new aL.default(s.opts.uriResolver,s.baseId,tt)}let Ge=(m=Y?.properties)===null||m===void 0?void 0:m[a];if(typeof Ge!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);k=k&&(b||E(Y)),P(Ge,H)}if(!k)throw new Error(`discriminator: "${a}" must be required`);return f;function E({required:H}){return Array.isArray(H)&&H.includes(a)}function P(H,Y){if(H.const)z(H.const,Y);else if(H.enum)for(let Ge of H.enum)z(Ge,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}}}};dm.default=uL});var t$=Z((M9,dL)=>{dL.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 fm=Z((De,pm)=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.MissingRefError=De.ValidationError=De.CodeGen=De.Name=De.nil=De.stringify=De.str=De._=De.KeywordCxt=De.Ajv=void 0;var pL=Yx(),fL=Jk(),hL=e$(),r$=t$(),mL=["/properties"],Lc="http://json-schema.org/draft-07/schema",jo=class extends pL.default{_addVocabularies(){super._addVocabularies(),fL.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(hL.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(r$,mL):r$;this.addMetaSchema(e,Lc,!1),this.refs["http://json-schema.org/schema"]=Lc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Lc)?Lc:void 0)}};De.Ajv=jo;pm.exports=De=jo;pm.exports.Ajv=jo;Object.defineProperty(De,"__esModule",{value:!0});De.default=jo;var gL=ei();Object.defineProperty(De,"KeywordCxt",{enumerable:!0,get:function(){return gL.KeywordCxt}});var Lo=fe();Object.defineProperty(De,"_",{enumerable:!0,get:function(){return Lo._}});Object.defineProperty(De,"str",{enumerable:!0,get:function(){return Lo.str}});Object.defineProperty(De,"stringify",{enumerable:!0,get:function(){return Lo.stringify}});Object.defineProperty(De,"nil",{enumerable:!0,get:function(){return Lo.nil}});Object.defineProperty(De,"Name",{enumerable:!0,get:function(){return Lo.Name}});Object.defineProperty(De,"CodeGen",{enumerable:!0,get:function(){return Lo.CodeGen}});var yL=mc();Object.defineProperty(De,"ValidationError",{enumerable:!0,get:function(){return yL.default}});var bL=ti();Object.defineProperty(De,"MissingRefError",{enumerable:!0,get:function(){return bL.default}})});var u$=Z(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.formatNames=yr.fastFormats=yr.fullFormats=void 0;function gr(t,e){return{validate:t,compare:e}}yr.fullFormats={date:gr(i$,ym),time:gr(mm(!0),bm),"date-time":gr(n$(!0),c$),"iso-time":gr(mm(),a$),"iso-date-time":gr(n$(),l$),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:$L,"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:IL,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:SL,int32:{type:"number",validate:RL},int64:{type:"number",validate:PL},float:{type:"number",validate:s$},double:{type:"number",validate:s$},password:!0,binary:!0};yr.fastFormats={...yr.fullFormats,date:gr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,ym),time:gr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,bm),"date-time":gr(/^\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,c$),"iso-time":gr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,a$),"iso-date-time":gr(/^\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,l$),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};yr.formatNames=Object.keys(yr.fullFormats);function wL(t){return t%4===0&&(t%100!==0||t%400===0)}var _L=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,vL=[0,31,28,31,30,31,30,31,31,30,31,30,31];function i$(t){let e=_L.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&&wL(r)?29:vL[n])}function ym(t,e){if(t&&e)return t>e?1:t<e?-1:0}var hm=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function mm(t){return function(r){let n=hm.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,w=o-l*c-(d<0?1:0);return(w===23||w===-1)&&(d===59||d===-1)&&i<61}}function bm(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 a$(t,e){if(!(t&&e))return;let r=hm.exec(t),n=hm.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 gm=/t|\s/i;function n$(t){let e=mm(t);return function(n){let o=n.split(gm);return o.length===2&&i$(o[0])&&e(o[1])}}function c$(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function l$(t,e){if(!(t&&e))return;let[r,n]=t.split(gm),[o,s]=e.split(gm),i=ym(r,o);if(i!==void 0)return i||bm(n,s)}var xL=/\/|:/,kL=/^(?:[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 $L(t){return xL.test(t)&&kL.test(t)}var o$=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function SL(t){return o$.lastIndex=0,o$.test(t)}var TL=-(2**31),EL=2**31-1;function RL(t){return Number.isInteger(t)&&t<=EL&&t>=TL}function PL(t){return Number.isInteger(t)}function s$(){return!0}var AL=/[^\\]\\Z/;function IL(t){if(AL.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var d$=Z(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.formatLimitDefinition=void 0;var OL=fm(),ir=fe(),sn=ir.operators,Dc={formatMaximum:{okStr:"<=",ok:sn.LTE,fail:sn.GT},formatMinimum:{okStr:">=",ok:sn.GTE,fail:sn.LT},formatExclusiveMaximum:{okStr:"<",ok:sn.LT,fail:sn.GTE},formatExclusiveMinimum:{okStr:">",ok:sn.GT,fail:sn.LTE}},CL={message:({keyword:t,schemaCode:e})=>(0,ir.str)`should be ${Dc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ir._)`{comparison: ${Dc[t].okStr}, limit: ${e}}`};Do.formatLimitDefinition={keyword:Object.keys(Dc),type:"string",schemaType:"string",$data:!0,error:CL,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 OL.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let w=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),m=e.const("fmt",(0,ir._)`${w}[${c.schemaCode}]`);t.fail$data((0,ir.or)((0,ir._)`typeof ${m} != "object"`,(0,ir._)`${m} instanceof RegExp`,(0,ir._)`typeof ${m}.compare != "function"`,d(m)))}function u(){let w=c.schema,m=a.formats[w];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw new Error(`"${o}": format "${w}" does not define "compare" function`);let f=e.scopeValue("formats",{key:w,ref:m,code:i.code.formats?(0,ir._)`${i.code.formats}${(0,ir.getProperty)(w)}`:void 0});t.fail$data(d(f))}function d(w){return(0,ir._)`${w}.compare(${r}, ${n}) ${Dc[o].fail} 0`}},dependencies:["format"]};var zL=t=>(t.addKeyword(Do.formatLimitDefinition),t);Do.default=zL});var m$=Z((mi,h$)=>{"use strict";Object.defineProperty(mi,"__esModule",{value:!0});var Mo=u$(),NL=d$(),wm=fe(),p$=new wm.Name("fullFormats"),jL=new wm.Name("fastFormats"),_m=(t,e={keywords:!0})=>{if(Array.isArray(e))return f$(t,e,Mo.fullFormats,p$),t;let[r,n]=e.mode==="fast"?[Mo.fastFormats,jL]:[Mo.fullFormats,p$],o=e.formats||Mo.formatNames;return f$(t,o,r,n),e.keywords&&(0,NL.default)(t),t};_m.get=(t,e="full")=>{let n=(e==="fast"?Mo.fastFormats:Mo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function f$(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,wm._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}h$.exports=mi=_m;Object.defineProperty(mi,"__esModule",{value:!0});mi.default=_m});function LL(){let t=new g$.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,y$.default)(t),t}var g$,y$,Mc,b$=O(()=>{g$=Yc(fm(),1),y$=Yc(m$(),1);Mc=class{constructor(e){this._ajv=e??LL()}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 Uc,w$=O(()=>{xo();Uc=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(w=>w.type==="tool_use").map(w=>w.id)),d=new Set(s.filter(w=>w.type==="tool_result").map(w=>w.toolUseId));if(u.size!==d.size||![...u].every(w=>d.has(w)))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},Ms,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},vo,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 _$(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 v$(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 x$=O(()=>{});var Zc,k$=O(()=>{Tv();xo();b$();Es();w$();x$();Zc=class extends rc{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ds.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 Mc,this.setRequestHandler(Cp,n=>this._oninitialize(n)),this.setNotificationHandler(zp,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Zp,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Ds.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Uc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Sv(this._capabilities,e)}setRequestHandler(e,r){let o=Gr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=go(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=Kr(_o,c);if(!u.success){let f=u.error instanceof Error?u.error.message:String(u.error);throw new G(Q.InvalidParams,`Invalid tools/call request: ${f}`)}let{params:d}=u.data,w=await Promise.resolve(r(c,l));if(d.task){let f=Kr(bo,w);if(!f.success){let b=f.error instanceof Error?f.error.message:String(f.error);throw new G(Q.InvalidParams,`Invalid task creation result: ${b}`)}return f.data}let m=Kr(Ba,w);if(!m.success){let f=m.error instanceof Error?m.error.message:String(m.error);throw new G(Q.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){v$(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&_$(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:S_.includes(r)?r:Rp,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"},Ra)}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},qp,r):this.request({method:"sampling/createMessage",params:e},Ms,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},vo,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},vo,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(Q.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof G?i:new G(Q.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},Fp,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 vm(t){return!!t&&typeof t=="object"&&S$ in t}function T$(t){return t[S$]?.complete}var S$,$$,E$=O(()=>{S$=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})($$||($$={}))});var R$=O(()=>{});function ML(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"),!DL.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 UL(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 xm(t){let e=ML(t);return UL(t,e.warnings),e.isValid}var DL,P$=O(()=>{DL=/^[A-Za-z0-9._-]{1,128}$/});var qc,A$=O(()=>{qc=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 C$(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function z$(t){return"_def"in t||"_zod"in t||C$(t)}function km(t){return typeof t!="object"||t===null||z$(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(C$)}function I$(t){if(t){if(km(t))return On(t);if(!z$(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function qL(t){let e=Gr(t);return e?Object.entries(e).map(([r,n])=>{let o=Jw(n),s=Yw(n);return{name:r,description:o,required:!s}}):[]}function an(t){let r=Gr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=go(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function O$(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Fc,ZL,gi,N$=O(()=>{k$();Es();Ef();xo();E$();R$();P$();A$();Qn();Fc=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 Zc(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new qc(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(an(Fa)),this.server.assertCanSetRequestHandler(an(_o)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Fa,()=>({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=mo(r.inputSchema);return o?$f(o,{strictUnions:!0,pipeStrategy:"input"}):ZL})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=mo(r.outputSchema);o&&(n.outputSchema=$f(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(_o,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new G(Q.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new G(Q.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(Q.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new G(Q.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===Q.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=mo(e.inputSchema)??e.inputSchema,i=await va(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=xa(a);throw new G(Q.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(Q.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=mo(e.outputSchema),s=await va(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=xa(i);throw new G(Q.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(w=>setTimeout(w,u));let d=await n.taskStore.getTask(c);if(!d)throw new G(Q.InternalError,`Task ${c} not found during polling`);l=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(an(Va)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Va,async e=>{switch(e.params.ref.type){case"ref/prompt":return Z_(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return q_(e),this.handleResourceCompletion(e,e.params.ref);default:throw new G(Q.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(Q.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new G(Q.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return gi;let s=Gr(n.argsSchema)?.[e.params.argument.name];if(!vm(s))return gi;let i=T$(s);if(!i)return gi;let a=await i(e.params.argument.value,e.params.context);return O$(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 gi;throw new G(Q.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return gi;let s=await o(e.params.argument.value,e.params.context);return O$(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(an(Da)),this.server.assertCanSetRequestHandler(an(Ma)),this.server.assertCanSetRequestHandler(an(Ua)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Da,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(Ma,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Ua,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new G(Q.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(Q.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(an(Za)),this.server.assertCanSetRequestHandler(an(qa)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Za,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?qL(r.argsSchema):void 0}))})),this.server.setRequestHandler(qa,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new G(Q.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new G(Q.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=mo(n.argsSchema),s=await va(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",l=xa(c);throw new G(Q.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:On(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=On(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 xt?c._def?.innerType:c;return vm(l)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,l){xm(e);let u={title:r,description:n,inputSchema:I$(o),outputSchema:I$(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"&&xm(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=On(d.paramsSchema)),typeof d.outputSchema<"u"&&(u.outputSchema=On(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(km(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!km(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()}},ZL={type:"object",properties:{}};gi={completion:{values:[],hasMore:!1}}});function BL(t){return C_.parse(JSON.parse(t))}function j$(t){return JSON.stringify(t)+`
1285
+ `}var FL,Bc,L$=O(()=>{xo();FL=10*1024*1024,Bc=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??FL}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(`
1286
+ `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),BL(r)}clear(){this._buffer=void 0}}});import D$ from"node:process";var Vc,M$=O(()=>{L$();Vc=class{constructor(e=D$.stdin,r=D$.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 Bc({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=j$(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var U$,Z$=O(()=>{U$=[]});var J$={};Ho(J$,{AUTHORING_MCP_SERVER_NAME:()=>H$,AUTHORING_MCP_SERVER_VERSION:()=>K$,AUTHORING_RESOURCES:()=>GL,AUTHORING_TOOLS:()=>KL,AUTHORING_TOOLS_PUBLIC:()=>W$,buildAuthoringMcpServer:()=>G$,runAuthoringMcpServer:()=>WL});import{promises as VL}from"node:fs";import{resolve as q$}from"node:path";function V$(){return B$??=import("../mcp/grounding.js").then(e=>e,()=>null),B$}function Ke(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 G$(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let m=await Yt(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 V$(),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 Fc({name:H$,version:K$},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 b=await n.getMcpPromptSkill(m,f.id,r);if(!b)throw new Error(`unknown prompt: ${f.id}`);return{description:b.description,messages:[{role:"user",content:{type:"text",text:(b.prompts??[]).join(`
1142
1287
 
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 He(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)}`:"",P=await fetch(`${y}/v1/catalog/records/${encodeURIComponent(m)}${E}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown record type "${m}" \u2014 list them with catalog_get.`);if(!P.ok)throw new Error(`record anatomy fetch failed: ${P.status}`);return He(await P.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 P=await fetch(`${y}/v1/catalog/columns?${E}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});if(P.status===404)throw new Error(`none of those record types resolved: ${m.join(", ")} \u2014 list them with catalog_get.`);if(!P.ok)throw new Error(`common columns fetch failed: ${P.status}`);return He(await P.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 He(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(S$).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(),P=new URLSearchParams({q:m});f&&P.set("kind",f),y!==void 0&&P.set("limit",String(y));let z=await fetch(`${v}/v1/catalog/objects?${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(!z.ok)throw new Error(`catalog object search failed: ${z.status}`);return He(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(S$),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 He(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 P=await fetch(`${y}/v1/kb/search?${E}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});if(!P.ok)throw new Error(`kb search failed: ${P.status}`);return He(await P.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 He(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 Lr({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=no("hook",{recordType:m.recordType,event:m.event,template:m.template,field:m.field,regex:m.regex,source:m.source,id:m.id});return He({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=no("conduit",{recordType:m.recordType,source:m.source,to:m.to,toRecordType:m.toRecordType,event:m.event,id:m.id});return He({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=$$(process.cwd(),f??"samples"),v=await rs(y),E=await Mi(m,v.map(z=>z.fixture)),P=E.filter(z=>!z.pass).length;return He({total:E.length,passed:E.length-P,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 He(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 He({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 He(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(),P=new Q({baseUrl:v,token:E});return He(await P.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 He(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(),P=new Q({baseUrl:v,token:E});return He(await P.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 He(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 He(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 He(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 Lr({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=$$(process.cwd(),"samples"),y=[];try{y=(await yL.readdir(f)).filter(E=>E.endsWith(".json"))}catch{y=[]}let v=await rs(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 E$(),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 vL(t={}){let e=await A$(t),r=new Uc;await e.connect(r)}var S$,T$,R$,P$,I$,wL,_L,C$=O(()=>{y$();v$();Xn();xl();Qo();Dr();Il();Dl();k$();S$=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];R$="turbobase-authoring",P$="0.1.0";I$=["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"],wL=[...I$,...x$],_L=["catalog:///","types://all","samples:///","recipes:///"]});import{spawn as vm}from"node:child_process";import{promises as ye}from"node:fs";import{homedir as xL}from"node:os";import{basename as N$,dirname as Mo,join as Ct,relative as Zc,resolve as $e,sep as _m}from"node:path";var Um=Bc(Mm(),1),{program:BL,createCommand:VL,createArgument:HL,createOption:KL,CommanderError:GL,InvalidArgumentError:WL,InvalidOptionArgumentError:JL,Command:Zm,Argument:YL,Option:XL,Help:QL}=Um.default;xl();Qo();Dr();Il();Pl();import{promises as $g}from"node:fs";function xg(t,e){return e===t?"same-type-merge":"different-type-mint"}var Sg=4;function Ol(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=eo(t,"id"),r=eo(t,"on"),n=eo(t,"source"),o=eo(t,"recordType"),s=/to\s*:\s*\{([^}]*)\}/.exec(t)?.[1]??"",i=eo(s,"source"),a=eo(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]):Sg}}function eo(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function qT(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 Tg(t,e,r="fixture"){let n=e.name??r,o=[],s;try{s=Ol(t)}catch(c){return{fixtureName:n,conduit:BT(),guards:o,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],logs:[],error:c instanceof Error?c.message:String(c)}}let i=qT(e),a=Object.entries(e.atlasLinks??{}).map(([c,l])=>({key:c,resolved:l}));try{let c=await Di(t),u=!!(await ts(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 ts(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=xg(s.fromRecordType,s.toRecordType),{wouldWriteBindings:E,masterAction:P}=FT(s,v,e);return{fixtureName:n,conduit:s,guards:o,whenPassed:u,atlasResolutions:a,transformResult:y,applyBranch:v,wouldWriteBindings:E,masterAction:P,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 FT(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 BT(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",cycleBudget:Sg}}async function Eg(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 Rg(t){let e=await $g.readFile(t,"utf8");return JSON.parse(e)}function Pg(t){return $g.readFile(t,"utf8")}function Ag(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(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(`
1145
- `)}function VT(t,e){return t.split(`
1288
+ `)}}]}})}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(),b=await fetch(`${m}/v1/catalog/records`,{headers:{Authorization:`Bearer ${f}`,Accept:"application/json"}});if(!b.ok)throw new Error(`catalog fetch failed: ${b.status}`);return Ke(await b.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:b,token:k}=await e(),E=f?`?source=${encodeURIComponent(f)}`:"",P=await fetch(`${b}/v1/catalog/records/${encodeURIComponent(m)}${E}`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown record type "${m}" \u2014 list them with catalog_get.`);if(!P.ok)throw new Error(`record anatomy fetch failed: ${P.status}`);return Ke(await P.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:b,token:k}=await e(),E=new URLSearchParams({types:m.join(",")});f&&E.set("source",f);let P=await fetch(`${b}/v1/catalog/columns?${E}`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}});if(P.status===404)throw new Error(`none of those record types resolved: ${m.join(", ")} \u2014 list them with catalog_get.`);if(!P.ok)throw new Error(`common columns fetch failed: ${P.status}`);return Ke(await P.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(),b=await fetch(`${m}/v1/catalog/census`,{headers:{Authorization:`Bearer ${f}`,Accept:"application/json"}});if(!b.ok)throw new Error(`catalog census failed: ${b.status}`);return Ke(await b.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(F$).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:b})=>{let{baseUrl:k,token:E}=await e(),P=new URLSearchParams({q:m});f&&P.set("kind",f),b!==void 0&&P.set("limit",String(b));let z=await fetch(`${k}/v1/catalog/objects?${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(!z.ok)throw new Error(`catalog object search failed: ${z.status}`);return Ke(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(F$),externalId:N.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:m,externalId:f})=>{let{baseUrl:b,token:k}=await e(),E=await fetch(`${b}/v1/catalog/objects/${encodeURIComponent(m)}/${encodeURIComponent(f)}`,{headers:{Authorization:`Bearer ${k}`,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 Ke(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:b,token:k}=await e(),E=new URLSearchParams({q:m});f!==void 0&&E.set("limit",String(f));let P=await fetch(`${b}/v1/kb/search?${E}`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}});if(!P.ok)throw new Error(`kb search failed: ${P.status}`);return Ke(await P.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:b}=await e(),k=await fetch(`${f}/v1/kb/document/${encodeURIComponent(m)}`,{headers:{Authorization:`Bearer ${b}`,Accept:"application/json"}});if(!k.ok&&k.status!==404)throw new Error(`kb document fetch failed: ${k.status}`);return Ke(await k.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:b}=await e();return{content:[{type:"text",text:await Ur({baseUrl:f,token:b,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=Br("hook",{recordType:m.recordType,event:m.event,template:m.template,field:m.field,regex:m.regex,source:m.source,id:m.id});return Ke({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=Br("conduit",{recordType:m.recordType,source:m.source,to:m.to,toRecordType:m.toRecordType,event:m.event,id:m.id});return Ke({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 b=q$(process.cwd(),f??"samples"),k=await ns(b),E=await Zi(m,k.map(z=>z.fixture)),P=E.filter(z=>!z.pass).length;return Ke({total:E.length,passed:E.length-P,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:b}=await e(),E=await new X({baseUrl:f,token:b}).deploy({id:m.id,recordType:m.recordType,event:m.event,source:m.source,sourceCode:m.sourceCode,extensionKind:m.extensionKind});return Ke(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:b,token:k}=await e(),E=new X({baseUrl:b,token:k});return Ke({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(),b=new X({baseUrl:m,token:f});return Ke(await b.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:b})=>{let{baseUrl:k,token:E}=await e(),P=new X({baseUrl:k,token:E});return Ke(await P.appsCreate({slug:m,name:f,description:b}))}),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:b}=await e(),k=new X({baseUrl:f,token:b});return Ke(await k.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:b})=>{let{baseUrl:k,token:E}=await e(),P=new X({baseUrl:k,token:E});return Ke(await P.appsPush(m,f,{note:b}))});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()}),w=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(),b=new X({baseUrl:m,token:f});return Ke(await b.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(w),claimedBy:N.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:m,claimedBy:f})=>{let{baseUrl:b,token:k}=await e(),E=new X({baseUrl:b,token:k});return Ke(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(w),claimedBy:N.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:m,claimedBy:f})=>{let{baseUrl:b,token:k}=await e(),E=new X({baseUrl:b,token:k});return Ke(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:b}=await e(),E=await(await fetch(`${f}/v1/catalog/records`,{headers:{Authorization:`Bearer ${b}`,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:b}=await e(),k=await Ur({baseUrl:f,token:b});return{contents:[{uri:m.href,mimeType:"text/plain",text:k}]}}),u.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async m=>{let f=q$(process.cwd(),"samples"),b=[];try{b=(await VL.readdir(f)).filter(E=>E.endsWith(".json"))}catch{b=[]}let k=await ns(f);return{contents:[{uri:m.href,mimeType:"application/json",text:JSON.stringify({files:b,samples:k.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 V$(),b=[];if(f){let{baseUrl:k,token:E}=await e();b=await f.listRecipesForSurface({surface:"mcp-authoring",baseUrl:k,token:E},r)}return{contents:[{uri:m.href,mimeType:"application/json",text:JSON.stringify({recipes:b})}]}}),u}async function WL(t={}){let e=await G$(t),r=new Vc;await e.connect(r)}var F$,B$,H$,K$,W$,KL,GL,Y$=O(()=>{N$();M$();Qn();Pl();es();$r();Dl();Vi();Z$();F$=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];H$="turbobase-authoring",K$="0.1.0";W$=["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"],KL=[...W$,...U$],GL=["catalog:///","types://all","samples:///","recipes:///"]});import{spawn as Pm}from"node:child_process";import{promises as ye}from"node:fs";import{homedir as JL}from"node:os";import{basename as Q$,dirname as Uo,join as zt,relative as Kc,resolve as $e,sep as Rm}from"node:path";var Gm=Yc(Km(),1),{program:bD,createCommand:wD,createArgument:_D,createOption:vD,CommanderError:xD,InvalidArgumentError:kD,InvalidOptionArgumentError:$D,Command:Wm,Argument:SD,Option:TD,Help:ED}=Gm.default;Pl();es();$r();Dl();jl();import{promises as Og}from"node:fs";function Ag(t,e){return e===t?"same-type-merge":"different-type-mint"}var Cg=4;function Ml(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=to(t,"id"),r=to(t,"on"),n=to(t,"source"),o=to(t,"recordType"),s=/to\s*:\s*\{([^}]*)\}/.exec(t)?.[1]??"",i=to(s,"source"),a=to(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]):Cg}}function to(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function i0(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 zg(t,e,r="fixture"){let n=e.name??r,o=[],s;try{s=Ml(t)}catch(c){return{fixtureName:n,conduit:c0(),guards:o,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],logs:[],error:c instanceof Error?c.message:String(c)}}let i=i0(e),a=Object.entries(e.atlasLinks??{}).map(([c,l])=>({key:c,resolved:l}));try{let c=await Ui(t),u=!!(await rs(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 w=await rs(c,i,{member:"transform",timeoutMs:200}),m=w.effects.logs,f=w.effects.result;if(!f||typeof f!="object")throw new Error(`conduit ${s.id} transform returned no result (expected { patch, createdFrom? })`);let b=f,k=Ag(s.fromRecordType,s.toRecordType),{wouldWriteBindings:E,masterAction:P}=a0(s,k,e);return{fixtureName:n,conduit:s,guards:o,whenPassed:u,atlasResolutions:a,transformResult:b,applyBranch:k,wouldWriteBindings:E,masterAction:P,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 a0(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 c0(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",cycleBudget:Cg}}async function Ng(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 jg(t){let e=await Og.readFile(t,"utf8");return JSON.parse(e)}function Lg(t){return Og.readFile(t,"utf8")}function Dg(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(`
1289
+ `);if(n.push(""),n.push("transform \u2192 patch:"),n.push(l0(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(`
1290
+ `)}function l0(t,e){return t.split(`
1146
1291
  `).map(r=>e+r).join(`
1147
- `)}var HT="2026-01-01",Ig="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"?HT:r.startsWith("timestamp")?Ig: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:Ig}:{}:r==="uuid"?"00000000-0000-0000-0000-000000000000":r==="array"||r.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function GT(t){let e={};for(let r of t.columns)e[r.name]=KT(r.pgType,r.name);return e}function WT(t,e={}){let r=e.event??"before_save";return{name:`${t.recordType} ${r} (generated)`,context:{recordType:t.recordType,event:r,source:t.source,payload:GT(t)},expect:e.expect??"pass"}}function Og(t,e={}){return t.map(r=>({recordType:r.recordType,fixture:WT(r,e)}))}import{promises as Cg}from"node:fs";import{join as zg,relative as JT,sep as YT}from"node:path";var XT=67324752,QT=33639248,e0=101010256,t0=(()=>{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 r0(t){let e=4294967295;for(let r=0;r<t.length;r++)e=t0[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}async function n0(t){let e=[];async function r(n){let o=await Cg.readdir(n,{withFileTypes:!0});for(let s of o){let i=zg(n,s.name);s.isDirectory()?await r(i):s.isFile()&&e.push(JT(t,i).split(YT).join("/"))}}return await r(t),e.sort(),e}async function Ng(t){let e=await n0(t),r=[],n=[],o=0;for(let a of e){let c=Buffer.from(a,"utf8"),l=await Cg.readFile(zg(t,a)),u=r0(l),d=Buffer.alloc(30+c.length);d.writeUInt32LE(XT,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(QT,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(e0,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 o0(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":"hook"}function Ui(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function s0(t){let e=jg(t,"from"),r=jg(t,"to");return{fromSource:e?Ui(e,"source"):void 0,fromRecordType:e?Ui(e,"recordType"):void 0,toSource:r?Ui(r,"source"):void 0,toRecordType:r?Ui(r,"recordType"):void 0}}function jg(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 i0(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 a0(t,e){let r=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return r?Number(r[1]):void 0}function c0(t){return/\bcreatedFrom\b/.test(t)}function Lg(t){let e=o0(t),r=[];if(e==="hook")return{kind:e,warnings:r};let{fromSource:n,toSource:o,fromRecordType:s,toRecordType:i}=s0(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=i0(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&&!c0(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=a0(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 Dg(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(`
1292
+ `)}var u0="2026-01-01",Mg="2026-01-01T00:00:00.000Z";function d0(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"?u0:r.startsWith("timestamp")?Mg: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:Mg}:{}:r==="uuid"?"00000000-0000-0000-0000-000000000000":r==="array"||r.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function p0(t){let e={};for(let r of t.columns)e[r.name]=d0(r.pgType,r.name);return e}function f0(t,e={}){let r=e.event??"before_save";return{name:`${t.recordType} ${r} (generated)`,context:{recordType:t.recordType,event:r,source:t.source,payload:p0(t)},expect:e.expect??"pass"}}function Ug(t,e={}){return t.map(r=>({recordType:r.recordType,fixture:f0(r,e)}))}import{promises as Zg}from"node:fs";import{join as qg,relative as h0,sep as m0}from"node:path";var g0=67324752,y0=33639248,b0=101010256,w0=(()=>{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 _0(t){let e=4294967295;for(let r=0;r<t.length;r++)e=w0[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}async function v0(t){let e=[];async function r(n){let o=await Zg.readdir(n,{withFileTypes:!0});for(let s of o){let i=qg(n,s.name);s.isDirectory()?await r(i):s.isFile()&&e.push(h0(t,i).split(m0).join("/"))}}return await r(t),e.sort(),e}async function Fg(t){let e=await v0(t),r=[],n=[],o=0;for(let a of e){let c=Buffer.from(a,"utf8"),l=await Zg.readFile(qg(t,a)),u=_0(l),d=Buffer.alloc(30+c.length);d.writeUInt32LE(g0,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 w=Buffer.alloc(46+c.length);w.writeUInt32LE(y0,0),w.writeUInt16LE(20,4),w.writeUInt16LE(20,6),w.writeUInt16LE(0,10),w.writeUInt32LE(u,16),w.writeUInt32LE(l.length,20),w.writeUInt32LE(l.length,24),w.writeUInt16LE(c.length,28),w.writeUInt32LE(o,42),c.copy(w,46),n.push(w),o+=d.length+l.length}let s=Buffer.concat(n),i=Buffer.alloc(22);return i.writeUInt32LE(b0,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 x0(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":"hook"}function qi(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function k0(t){let e=Bg(t,"from"),r=Bg(t,"to");return{fromSource:e?qi(e,"source"):void 0,fromRecordType:e?qi(e,"recordType"):void 0,toSource:r?qi(r,"source"):void 0,toRecordType:r?qi(r,"recordType"):void 0}}function Bg(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 $0(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 S0(t,e){let r=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return r?Number(r[1]):void 0}function T0(t){return/\bcreatedFrom\b/.test(t)}function Vg(t){let e=x0(t),r=[];if(e==="hook")return{kind:e,warnings:r};let{fromSource:n,toSource:o,fromRecordType:s,toRecordType:i}=k0(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=$0(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&&!T0(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=S0(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 Hg(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(`
1148
1293
  `);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(`
1149
1294
  lint: ${n(`${e.warnings.length} warning(s).`)}`),i.join(`
1150
- `)}function Mg(t){return t.cases.filter(e=>e.status==="failed").length}function os(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function l0(t){let e=Mg(t),r=[];r.push('<?xml version="1.0" encoding="UTF-8"?>'),r.push(`<testsuite name="${os(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let n of t.cases){let o=` <testcase name="${os(n.name)}"`;if(n.status==="passed"){r.push(`${o} />`);continue}r.push(`${o}>`);let s=n.detail??"failed",i=n.type?` type="${os(n.type)}"`:"";r.push(` <failure${i} message="${os(s)}">${os(s)}</failure>`),r.push(" </testcase>")}return r.push("</testsuite>"),`${r.join(`
1295
+ `)}function Kg(t){return t.cases.filter(e=>e.status==="failed").length}function ss(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function E0(t){let e=Kg(t),r=[];r.push('<?xml version="1.0" encoding="UTF-8"?>'),r.push(`<testsuite name="${ss(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let n of t.cases){let o=` <testcase name="${ss(n.name)}"`;if(n.status==="passed"){r.push(`${o} />`);continue}r.push(`${o}>`);let s=n.detail??"failed",i=n.type?` type="${ss(n.type)}"`:"";r.push(` <failure${i} message="${ss(s)}">${ss(s)}</failure>`),r.push(" </testcase>")}return r.push("</testsuite>"),`${r.join(`
1151
1296
  `)}
1152
- `}function u0(t){let e={suite:t.name,tests:t.cases.length,failures:Mg(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
1153
- `}function Zi(t,e){return e==="junit"?l0(t):u0(t)}var xt={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"},Ge={hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",clearLine:"\x1B[2K",clearToEnd:"\x1B[0J",col0:"\r",cursorUp:t=>`\x1B[${t}A`},to=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Lt={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},Ug=/\x1b\[[0-9;]*m/g;function kr(t){return t.replace(Ug,"").length}function Cl(t,e){return e<=0?1:Math.max(1,Math.ceil(kr(t)/e))}function d0(){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 zl=d0();function Xe(){return zl}function Nl(t){zl=t}function Rt(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function Dt(t,e){return zl?`${t}${e}${xt.reset}`:e}var w={bold:t=>Dt(xt.bold,t),dim:t=>Dt(xt.dim,t),red:t=>Dt(xt.red,t),green:t=>Dt(xt.green,t),yellow:t=>Dt(xt.yellow,t),blue:t=>Dt(xt.blue,t),magenta:t=>Dt(xt.magenta,t),cyan:t=>Dt(xt.cyan,t),grey:t=>Dt(xt.grey,t)};var ft={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}`},Mr={add:t=>w.green(`+ ${t}`),change:t=>w.yellow(`~ ${t}`),destroy:t=>w.red(`- ${t}`)},p0=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),f0=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),h0=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function ro(t){let e=t.toLowerCase();return p0.has(e)?w.green(t):f0.has(e)?w.red(t):h0.has(e)?w.yellow(t):t}function Ur(t,e=[]){let r=Math.max(kr(t),...e.map(kr),0),n=r+2,o=w.cyan(Lt.v),s=a=>` ${a}${" ".repeat(r-kr(a))} `,i=[w.cyan(`${Lt.tl}${Lt.h.repeat(n)}${Lt.tr}`),`${o}${w.bold(s(t))}${o}`];if(e.length){i.push(`${w.cyan(Lt.ml)}${w.dim(Lt.h.repeat(n))}${w.cyan(Lt.mr)}`);for(let a of e)i.push(`${o}${s(a)}${o}`)}return i.push(w.cyan(`${Lt.bl}${Lt.h.repeat(n)}${Lt.br}`)),i.join(`
1154
- `)}function Zr(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=>kr(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]-kr(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]??kr(l)))))));for(let l of t)c.push(a(l));return c.join(`
1155
- `)}function jl(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`${Xe()?e.map(n=>Dt(xt.cyan,n)).join(`
1297
+ `}function R0(t){let e={suite:t.name,tests:t.cases.length,failures:Kg(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
1298
+ `}function Fi(t,e){return e==="junit"?E0(t):R0(t)}var $t={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"},We={hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",clearLine:"\x1B[2K",clearToEnd:"\x1B[0J",col0:"\r",cursorUp:t=>`\x1B[${t}A`},ro=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Dt={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},Gg=/\x1b\[[0-9;]*m/g;function Sr(t){return t.replace(Gg,"").length}function Ul(t,e){return e<=0?1:Math.max(1,Math.ceil(Sr(t)/e))}function P0(){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 Zl=P0();function Qe(){return Zl}function ql(t){Zl=t}function ht(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function Mt(t,e){return Zl?`${t}${e}${$t.reset}`:e}var g={bold:t=>Mt($t.bold,t),dim:t=>Mt($t.dim,t),red:t=>Mt($t.red,t),green:t=>Mt($t.green,t),yellow:t=>Mt($t.yellow,t),blue:t=>Mt($t.blue,t),magenta:t=>Mt($t.magenta,t),cyan:t=>Mt($t.cyan,t),grey:t=>Mt($t.grey,t)};var Ve={success:t=>`${g.green("\u2713")} ${t}`,error:t=>`${g.red("\u2716")} ${t}`,warn:t=>`${g.yellow("\u26A0")} ${t}`,info:t=>`${g.dim("\xB7")} ${t}`,step:t=>`${g.cyan("\u25B8")} ${t}`},Zr={add:t=>g.green(`+ ${t}`),change:t=>g.yellow(`~ ${t}`),destroy:t=>g.red(`- ${t}`)},A0=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),I0=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),O0=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function no(t){let e=t.toLowerCase();return A0.has(e)?g.green(t):I0.has(e)?g.red(t):O0.has(e)?g.yellow(t):t}function qr(t,e=[]){let r=Math.max(Sr(t),...e.map(Sr),0),n=r+2,o=g.cyan(Dt.v),s=a=>` ${a}${" ".repeat(r-Sr(a))} `,i=[g.cyan(`${Dt.tl}${Dt.h.repeat(n)}${Dt.tr}`),`${o}${g.bold(s(t))}${o}`];if(e.length){i.push(`${g.cyan(Dt.ml)}${g.dim(Dt.h.repeat(n))}${g.cyan(Dt.mr)}`);for(let a of e)i.push(`${o}${s(a)}${o}`)}return i.push(g.cyan(`${Dt.bl}${Dt.h.repeat(n)}${Dt.br}`)),i.join(`
1299
+ `)}function Xt(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=>Sr(u[l]??"")));let a=l=>{let u=l.map((d,w)=>{let m=d??"";return w===l.length-1?m:m+" ".repeat(Math.max(0,i[w]-Sr(m)))});return r+u.join(n)},c=[];e.head&&(c.push(a(e.head.map(l=>g.bold(l)))),c.push(a(e.head.map((l,u)=>g.dim("\u2500".repeat(i[u]??Sr(l)))))));for(let l of t)c.push(a(l));return c.join(`
1300
+ `)}function Fl(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`${Qe()?e.map(n=>Mt($t.cyan,n)).join(`
1156
1301
  `):e.join(`
1157
1302
  `)}
1158
- ${w.dim(` ${t}`)}`}var Mt=t=>{process.stderr.write(t)};function qi(){return Xe()&&process.stderr.isTTY===!0}function Zg(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=qi(),n=0,o;r&&(Mt(Ge.hideCursor),o=setInterval(()=>{Mt(`${Ge.col0}${Ge.clearLine}${w.magenta(to[n++%to.length])} ${t}`)},80));let s=()=>{o&&clearInterval(o),r&&Mt(`${Ge.col0}${Ge.clearLine}${Ge.showCursor}`)};try{let i=await e();return s(),r&&Mt(`${ft.success(t)}
1159
- `),i}catch(i){throw s(),r&&Mt(`${ft.error(t)}
1160
- `),i}}function Ll(t){let e=0,r={stage:"queued"},n=!1,o=()=>{let c=w.magenta(to[e%to.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} ${Zg(r.percent)} ${d}`},s=()=>{Mt(`${Ge.col0}${Ge.clearLine}${o()}`),n=!0},i=()=>{n&&Mt(`${Ge.col0}${Ge.clearLine}`),n=!1};Mt(Ge.hideCursor);let a=setInterval(()=>{e+=1,s()},80);return{log(c){i(),Mt(`${c}
1161
- `),s()},status(c){r=c,s()},done(c){clearInterval(a),i(),Mt(Ge.showCursor);let l=c.stage!=="failed",u=`${t} ${w.dim("\u25B8")} ${m0(c.stage)}${c.runStatus?` (${c.runStatus})`:""}`;Mt(`${l?ft.success(u):ft.error(u)}
1162
- `)},stop(){clearInterval(a),i(),Mt(Ge.showCursor)}}}function m0(t){return t==="completed"?w.green(t):t==="failed"?w.red(t):w.cyan(t)}function Pt(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(Ge.hideCursor);let u=0,d=()=>{let y=process.stderr.columns??process.stdout.columns??80;u>0&&(a(Ge.cursorUp(u)),a(Ge.clearToEnd));let v=0;for(let E=0;E<e.length;E+=1){let P=e[E],z=E===i,V=z?w.cyan("\u25B6"):" ",Y=P.disabled?w.grey(P.label):z?w.bold(w.cyan(P.label)):P.label,Ke=P.description?` ${w.dim(P.description)}`:"",et=` ${V} ${Y}${Ke}`;a(`\r${et}
1165
- `),v+=Cl(et,y)}u=v},b=()=>{c.removeListener("data",f),c.setRawMode?.(l??!1),c.pause(),a(Ge.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(`
1166
- `),o(new Error("aborted"));return}if(v==="\r"||v===`
1167
- `){let P=e[i];if(P.disabled)return;b(),n(P.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 Fg(t,e){return`${ro(t)}${" ".repeat(Math.max(0,e-t.length))}`}var g0=t=>new Promise(e=>setTimeout(e,t));function qg(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}] ${Fg(t.state,9)} ${t.conduitId} \u2192 ${e}${n} hop=${t.hop}${o}${r}`}async function Bg(t,e,r={}){let n=r.sink??(u=>{process.stdout.write(`${u}
1168
- `)}),o=r.sleep??g0,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(qg(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(qg(b)),a+=1,b.updatedAt>c&&(c=b.updatedAt)}return a}function y0(t){let e=t.externalId??"\u2014",r=t.createdByConduit?` via=${t.createdByConduit}`:"",n=t.lastError?` last_error="${t.lastError}"`:"";return`${t.id} ${Fg(t.writeStatus,9)} ${t.sourceSystem}/${e} role=${t.role} master=${t.masterTable}/${t.masterRowId}${r}${n}`}async function Vg(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(y0(o));return r(`
1170
- binding: ${n.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:n.length}}Dl();function Kg(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 Ml=".github/workflows/turbobase-release-deploy.yml",v0=`# \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
1303
+ ${g.dim(` ${t}`)}`}var Ut=t=>{process.stderr.write(t)};function Bi(){return Qe()&&process.stderr.isTTY===!0}function Wg(t,e=15){let r=Math.max(0,Math.min(100,t??0)),n=Math.round(r/100*e);return`${"\u2588".repeat(n)}${g.dim("\u2591".repeat(e-n))}`}async function ie(t,e){let r=Bi(),n=0,o;r&&(Ut(We.hideCursor),o=setInterval(()=>{Ut(`${We.col0}${We.clearLine}${g.magenta(ro[n++%ro.length])} ${t}`)},80));let s=()=>{o&&clearInterval(o),r&&Ut(`${We.col0}${We.clearLine}${We.showCursor}`)};try{let i=await e();return s(),r&&Ut(`${Ve.success(t)}
1304
+ `),i}catch(i){throw s(),r&&Ut(`${Ve.error(t)}
1305
+ `),i}}function Bl(t){let e=0,r={stage:"queued"},n=!1,o=()=>{let c=g.magenta(ro[e%ro.length]),l=g.cyan(r.stage),u=r.runStatus?` ${g.dim(`(${r.runStatus})`)}`:"",d=`${String(Math.round(r.percent??0)).padStart(3)}%`;return`${c} ${t} ${g.dim("\u25B8")} ${l}${u} ${Wg(r.percent)} ${d}`},s=()=>{Ut(`${We.col0}${We.clearLine}${o()}`),n=!0},i=()=>{n&&Ut(`${We.col0}${We.clearLine}`),n=!1};Ut(We.hideCursor);let a=setInterval(()=>{e+=1,s()},80);return{log(c){i(),Ut(`${c}
1306
+ `),s()},status(c){r=c,s()},done(c){clearInterval(a),i(),Ut(We.showCursor);let l=c.stage!=="failed",u=`${t} ${g.dim("\u25B8")} ${C0(c.stage)}${c.runStatus?` (${c.runStatus})`:""}`;Ut(`${l?Ve.success(u):Ve.error(u)}
1307
+ `)},stop(){clearInterval(a),i(),Ut(We.showCursor)}}}function C0(t){return t==="completed"?g.green(t):t==="failed"?g.red(t):g.cyan(t)}function mt(t,e,r={}){return new Promise((n,o)=>{let s=e.findIndex(b=>!b.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=b=>{process.stderr.write(b)},c=process.stdin,l=c.isRaw;c.setRawMode?.(!0),c.resume(),a(`${g.bold(g.cyan("?"))} ${g.bold(t)}
1308
+ `),a(`${g.dim(" (\u2191/\u2193 to move, enter to select, ctrl+c to abort)")}
1309
+ `),a(We.hideCursor);let u=0,d=()=>{let b=process.stderr.columns??process.stdout.columns??80;u>0&&(a(We.cursorUp(u)),a(We.clearToEnd));let k=0;for(let E=0;E<e.length;E+=1){let P=e[E],z=E===i,H=z?g.cyan("\u25B6"):" ",Y=P.disabled?g.grey(P.label):z?g.bold(g.cyan(P.label)):P.label,Ge=P.description?` ${g.dim(P.description)}`:"",tt=` ${H} ${Y}${Ge}`;a(`\r${tt}
1310
+ `),k+=Ul(tt,b)}u=k},w=()=>{c.removeListener("data",f),c.setRawMode?.(l??!1),c.pause(),a(We.showCursor)},m=b=>{let k=i;for(let E=0;E<e.length;E+=1)if(k=(k+b+e.length)%e.length,!e[k].disabled){i=k;return}},f=b=>{let k=b.toString("utf8");if(k===""||k==="q"){w(),a(`
1311
+ `),o(new Error("aborted"));return}if(k==="\r"||k===`
1312
+ `){let P=e[i];if(P.disabled)return;w(),n(P.value);return}if(k==="\x1B[A"||k==="k"){m(-1),d();return}if(k==="\x1B[B"||k==="j"){m(1),d();return}let E=Number(k);Number.isFinite(E)&&E>=1&&E<=e.length&&!e[E-1].disabled&&(i=E-1,d())};c.on("data",f),d()})}function Yg(t,e){return`${no(t)}${" ".repeat(Math.max(0,e-t.length))}`}var z0=t=>new Promise(e=>setTimeout(e,t));function Jg(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}] ${Yg(t.state,9)} ${t.conduitId} \u2192 ${e}${n} hop=${t.hop}${o}${r}`}async function Xg(t,e,r={}){let n=r.sink??(u=>{process.stdout.write(`${u}
1313
+ `)}),o=r.sleep??z0,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(Jg(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 w of[...d].reverse())n(Jg(w)),a+=1,w.updatedAt>c&&(c=w.updatedAt)}return a}function N0(t){let e=t.externalId??"\u2014",r=t.createdByConduit?` via=${t.createdByConduit}`:"",n=t.lastError?` last_error="${t.lastError}"`:"";return`${t.id} ${Yg(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}
1314
+ `)});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(N0(o));return r(`
1315
+ binding: ${n.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:n.length}}Vi();function ty(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 Vl=".github/workflows/turbobase-release-deploy.yml",M0=`# \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
1171
1316
  # Turbobase release deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR repo)
1172
1317
  #
1173
1318
  # Epic #775 "GitHub is just a link": Turbobase hosts nothing and clones nothing.
@@ -1269,7 +1414,7 @@ jobs:
1269
1414
  --ref "\${{ github.sha }}" \\
1270
1415
  --project . \\
1271
1416
  --follow
1272
- `,x0=".github/workflows/turbobase-tables-plan.yml",k0=`# \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
1417
+ `,U0=".github/workflows/turbobase-tables-plan.yml",Z0=`# \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
1273
1418
  # Turbobase table check \u2014 REUSABLE TEMPLATE (drop this into YOUR app repo)
1274
1419
  #
1275
1420
  # Runs \`turbobase tables plan\` against your instance on every pull request. It
@@ -1344,14 +1489,14 @@ jobs:
1344
1489
  # field and at what type. Writes nothing to the instance either way.
1345
1490
  - name: Plan the declared tables
1346
1491
  run: turbobase tables plan .
1347
- `;function Gg(){return[{path:Ml,content:v0}]}function Wg(){return[{path:x0,content:k0}]}var $0=[".mcp.json"];function Yg(t,e=$0){let r=i=>i.replace(/^\//,""),n=new Set(t.split(`
1492
+ `;function ry(){return[{path:Vl,content:M0}]}function ny(){return[{path:U0,content:Z0}]}Vi();var q0=[".mcp.json"];function sy(t,e=q0){let r=i=>i.replace(/^\//,""),n=new Set(t.split(`
1348
1493
  `).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(`
1349
1494
  `)?t:`${t}
1350
1495
  `}
1351
1496
  # Added by the Turbobase scaffold.
1352
1497
  ${o.join(`
1353
1498
  `)}
1354
- `}var S0=`# Turbobase Extensions \u2014 extension project
1499
+ `}var F0=`# Turbobase Extensions \u2014 extension project
1355
1500
 
1356
1501
  This directory authors **Turbobase extensions** (hooks today; conduits later)
1357
1502
  against a live instance. The \`turbobase\` CLI is the engine; Claude Code drives it
@@ -1420,8 +1565,8 @@ order is the signal, and it is the part the product team reads first.
1420
1565
 
1421
1566
  Do this WITHOUT being asked \u2014 treat it as part of finishing a task, like
1422
1567
  updating a test. It is checked into the repo so the whole team sees it.
1423
- `,T0=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 E0(t){return`---
1568
+ `,B0=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)+`
1569
+ `;function V0(t){return`---
1425
1570
  name: generate-types
1426
1571
  description: Regenerate ${t} from the signed-in instance's catalog. Use before authoring or whenever the schema may have changed.
1427
1572
  ---
@@ -1432,7 +1577,7 @@ write \`${t}\`. Import the generated record interfaces for typed rows.
1432
1577
 
1433
1578
  The OpenAPI half is cookie-session-gated, so a headless run with a stored token
1434
1579
  degrades to record shapes only and says so \u2014 that is expected, not a failure.
1435
- `}var R0=`---
1580
+ `}var H0=`---
1436
1581
  name: mock-test
1437
1582
  description: Dry-run a hook against samples/ fixtures using the production sandbox. Use after editing a hook, before deploy.
1438
1583
  ---
@@ -1441,7 +1586,7 @@ Run \`turbobase ext test hooks/<file>.ts\`. It bundles the hook through the same
1441
1586
  self-contained-fence esbuild + isolated-vm the live runtime uses, then runs it
1442
1587
  against every \`samples/*.json\` fixture and reports pass/reject per sample. Add a
1443
1588
  fixture for each branch (a passing record and a rejecting record).
1444
- `,P0=`---
1589
+ `,K0=`---
1445
1590
  name: deploy
1446
1591
  description: Deploy a hook to your instance. Use only after mock-test is green.
1447
1592
  ---
@@ -1449,7 +1594,7 @@ description: Deploy a hook to your instance. Use only after mock-test is green.
1449
1594
  Run \`turbobase ext deploy hooks/<file>.ts\`. It POSTs the hook source to
1450
1595
  /v1/extensions with the stored admin PAT; the hook lands **active**. Re-deploying
1451
1596
  the same id overwrites it (idempotent). Tail with \`turbobase ext logs <id>\`.
1452
- `;function A0(t){return`# ${t} \u2014 Turbobase app
1597
+ `;function G0(t){return`# ${t} \u2014 Turbobase app
1453
1598
 
1454
1599
  This directory is a **hosted Turbobase app**: a Vite + React + TS SPA served
1455
1600
  same-origin by the instance at \`/a/${t}\`. The \`turbobase\` CLI ships it; you
@@ -1528,6 +1673,8 @@ Check them before you trust a result.
1528
1673
  - \`src/lib/turbobase.ts\` \u2014 the auth-wired client. Don't rewrite it; import from it.
1529
1674
  - \`src/types.ts\` \u2014 generated record types (\`turbobase project types -o src/types.ts\`),
1530
1675
  refreshed at the start of every Claude Code session.
1676
+ - \`hooks/\` \u2014 validation and business rules, one self-contained file each.
1677
+ - \`samples/\` \u2014 JSON fixtures \`turbobase ext test\` runs the hooks against.
1531
1678
  - \`INSTANCE.md\` \u2014 the grounding brief (\`turbobase project grounding\`), refreshed
1532
1679
  each session; instance-specific, don't hand-edit.
1533
1680
  - \`vite.config.ts\` \u2014 \`base\` is pinned to \`/a/${t}/\` and MUST stay that way, or
@@ -1539,11 +1686,35 @@ Check them before you trust a result.
1539
1686
  - **Read** with \`select('<table>?select=...')\` \u2192 PostgREST, row-level-security scoped.
1540
1687
  - **Write** with \`write('<recordType>', { parent, lines })\` \u2192 \`POST /v1/data/:recordType\`,
1541
1688
  the canonical write boundary. **Never** write a table directly through PostgREST.
1689
+ - **Delete** with \`del('<recordType>', { pgRowId })\` \u2192 \`DELETE /v1/data/:recordType\`.
1690
+ Returns \`{ deleted, enqueued }\`. \`enqueued\` means a source delete was QUEUED \u2014
1691
+ not that the source accepted it: it can still be held for operator approval or
1692
+ refused upstream, and that failure surfaces as a sync failure, not as a throw.
1542
1693
 
1543
1694
  Both are same-origin and carry the session cookie. There are no app-owned keys,
1544
1695
  no Bearer tokens to manage, and no sign-in page to build \u2014 the instance handles
1545
1696
  auth before your SPA loads.
1546
1697
 
1698
+ ## Business rules go in a hook, not in this app
1699
+
1700
+ The app **cannot** bypass \`POST /v1/data\` \u2014 \`authenticated\` holds no
1701
+ INSERT/UPDATE/DELETE on the mirror, so a PostgREST write is refused however the
1702
+ query is phrased. Don't try to route around it; that boundary is where every
1703
+ write runs the record type's \`before_save\`.
1704
+
1705
+ So validation belongs in a hook, not in a component: a rule enforced in
1706
+ \`App.tsx\` is bypassed by the chat agent, an MCP client, the sync worker and the
1707
+ next app. \`hooks/\` already holds a working example for the record the starter
1708
+ touches. Edit it, then:
1709
+
1710
+ \`\`\`sh
1711
+ turbobase ext test hooks/<file>.ts # against samples/*.json, in the production sandbox
1712
+ turbobase ext deploy hooks/<file>.ts # lands ACTIVE \u2014 it gates writes immediately
1713
+ \`\`\`
1714
+
1715
+ A hook is pure and credentials-free: no secrets, no network, no Node builtins,
1716
+ and nothing factored into a shared module.
1717
+
1547
1718
  **Reading data yourself, without a browser.** The PAT in \`.mcp.json\` authenticates
1548
1719
  the authoring MCP, but PostgREST rejects it outright (\`PGRST301 \u2026 Expected 3
1549
1720
  parts; got 1\`) \u2014 it is an opaque bearer, not a JWT. To read rows from a script or
@@ -1634,7 +1805,27 @@ a test. \`turbobase apps deploy\` reads both files and queues what it finds for
1634
1805
  review, so what you write reaches the knowledge base and the product team instead
1635
1806
  of evaporating at the end of the session. Keep the section headings exactly as
1636
1807
  they are \u2014 the ingest finds entries by heading, not by filename.
1637
- `}var I0="---\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",O0=`---
1808
+ `}var oo="customer",$n="email",W0="^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$",J0=`// EXAMPLE \u2014 a business rule that holds for EVERY writer, not just this app.
1809
+ //
1810
+ // It runs inside \`POST /v1/data\`, which is the only way an app can write at all:
1811
+ // the \`authenticated\` role holds no INSERT/UPDATE/DELETE on the mirror, so a
1812
+ // PostgREST write is refused however the query is phrased. That is what makes a
1813
+ // rule here different from the same rule in a React component \u2014 this one also
1814
+ // applies to the chat agent, an MCP client, another app, and the sync worker.
1815
+ //
1816
+ // As written it rejects a malformed address and passes everything else, so the
1817
+ // app's edit box shows you the rejection the moment you try one. Replace the
1818
+ // check with the rule you actually need.
1819
+ //
1820
+ // turbobase ext lint hooks/... static check
1821
+ // turbobase ext test hooks/... run against samples/*.json, in the production sandbox
1822
+ // turbobase ext deploy hooks/... lands ACTIVE \u2014 it starts gating writes immediately
1823
+ //
1824
+ // Pure and credentials-free: no secrets, no network, no Node builtins, one
1825
+ // concern per file, nothing factored into a shared module (the sandbox fences
1826
+ // every import except the SDK).
1827
+ `;function Y0(){let t=Br("hook",{recordType:oo,event:"before_save",template:"enforce-format",field:$n,regex:W0,id:`app:${oo}:${$n}-format`,description:`Reject a ${oo} write whose ${$n} is not an address.`}),e=(r,n,o)=>JSON.stringify({name:o,context:{recordType:oo,event:"before_save",payload:r},expect:n},null,2)+`
1828
+ `;return[{path:t.relativePath,content:`${J0}${t.content}`},{path:`samples/${oo}.${$n}-ok.json`,content:e({company_name:"Acme Supply",[$n]:"ada@example.com"},"pass","a well-formed address passes")},{path:`samples/${oo}.${$n}-malformed.json`,content:e({company_name:"Acme Supply",[$n]:"ada-at-example"},"reject","a malformed address is rejected")}]}var X0="---\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",Q0=`---
1638
1829
  name: ship-app
1639
1830
  description: Push the app's source to the instance and deploy it live. Use once the app has been previewed and works.
1640
1831
  ---
@@ -1677,7 +1868,7 @@ Text files only \u2014 \`push\` skips \`node_modules/\`, \`dist/\`, \`build/\`,
1677
1868
  non-text, so images and fonts belong in the build pipeline or object storage, not
1678
1869
  the source tree. \`INSTANCE-LEARNINGS.md\` and \`TURBOBASE-FEEDBACK.md\` sit at the
1679
1870
  project root and DO travel \u2014 deploy reads them.
1680
- `;function C0(t){return`---
1871
+ `;function eE(t){return`---
1681
1872
  name: record-learning
1682
1873
  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.
1683
1874
  ---
@@ -1722,7 +1913,7 @@ the product team acts on first, so it is maintained with the entries.
1722
1913
 
1723
1914
  Do not reword the three headings. The deploy-side ingest recognises entries by
1724
1915
  heading, not by filename, so a renamed section is a finding nobody receives.
1725
- `}function z0(t){return`# What this instance's source system actually does
1916
+ `}function tE(t){return`# What this instance's source system actually does
1726
1917
 
1727
1918
  Findings from ${t?`building the ${t.slug} app against the live mirror`:"authoring extensions against the live instance"}.
1728
1919
  Written for the knowledge base, and **everything here is verified against real
@@ -1841,7 +2032,7 @@ finding has not been handed to the knowledge base yet.
1841
2032
  and then \`turbobase skills release\`. \`turbobase skills list\` shows what is
1842
2033
  already live, which is worth reading before adding another rule. -->
1843
2034
 
1844
- `}function N0(t){return`# Feedback for the Turbobase team \u2014 what ${t?`building the ${t.slug} app`:"authoring extensions here"} actually hit
2035
+ `}function rE(t){return`# Feedback for the Turbobase team \u2014 what ${t?`building the ${t.slug} app`:"authoring extensions here"} actually hit
1845
2036
 
1846
2037
  Everything below cost time or produced a wrong result. Not speculation, and not
1847
2038
  a wishlist. This file is about the PLATFORM \u2014 scaffold, catalog, CLI, MCP, API.
@@ -1905,7 +2096,7 @@ Expected / happened / cost / fix.
1905
2096
 
1906
2097
  <!-- Rank the findings above by how much time each would have saved. Position is
1907
2098
  the signal \u2014 1 is the biggest win. -->
1908
- `}function j0(t,e){let r=e?`
2099
+ `}function nE(t,e){let r=e?`
1909
2100
  # INSTANCE.md \u2014 the instance's grounding brief (see CLAUDE.md). Reuse the
1910
2101
  # --records focus a previous run stamped into the file, so a refresh never
1911
2102
  # narrows what an agent deliberately widened.
@@ -1923,52 +2114,53 @@ turbobase project grounding \${records:+--records "$records"} --query ${JSON.str
1923
2114
  set -euo pipefail
1924
2115
  turbobase project types -o ${t} >/dev/null \\
1925
2116
  || echo "turbobase: \\\`turbobase project types\\\` failed (its error is above) \u2014 ${t} was NOT refreshed." >&2
1926
- ${r}`}var L0=JSON.stringify({hooks:{SessionStart:[{hooks:[{type:"command",command:"bash .claude/hooks/session-start-refresh-types.sh"}]}]}},null,2)+`
1927
- `,Jg="",D0=t=>`node_modules/
2117
+ ${r}`}var oE=JSON.stringify({hooks:{SessionStart:[{hooks:[{type:"command",command:"bash .claude/hooks/session-start-refresh-types.sh"}]}]}},null,2)+`
2118
+ `,oy="",sE=t=>`node_modules/
1928
2119
 
1929
2120
  # Holds a live personal access token (written by \`turbobase ${t?"apps":"project"} init\`).
1930
2121
  .mcp.json
1931
2122
 
1932
2123
  .DS_Store
1933
- `;function Ul(t={}){let e=T0.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:D0(r)},{path:"INSTANCE-LEARNINGS.md",content:z0(o)},{path:"TURBOBASE-FEEDBACK.md",content:N0(o)},{path:".claude/settings.json",content:L0},{path:".claude/skills/generate-types/SKILL.md",content:E0(n)},{path:".claude/skills/record-learning/SKILL.md",content:C0(o)},{path:".claude/hooks/session-start-refresh-types.sh",content:j0(n,o),executable:!0}];return r?[{path:"CLAUDE.md",content:A0(t.appSlug)},...s,{path:".claude/skills/preview-app/SKILL.md",content:I0},{path:".claude/skills/ship-app/SKILL.md",content:O0},...Wg()]:[{path:"CLAUDE.md",content:S0},...s,{path:".claude/skills/mock-test/SKILL.md",content:R0},{path:".claude/skills/deploy/SKILL.md",content:P0},{path:"hooks/.gitkeep",content:Jg},{path:"samples/.gitkeep",content:Jg}]}import{promises as Fl}from"node:fs";import{resolve as B0}from"node:path";var M0="For app developers \u2014 adopt these";function Xg(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 Qg(t,e){let r=Xg(t),n=Xg(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 U0(t){return t.replace(/[‐-―]/g,"-").toLowerCase().replace(/\s+/g," ").trim()}var nU=U0(M0);Qo();Dr();var Z0=t=>new Promise(e=>setTimeout(e,t));function ey(t){return t.stage==="completed"||t.stage==="failed"}function q0(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function F0(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 Zl(t,e={}){let r=e.sink??(b=>{process.stdout.write(`${b}
1935
- `)}),n=e.sleep??Z0,o=e.intervalMs??2e3,s=e.maxPolls??Number.POSITIVE_INFINITY,i=e.onStage??(b=>r(q0(b))),a=e.onPoll,c="",l="",u=b=>{a?.(b),b.stage!==l&&i(b),c=F0(b,c,r),l=b.stage},d=await t();if(u(d),ey(d))return d;for(let b=0;b<s;b+=1)if(await n(o),d=await t(),u(d),ey(d))return d;return d}var S=t=>{process.stdout.write(`${t}
1936
- `)},H=t=>{process.stderr.write(`${t}
1937
- `)};function x(t){H(w.red(`turbobase: ${t}`)),process.exit(1)}var ss=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function ty(t,e){let r=e.json===!0||typeof e.reporter=="string";(t.color===!1||r)&&Nl(!1)}async function ne(t){let e=await Jt(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let r=await xr();if(t){let n=r.length?` Stored instances: ${r.map(o=>o.baseUrl).join(", ")}.`:"";x(`not signed in to ${jt(t)}.${n} Run \`turbobase auth login --base-url ${jt(t)} --token tb_pat_\u2026\`.`)}if(r.length===0&&x("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Rt())try{let n=await Pt("Multiple instances stored \u2014 pick the active one:",r.map(s=>({value:s.baseUrl,label:s.baseUrl,description:`updated ${s.updatedAt}`})));await ji(n);let o=await Jt();if(o)return{baseUrl:o.baseUrl,token:o.token}}catch{}x(`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 ce(t,e,r){if(!(t instanceof ge)||t.status!==403)return;t.body?.error==="approval_required"&&x(`${r} denied (403): an approval-gated deploy needs a recorded approval \u2014 pass --approved-by <email>.`),x(`${r} forbidden (403) \u2014 the stored PAT lacks the '${e}' scope. Re-run \`turbobase auth login\` with a token that has it.`)}async function ql(t,e,r){let n=r?Number(r):void 0;if(qi()){let s=Ll(e),i;try{i=await Zl(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(),x(`${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 Zl(t,{sink:S,intervalMs:n})}catch(s){x(`${e} --follow failed: ${s instanceof Error?s.message:String(s)}`)}o.stage==="failed"&&x(`${e} failed${o.runStatus?` (${o.runStatus})`:""}.`),S(`${e} ${o.stage}.`)}var V0=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function H0(t){try{let e=await Fl.readFile(t,"utf8");return V0.exec(e)?.[1]??null}catch{return null}}var K0=/GENERATED by `turbobase project adopt`/,ny=/^##[ \t]+v?(\d+(?:\.\d+){0,2}(?:-[0-9A-Za-z.-]+)?)[ \t]*$/,G0=/^[ \t]*[-*][ \t]+\[([ xX])\][ \t]+(.*)$/;function ry(t){let e=[],r=null;for(let n of t.split(`
1938
- `)){let o=ny.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=G0.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 W0(t){let e=t.items.map(r=>[`- [${r.done?"x":" "}] ${r.text}`,...r.extra].join(`
2124
+ `;function Hl(t={}){let e=B0.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:sE(r)},{path:"INSTANCE-LEARNINGS.md",content:tE(o)},{path:"TURBOBASE-FEEDBACK.md",content:rE(o)},{path:".claude/settings.json",content:oE},{path:".claude/skills/generate-types/SKILL.md",content:V0(n)},{path:".claude/skills/record-learning/SKILL.md",content:eE(o)},{path:".claude/hooks/session-start-refresh-types.sh",content:nE(n,o),executable:!0}];return r?[{path:"CLAUDE.md",content:G0(t.appSlug)},...s,{path:".claude/skills/preview-app/SKILL.md",content:X0},{path:".claude/skills/ship-app/SKILL.md",content:Q0},...Y0(),...ny()]:[{path:"CLAUDE.md",content:F0},...s,{path:".claude/skills/mock-test/SKILL.md",content:H0},{path:".claude/skills/deploy/SKILL.md",content:K0},{path:"hooks/.gitkeep",content:oy},{path:"samples/.gitkeep",content:oy}]}import{promises as Wl}from"node:fs";import{resolve as dE}from"node:path";var iE="For app developers \u2014 adopt these";function iy(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 ay(t,e){let r=iy(t),n=iy(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 aE(t){return t.replace(/[‐-―]/g,"-").toLowerCase().replace(/\s+/g," ").trim()}var OU=aE(iE);es();$r();var cE=t=>new Promise(e=>setTimeout(e,t));function cy(t){return t.stage==="completed"||t.stage==="failed"}function lE(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function uE(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(`
2125
+ `))r(i)}return n}async function Kl(t,e={}){let r=e.sink??(w=>{process.stdout.write(`${w}
2126
+ `)}),n=e.sleep??cE,o=e.intervalMs??2e3,s=e.maxPolls??Number.POSITIVE_INFINITY,i=e.onStage??(w=>r(lE(w))),a=e.onPoll,c="",l="",u=w=>{a?.(w),w.stage!==l&&i(w),c=uE(w,c,r),l=w.stage},d=await t();if(u(d),cy(d))return d;for(let w=0;w<s;w+=1)if(await n(o),d=await t(),u(d),cy(d))return d;return d}var x=t=>{process.stdout.write(`${t}
2127
+ `)},B=t=>{process.stderr.write(`${t}
2128
+ `)};function v(t){B(g.red(`turbobase: ${t}`)),process.exit(1)}var is=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function ly(t,e){let r=e.json===!0||typeof e.reporter=="string";(t.color===!1||r)&&ql(!1)}async function re(t){let e=await Yt(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let r=await kr();if(t){let n=r.length?` Stored instances: ${r.map(o=>o.baseUrl).join(", ")}.`:"";v(`not signed in to ${Lt(t)}.${n} Run \`turbobase auth login --base-url ${Lt(t)} --token tb_pat_\u2026\`.`)}if(r.length===0&&v("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),ht())try{let n=await mt("Multiple instances stored \u2014 pick the active one:",r.map(s=>({value:s.baseUrl,label:s.baseUrl,description:`updated ${s.updatedAt}`})));await Di(n);let o=await Yt();if(o)return{baseUrl:o.baseUrl,token:o.token}}catch{}v(`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 oe(t,e,r){if(!(t instanceof pe)||t.status!==403)return;t.body?.error==="approval_required"&&v(`${r} denied (403): an approval-gated deploy needs a recorded approval \u2014 pass --approved-by <email>.`),v(`${r} forbidden (403) \u2014 the stored PAT lacks the '${e}' scope. Re-run \`turbobase auth login\` with a token that has it.`)}async function Gl(t,e,r){let n=r?Number(r):void 0;if(Bi()){let s=Bl(e),i;try{i=await Kl(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(),v(`${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 Kl(t,{sink:x,intervalMs:n})}catch(s){v(`${e} --follow failed: ${s instanceof Error?s.message:String(s)}`)}o.stage==="failed"&&v(`${e} failed${o.runStatus?` (${o.runStatus})`:""}.`),x(`${e} ${o.stage}.`)}var pE=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function fE(t){try{let e=await Wl.readFile(t,"utf8");return pE.exec(e)?.[1]??null}catch{return null}}var hE=/GENERATED by `turbobase project adopt`/,dy=/^##[ \t]+v?(\d+(?:\.\d+){0,2}(?:-[0-9A-Za-z.-]+)?)[ \t]*$/,mE=/^[ \t]*[-*][ \t]+\[([ xX])\][ \t]+(.*)$/;function uy(t){let e=[],r=null;for(let n of t.split(`
2129
+ `)){let o=dy.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=mE.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 gE(t){let e=t.items.map(r=>[`- [${r.done?"x":" "}] ${r.text}`,...r.extra].join(`
1939
2130
  `)).join(`
1940
2131
  `);return`## v${t.version}
1941
2132
 
1942
- ${e}`}function J0(t,e){let r=ry(t);if(r.length===0&&!K0.test(t))return null;let n=new Map(r.map(u=>[u.version,u])),o=[],s=0;for(let u of ry(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)=>Qg(d.version,u.version));let i=e.split(`
1943
- `),a=i.findIndex(u=>ny.test(u)),c=(a===-1?i:i.slice(0,a)).join(`
2133
+ ${e}`}function yE(t,e){let r=uy(t);if(r.length===0&&!hE.test(t))return null;let n=new Map(r.map(u=>[u.version,u])),o=[],s=0;for(let u of uy(e)){let d=n.get(u.version);n.delete(u.version);let w=new Set(u.items.map(f=>f.key)),m=u.items.map(f=>{let b=d?.items.find(k=>k.key===f.key);return b?{...f,done:b.done,extra:b.extra}:f});for(let f of d?.items??[])w.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(w=>!w.done);d.length!==0&&(s+=d.length,o.push({version:u.version,items:d}))}o.sort((u,d)=>ay(d.version,u.version));let i=e.split(`
2134
+ `),a=i.findIndex(u=>dy.test(u)),c=(a===-1?i:i.slice(0,a)).join(`
1944
2135
  `).replace(/\s+$/,"");return{markdown:o.length===0?`${c}
1945
2136
  `:`${c}
1946
2137
 
1947
- ${o.map(W0).join(`
2138
+ ${o.map(gE).join(`
1948
2139
 
1949
2140
  `)}
1950
- `,carried:s}}function oy(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 H0(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||x(`adopt fetch failed: GET /v1/catalog/adopt-notes \u2192 ${c.status}`);let l=await c.json();if(!l.available){S(`${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){S(`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 Fl.readFile(o,"utf8").catch(()=>null),f=l.markdown,y=0;if(m!==null&&m.trim()!==""){let v=J0(m,l.markdown);v||x(`${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 Fl.writeFile(o,b+f,"utf8"),S(`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`:""}.`)})}Dr();var is=["suggested_kb_edit","kb_correction"];var Y0=[{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 gU=new Map(Y0.map(t=>[X0(t.heading),t]));var yU=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 Q0(t){return t.diff??!!t.dryRun}var eE={update_page:"append to the existing page",new_page:"create a NEW page"},$r=(t,e)=>` ${w.dim(t.padEnd(11))}${e}`,iy=t=>t.ownerEmail??t.ownerId;function oo(t){return!t.needsPageRef&&!t.blockedBy}var Fi=t=>w.green(t?` + ${t}`:" +"),tE=t=>w.red(t?` - ${t}`:" -"),kn=t=>w.dim(` ${t}`),rE=` ${w.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,Bl=80;function nE(t){let e=[rE];t.target?(e.push(kn(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(tE(`visibility: ${t.target.visibility}`)),e.push(Fi("visibility: admin"))):e.push(kn(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(kn("title, slug, evidence: untouched")),e.push(kn("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(kn("turbobase.document \xB7 new")),e.push(Fi(`title: ${t.pageTitle}`)),e.push(Fi("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(kn('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(kn('appended under "## From app developers":'));let r=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
1953
- `);for(let n of r.slice(0,Bl))e.push(Fi(n?` ${n}`:""));return r.length>Bl&&e.push(w.yellow(` \u2026 ${r.length-Bl} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function oE(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($r("page",s?`${s.title} (${s.slug}) [${s.visibility}]`:w.dim("new \u2014 no existing page matches"))),r.push($r("action",oo(n)?eE[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($r("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($r("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($r("confidence",n.withdraws?w.red("WITHDRAWN from readers (text untouched)"):w.dim("untouched"))),n.supersedes&&r.push($r("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($r("blocked",w.red(`unpublished work on this page belongs to ${iy(n.blockedBy)} \u2014 this page will be SKIPPED`))),n.alsoMatched.length>0&&r.push($r("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($r("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&&oo(n)&&r.push(...nE(n)),r.push("")}),r}function sE(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(oo)} page(s)`,`${e(l=>l.action==="update_page"&&oo(l))} appended`,`${e(l=>l.action==="new_page"&&oo(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 iE(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?iy(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 sy(t){if(t instanceof ge){let e=t.body;t.status===403&&e?.reason==="admin_required"&&x("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&&x("this instance does not serve /v1/learnings \u2014 it predates the app-developer learning loop. Ask for an instance upgrade.")}ce(t,"extensions:deploy","learnings push-kb")}async function as(t,e){let r;try{r=await se("re-reading pushed markdown",()=>t.learningsIngest(e))}catch(o){return o instanceof ge&&o.status===404?H(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`.")):H(w.yellow(`could not re-read the pushed markdown: ${aE(o)} \u2014 planning anyway.`)),null}if(r.filesScanned===0)return H(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`)),H(w.dim(n.join(" \xB7 "))),r}function aE(t){return t instanceof Error?t.message:String(t)}async function ay(t,e=r=>new Q(r)){t.section&&!is.includes(t.section.trim())&&x(`unknown --section "${t.section}" \u2014 expected one of ${is.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&x("--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 as(n,t.app),i;try{i=await se("reading the pending queue",()=>n.learningsPending(o))}catch(l){sy(l),x(`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){H(`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}H(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(S(oE(i.items,{diff:Q0(t)}).join(`
1954
- `)),S(sE(i.items)),t.dryRun){H(w.dim("dry run \u2014 nothing was written."));return}let a=i.items.filter(oo);if(a.length===0){H(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(!Rt()){H(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 Pt(`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"){H("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{let l=await se("writing pages",()=>n.learningsPushKb(i.planToken,o));S(iE(l.applied,i.items).join(`
1955
- `))}catch(l){if(l instanceof ge&&l.status===409){H(w.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),H(`re-run \`${ss} kb push\` to review the current plan.`),process.exitCode=2;return}sy(l),H(w.red(`turbobase: ${l instanceof Error?l.message:String(l)}`)),process.exitCode=2}}Dr();var so=t=>new Q(t);async function io(t,e){let r=await ne(t.baseUrl);return e(r)}async function Bi(t,e,r,n){return n.yes?!0:Rt()?await Pt(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(H("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(H(w.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function cE(t){return t.visibility!=="published"?w.dim("draft"):t.in_current_release?w.green("live"):w.yellow("unreleased")}function cy(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function lE(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(`${cy(w.bold(s.slug),e)} ${cy(cE(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 ly(t,e=so){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&x(`--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 knowledge base",()=>n.docsList(r))}catch(s){ce(s,"docs:publish","read the knowledge base"),x(`could not read the knowledge base: ${s instanceof Error?s.message:String(s)}`)}S(lE(o).join(`
1956
- `))}async function uy(t,e,r=so){let n=[...new Set(t.map(c=>c.trim()).filter(Boolean))];n.length===0&&x("name at least one page slug. `turbobase kb list` shows them.");let o=await io(e,r);if(!await Bi(`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){ce(c,"docs:publish","publish a page"),x(`publish failed: ${c instanceof Error?c.message:String(c)}`)}let a=i.published.map(c=>c.slug);S(w.green(`published ${a.length} page(s) \u2014 readable now.`)),i.missing.length>0&&(H(w.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1),H(w.dim(`undo with: turbobase kb unpublish ${a.join(" ")}`))}async function dy(t,e,r=so){let n=[...new Set(t.map(c=>c.trim()).filter(Boolean))];n.length===0&&x("name at least one page slug. `turbobase kb list` shows them.");let o=await io(e,r);if(!await Bi(`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){ce(c,"docs:publish","unpublish a page"),x(`unpublish failed: ${c instanceof Error?c.message:String(c)}`)}let a=i.unpublished.map(c=>c.slug);S(w.green(`unpublished ${a.length} page(s) \u2014 retracted now.`)),H(w.dim(`re-publish with: turbobase kb publish ${a.join(" ")}`)),i.missing.length>0&&(H(w.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1)}async function py(t,e=so){let r=await io(t,e),n;try{n=await se("reading the releases",()=>r.docsVersions())}catch(o){ce(o,"docs:publish","read the knowledge-base releases"),x(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){S("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(" ");S(`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&&S(` ${w.dim(o.release_note)}`)}}async function fy(t,e,r=so){let n=Number(t);(!Number.isInteger(n)||n<1)&&x(`version must be a release number (got '${t}'). \`turbobase kb versions\` lists them.`);let o=await io(e,r);if(await Bi(`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));S(w.green(`rolled back \u2014 release v${i.version.version_no} is current.`))}catch(i){ce(i,"docs:publish","roll the knowledge base back"),x(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function hy(t,e,r=so){let n=(t??"").trim();n||x("name the page slug to delete. `turbobase kb list` shows them.");let o=await io(e,r);if(await Bi(`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));S(w.green(`deleted ${i.deleted} \u2014 restorable from the knowledge-base trash.`))}catch(i){ce(i,"docs:publish","delete a page"),x(`delete failed: ${i instanceof Error?i.message:String(i)}`)}}Dr();function uE(t){return t.diff??!!t.dryRun}function dE(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 pE(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 my(t,e=r=>new Q(r)){t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&x("--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 as(n,t.app),i;try{i=await se("reading the pending rules",()=>n.rulesPending(o))}catch(c){ce(c,"extensions:deploy","read the pending rules"),x(`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){H(`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}H(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(S(dE(i.items,{diff:uE(t)}).join(`
1958
- `)),S(pE(i.items)),t.dryRun){H(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(!Rt()){H(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 Pt(`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"){H("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{await se("writing the rules",()=>n.rulesPush(i.planToken,o))}catch(c){c instanceof ge&&c.status===409&&x("the pending queue changed while you were reading the plan \u2014 nothing was written. Re-run to see the new plan."),x(`push failed: ${c instanceof Error?c.message:String(c)}`)}S(w.green(`wrote ${i.items.length} draft rule(s).`)),H(w.dim("They are DRAFT \u2014 nothing is injected yet. An admin reviews and publishes them under Settings \u203A Skills."))}Dr();var ao=t=>new Q(t);async function co(t,e){let r=await ne(t.baseUrl);return e(r)}async function Vi(t,e,r,n){return n.yes?!0:Rt()?await Pt(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(H("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(H(w.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function fE(t){return t.visibility!=="published"?w.dim("draft"):t.in_current_release?w.green("live"):w.yellow("unreleased")}function gy(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function hE(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(`${gy(w.bold(s.slug),e)} ${gy(fE(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 yy(t,e=ao){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&x(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await co(t,e),o;try{o=await se("reading the skills",()=>n.skillsList(r))}catch(s){ce(s,"skills:publish","read the instance skills"),x(`could not read the skills: ${s instanceof Error?s.message:String(s)}`)}S(hE(o).join(`
1959
- `))}async function by(t,e,r=ao){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&x("name at least one skill slug. `turbobase skills list` shows them.");let o=await co(e,r);if(!await Vi(`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){ce(a,"skills:publish","publish a skill"),x(`publish failed: ${a instanceof Error?a.message:String(a)}`)}S(w.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(H(w.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),H(w.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function wy(t,e,r=ao){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&x("name at least one skill slug. `turbobase skills list` shows them.");let o=await co(e,r);if(!await Vi(`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){ce(a,"skills:publish","unpublish a skill"),x(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}S(w.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),H(w.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(H(w.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function _y(t,e,r=ao){let n=Number(t);(!Number.isInteger(n)||n<1)&&x(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let o=await co(e,r);if(await Vi(`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));S(w.green(`rolled back to v${i.version.version_no}.`))}catch(i){ce(i,"skills:publish","roll back a skills release"),x(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function vy(t,e=ao){let r=await co(t,e),n;try{n=await se("reading the releases",()=>r.skillsReleases())}catch(o){ce(o,"skills:publish","read the skills releases"),x(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){H("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(`${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 xy(t,e,r=ao){let n=[...new Set((t??[]).map(l=>l.trim()).filter(Boolean))];n.length===0&&x("name at least one skill to delete. `turbobase skills list` shows the slugs.");let o=await co(e,r);if(!await Vi(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
2141
+ `,carried:s}}function py(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 re(e.baseUrl),o=dE(process.cwd(),e.out),s=e.since?.trim()||await fE(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||v(`adopt fetch failed: GET /v1/catalog/adopt-notes \u2192 ${c.status}`);let l=await c.json();if(!l.available){x(`${r} ships no release notes to adopt from (nothing written).`);return}let u=l.releases.reduce((k,E)=>k+E.items.length,0);if(u===0){x(`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??"",w=`<!-- GENERATED by \`turbobase project adopt\` against ${r} \u2014 adopted-through=${d}. Re-run to refresh; delete this file once every line is done. -->
2142
+
2143
+ `,m=await Wl.readFile(o,"utf8").catch(()=>null),f=l.markdown,b=0;if(m!==null&&m.trim()!==""){let k=yE(m,l.markdown);k||v(`${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=k.markdown,b=k.carried}await Wl.writeFile(o,w+f,"utf8"),x(`wrote ${o} \u2014 ${u} item(s) across ${l.releases.length} release(s)${s?` since v${s.replace(/^v/,"")}`:""}${b>0?`, keeping ${b} unticked item(s) already in the file`:""}.`)})}$r();var as=["suggested_kb_edit","kb_correction"];var bE=[{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 wE(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var VU=new Map(bE.map(t=>[wE(t.heading),t]));var HU=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 _E(t){return t.diff??!!t.dryRun}var vE={update_page:"append to the existing page",new_page:"create a NEW page"},Tr=(t,e)=>` ${g.dim(t.padEnd(11))}${e}`,hy=t=>t.ownerEmail??t.ownerId;function so(t){return!t.needsPageRef&&!t.blockedBy}var Hi=t=>g.green(t?` + ${t}`:" +"),xE=t=>g.red(t?` - ${t}`:" -"),Sn=t=>g.dim(` ${t}`),kE=` ${g.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,Jl=80;function $E(t){let e=[kE];t.target?(e.push(Sn(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(xE(`visibility: ${t.target.visibility}`)),e.push(Hi("visibility: admin"))):e.push(Sn(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(Sn("title, slug, evidence: untouched")),e.push(Sn("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(Sn("turbobase.document \xB7 new")),e.push(Hi(`title: ${t.pageTitle}`)),e.push(Hi("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(Sn('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(Sn('appended under "## From app developers":'));let r=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
2144
+ `);for(let n of r.slice(0,Jl))e.push(Hi(n?` ${n}`:""));return r.length>Jl&&e.push(g.yellow(` \u2026 ${r.length-Jl} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function SE(t,e={}){let r=[];return t.forEach((n,o)=>{let{target:s,entries:i}=n;if(r.push(`${String(o+1).padStart(2)}. ${g.bold(n.pageTitle)}`),r.push(Tr("page",s?`${s.title} (${s.slug}) [${s.visibility}]`:g.dim("new \u2014 no existing page matches"))),r.push(Tr("action",so(n)?vE[n.action]:g.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(Tr("unresolved",g.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(Tr("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?` ${g.dim(`\xB7 ${a.verdict}`)}`:"",l=a.kb_page_ref?` ${g.dim(`(${a.kb_page_ref})`)}`:"";r.push(` ${g.dim("\xB7")} ${a.title.trim()}${l}${c}`)}),r.push(Tr("confidence",n.withdraws?g.red("WITHDRAWN from readers (text untouched)"):g.dim("untouched"))),n.supersedes&&r.push(Tr("supersedes",g.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(Tr("blocked",g.red(`unpublished work on this page belongs to ${hy(n.blockedBy)} \u2014 this page will be SKIPPED`))),n.alsoMatched.length>0&&r.push(Tr("ambiguous",g.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(Tr("similar",g.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&&so(n)&&r.push(...$E(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(so)} page(s)`,`${e(l=>l.action==="update_page"&&so(l))} appended`,`${e(l=>l.action==="new_page"&&so(l))} created (unpublished)`,...s>0?[g.red(`${s} SKIPPED \u2014 correction with no page to correct`)]:[]],a=n>0?g.red(`${n} page(s) WITHDRAWN from readers`):g.dim("no page withdrawn"),c=o>0?` \xB7 ${g.red(`${o} page(s) BLOCKED by another editor`)}`:"";return`${i.join(" \xB7 ")} \xB7 ${a}${c}`}function EE(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(`${g.yellow("skipped")} ${i} \u2014 unpublished work belongs to ${o.blockedBy?hy(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(`${g.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(`${g.yellow("skipped")} ${i} \u2014 ${o.skipped.replace(/_/g," ")}`);continue}let a=o.created?g.green("created "):g.green("appended");n.push(`${a} ${i} \u2014 ${o.appliedEntryIds.length} finding(s) \u2192 page ${g.bold(o.documentId??"?")}`+(o.created?g.dim(" (unpublished)"):"")),o.confidence==="downgraded"?n.push(` ${g.red("withdrawn from readers:")} ${i}`):o.confidence==="already_withdrawn"?n.push(` ${g.dim("page was already unpublished \u2014 left as is")}`):o.confidence==="missing"&&n.push(` ${g.yellow("page vanished between plan and push \u2014 nothing withdrawn")}`)}return n}function fy(t){if(t instanceof pe){let e=t.body;t.status===403&&e?.reason==="admin_required"&&v("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&&v("this instance does not serve /v1/learnings \u2014 it predates the app-developer learning loop. Ask for an instance upgrade.")}oe(t,"extensions:deploy","learnings push-kb")}async function cs(t,e){let r;try{r=await ie("re-reading pushed markdown",()=>t.learningsIngest(e))}catch(o){return o instanceof pe&&o.status===404?B(g.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`.")):B(g.yellow(`could not re-read the pushed markdown: ${RE(o)} \u2014 planning anyway.`)),null}if(r.filesScanned===0)return B(g.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(g.yellow(`${r.parseSkipped} unparseable`)),B(g.dim(n.join(" \xB7 "))),r}function RE(t){return t instanceof Error?t.message:String(t)}async function my(t,e=r=>new X(r)){t.section&&!as.includes(t.section.trim())&&v(`unknown --section "${t.section}" \u2014 expected one of ${as.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&v("--limit must be a positive integer.");let r=await re(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 cs(n,t.app),i;try{i=await ie("reading the pending queue",()=>n.learningsPending(o))}catch(l){fy(l),v(`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){B(`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}B(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(x(SE(i.items,{diff:_E(t)}).join(`
2145
+ `)),x(TE(i.items)),t.dryRun){B(g.dim("dry run \u2014 nothing was written."));return}let a=i.items.filter(so);if(a.length===0){B(g.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(!ht()){B(g.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 mt(`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"){B("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{let l=await ie("writing pages",()=>n.learningsPushKb(i.planToken,o));x(EE(l.applied,i.items).join(`
2146
+ `))}catch(l){if(l instanceof pe&&l.status===409){B(g.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),B(`re-run \`${is} kb push\` to review the current plan.`),process.exitCode=2;return}fy(l),B(g.red(`turbobase: ${l instanceof Error?l.message:String(l)}`)),process.exitCode=2}}$r();var io=t=>new X(t);async function ao(t,e){let r=await re(t.baseUrl);return e(r)}async function Ki(t,e,r,n){return n.yes?!0:ht()?await mt(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(B("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(B(g.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function PE(t){return t.visibility!=="published"?g.dim("draft"):t.in_current_release?g.green("live"):g.yellow("unreleased")}function gy(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function AE(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(`${gy(g.bold(s.slug),e)} ${gy(PE(s),10)} ${g.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 yy(t,e=io){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&v(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await ao(t,e),o;try{o=await ie("reading the knowledge base",()=>n.docsList(r))}catch(s){oe(s,"docs:publish","read the knowledge base"),v(`could not read the knowledge base: ${s instanceof Error?s.message:String(s)}`)}x(AE(o).join(`
2147
+ `))}async function by(t,e,r=io){let n=[...new Set(t.map(c=>c.trim()).filter(Boolean))];n.length===0&&v("name at least one page slug. `turbobase kb list` shows them.");let o=await ao(e,r);if(!await Ki(`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 ie("publishing",()=>o.docsPublish(n))}catch(c){oe(c,"docs:publish","publish a page"),v(`publish failed: ${c instanceof Error?c.message:String(c)}`)}let a=i.published.map(c=>c.slug);x(g.green(`published ${a.length} page(s) \u2014 readable now.`)),i.missing.length>0&&(B(g.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1),B(g.dim(`undo with: turbobase kb unpublish ${a.join(" ")}`))}async function wy(t,e,r=io){let n=[...new Set(t.map(c=>c.trim()).filter(Boolean))];n.length===0&&v("name at least one page slug. `turbobase kb list` shows them.");let o=await ao(e,r);if(!await Ki(`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 ie("unpublishing",()=>o.docsUnpublish(n))}catch(c){oe(c,"docs:publish","unpublish a page"),v(`unpublish failed: ${c instanceof Error?c.message:String(c)}`)}let a=i.unpublished.map(c=>c.slug);x(g.green(`unpublished ${a.length} page(s) \u2014 retracted now.`)),B(g.dim(`re-publish with: turbobase kb publish ${a.join(" ")}`)),i.missing.length>0&&(B(g.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1)}async function _y(t,e=io){let r=await ao(t,e),n;try{n=await ie("reading the releases",()=>r.docsVersions())}catch(o){oe(o,"docs:publish","read the knowledge-base releases"),v(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){x("no releases yet \u2014 nothing has been published.");return}for(let o of n.items){let s=o.is_current?g.green("current"):g.dim(" ");x(`v${String(o.version_no).padEnd(4)} ${s} ${o.published_at} ${o.node_count} page(s)${o.published_by?` ${g.dim(o.published_by)}`:""}`),o.release_note&&x(` ${g.dim(o.release_note)}`)}}async function vy(t,e,r=io){let n=Number(t);(!Number.isInteger(n)||n<1)&&v(`version must be a release number (got '${t}'). \`turbobase kb versions\` lists them.`);let o=await ao(e,r);if(await Ki(`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 ie("rolling back",()=>o.docsRollback(n));x(g.green(`rolled back \u2014 release v${i.version.version_no} is current.`))}catch(i){oe(i,"docs:publish","roll the knowledge base back"),v(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function xy(t,e,r=io){let n=(t??"").trim();n||v("name the page slug to delete. `turbobase kb list` shows them.");let o=await ao(e,r);if(await Ki(`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 ie("deleting",()=>o.docsDelete(n));x(g.green(`deleted ${i.deleted} \u2014 restorable from the knowledge-base trash.`))}catch(i){oe(i,"docs:publish","delete a page"),v(`delete failed: ${i instanceof Error?i.message:String(i)}`)}}$r();function IE(t){return t.diff??!!t.dryRun}function OE(t,e){let r=[];return t.forEach((n,o)=>{let s=n.action==="new_rule"?g.green("new rule"):g.yellow("amend rule"),i=n.targetPublished?` ${g.yellow("[currently live]")}`:"";r.push(`${o+1}. ${s} ${g.bold(n.slug)}${i}`),r.push(` ${n.name}`),n.description&&r.push(` ${g.dim(n.description)}`);for(let a of n.entries)r.push(` ${g.dim("\xB7")} ${g.dim(a.app_slug)} ${a.title}`);if(e.diff){r.push("");for(let a of n.bodyMarkdown.split(`
2148
+ `))r.push(` ${g.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(g.yellow(`${r} amend a rule that is currently live`)),n.join(" \xB7 ")}async function ky(t,e=r=>new X(r)){t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&v("--limit must be a positive integer.");let r=await re(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 cs(n,t.app),i;try{i=await ie("reading the pending rules",()=>n.rulesPending(o))}catch(c){oe(c,"extensions:deploy","read the pending rules"),v(`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){B(`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}B(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(x(OE(i.items,{diff:IE(t)}).join(`
2149
+ `)),x(CE(i.items)),t.dryRun){B(g.dim("dry run \u2014 nothing was written."));return}let a=i.items.reduce((c,l)=>c+l.entries.length,0);if(!t.yes){if(!ht()){B(g.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 mt(`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"){B("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{await ie("writing the rules",()=>n.rulesPush(i.planToken,o))}catch(c){c instanceof pe&&c.status===409&&v("the pending queue changed while you were reading the plan \u2014 nothing was written. Re-run to see the new plan."),v(`push failed: ${c instanceof Error?c.message:String(c)}`)}x(g.green(`wrote ${i.items.length} draft rule(s).`)),B(g.dim("They are DRAFT \u2014 nothing is injected yet. An admin reviews and publishes them under Settings \u203A Skills."))}$r();var zE=["proposed","active","rejected"],NE=["mechanic","operator","learning","code-baseline"],Gi=t=>new X(t);async function Wi(t,e){let r=await re(t.baseUrl);return e(r)}function $y(t,e,r){if(!t)return;let n=t.split(",").map(o=>o.trim()).filter(o=>o.length>0);if(n.length!==0){for(let o of n)e.includes(o)||v(`${r}: unknown value '${o}' \u2014 expected one of ${e.join(", ")}.`);return n}}function jE(t){if(t===void 0)return;let e=Number(t);return(!Number.isFinite(e)||e<=0)&&v("--limit must be a positive number."),Math.floor(e)}function Ey(t){let e=$y(t.status,zE,"--status"),r=$y(t.provenance,NE,"--provenance"),n=jE(t.limit);return{...e?{status:e}:{},...r?{provenance:r}:{},...t.recordType?{recordType:t.recordType}:{},...t.source?{source:t.source}:{},...n?{limit:n}:{}}}function Sy(t){return!!(t.provenance?.length||t.recordType||t.source)}var Ry=["ID","STATUS","PROVENANCE","RECORD","EVENT","SOURCE","EVIDENCE","ENFORCES"];function LE(t){return t.status==="active"?g.green("active"):t.status==="rejected"?g.dim("rejected"):g.yellow("proposed")}function DE(t){return t.message?t.message:t.kind&&t.field?g.dim(`${t.kind} ${t.field}`):t.kind?g.dim(t.kind):g.dim("(no description)")}function Py(t){return[t.hookId,LE(t),t.provenance==="learning"?g.yellow(t.provenance):t.provenance,t.recordType,t.event,t.source,String(t.taughtBy.length),DE(t)]}async function Ay(t={},e=Gi){let r=await Wi(t,e),n=Ey(t),o;try{o=await r.proposals(n)}catch(i){oe(i,"extensions:deploy","list hook proposals"),v(`list hook proposals failed: ${i instanceof Error?i.message:String(i)}`)}if(t.json)return x(JSON.stringify(o,null,2));if(o.length===0){let i=n.status?.length?n.status.join("/"):"proposed";return x(`no ${i} hook proposals.
2150
+ `+g.dim(" the Mechanic stages one when a sync failure teaches a repeatable invariant."))}x(Xt(o.map(Py),{head:Ry})),x(g.dim(" EVIDENCE = distinct sync failures that taught the rule. Arm one with `turbobase ext proposals promote <id>`."));let s=o.filter(i=>i.provenance==="learning"&&i.status==="proposed");s.length>0&&x(g.dim(` ${s.length} learning-provenance row(s) shown \u2014 those are armed through sign-off in the console, not from here.`))}async function ME(t,e,r){return r.yes?!0:ht()?await mt(t,[{value:"yes",label:e},{value:"no",label:"No \u2014 leave them alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(B("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(B(g.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function UE(t){return!(t instanceof pe)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function Yl(t,e){UE(t)&&oe(t,"extensions:deploy",e)}function Xl(t,e){let r=e instanceof pe?e.body:void 0,n=r?.error==="forbidden"?r.reason??r.error:r?.error,s=n?{learning_requires_signoff:"learning-provenance rows are armed through sign-off in the console, not from the CLI",provenance_unverified:"the instance could not read the row back \u2014 refused rather than guessed",system_reserved:"a managed-service guardrail \u2014 contact support to adjust its feature flag",not_found:"no hook proposal with that id",wrong_kind:"that id is not a hook (conduits have their own review surface)",admin_required:"the PAT resolves to a non-admin user on this instance"}[n]??n:e instanceof Error?e.message:String(e);B(Ve.error(`${g.bold(t)} \u2014 ${s}`))}async function Ty(t,e){try{let r=await t.proposalPromote(e);return x(Ve.success(`${g.bold(e)} ${g.dim(`${r.previousStatus} \u2192`)} ${g.green(r.status)}`)),!0}catch(r){return Yl(r,"promote a hook proposal"),Xl(e,r),!1}}async function Iy(t,e={},r=Gi){!e.auto&&t.length===0&&v("promote: name at least one proposal id, or pass --auto with a filter."),e.auto&&t.length>0&&v("promote: pass ids OR --auto, not both \u2014 --auto selects by filter."),!e.auto&&(e.apply||e.all)&&v("promote: --apply / --all only mean something with --auto.");let n=await Wi(e,r);if(!e.auto){let u=0;for(let d of t)await Ty(n,d)&&(u+=1);u>0&&x(g.dim(` ${u} hook(s) armed \u2014 the loader compiles them on its next reload.`)),u<t.length&&(process.exitCode=1);return}let o=Ey({...e,status:e.status??"proposed"});o.provenance?.includes("learning")&&v("promote --auto: learning-provenance proposals are armed through sign-off in the console, not from the CLI. Drop `learning` from --provenance."),o.status?.some(u=>u!=="proposed")&&v("promote --auto: only `--status proposed` rows can be armed in bulk.");let s;try{s=await n.proposals(o)}catch(u){oe(u,"extensions:deploy","list hook proposals"),v(`list hook proposals failed: ${u instanceof Error?u.message:String(u)}`)}let i=s.filter(u=>u.provenance==="learning"),a=s.filter(u=>u.provenance!=="learning");if(e.json&&(x(JSON.stringify({apply:!!e.apply,plan:a,skipped:i},null,2)),!e.apply))return;if(a.length===0){e.json||(x(`nothing to promote${Sy(o)?" for that filter":""}.`),i.length>0&&x(g.dim(` ${i.length} learning-provenance row(s) skipped \u2014 they need sign-off.`)));return}if(e.json||(x(e.apply?`promoting ${g.bold(String(a.length))} hook proposal(s):`:`${g.bold("dry run")} \u2014 would promote ${g.bold(String(a.length))} hook proposal(s):`),x(Xt(a.map(Py),{head:Ry})),i.length>0&&x(g.dim(` ${i.length} learning-provenance row(s) skipped \u2014 armed through sign-off in the console.`))),!e.apply){x(""),x(Ve.info("nothing was changed. Re-run with --apply to arm these."));return}if(!Sy(o)&&!e.all&&v(`promote --auto --apply with no filter would arm all ${a.length} proposal(s) in the queue. Narrow it with --provenance / --record-type / --source, or pass --all to mean it.`),!await ME(`Arm ${a.length} hook proposal(s)? They start rejecting writes on the next loader reload.`,`Yes \u2014 promote ${a.length}`,e))return;let l=0;for(let u of a)await Ty(n,u.hookId)&&(l+=1);x(g.dim(` ${l}/${a.length} armed \u2014 the loader compiles them on its next reload. Undo one with \`turbobase ext proposals retract <id>\`.`)),l<a.length&&(process.exitCode=1)}async function Oy(t,e={},r=Gi){t.length===0&&v("retract: name at least one proposal id.");let n=await Wi(e,r),o=0;for(let s of t)try{let i=await n.proposalRetract(s);x(Ve.success(`${g.bold(s)} ${g.dim(`${i.previousStatus} \u2192`)} ${g.yellow(i.status)}`)),o+=1}catch(i){Yl(i,"retract a hook proposal"),Xl(s,i)}o>0&&x(g.dim(" source kept \u2014 re-arm with `turbobase ext proposals promote <id>`.")),o<t.length&&(process.exitCode=1)}async function Cy(t,e={},r=Gi){t.length===0&&v("reject: name at least one proposal id.");let n=await Wi(e,r),o=0;for(let s of t)try{let i=await n.proposalReject(s,e.reason);x(Ve.success(`${g.bold(s)} ${g.dim(`${i.previousStatus} \u2192`)} ${g.dim(i.status)}`)),o+=1}catch(i){Yl(i,"reject a hook proposal"),Xl(s,i)}o<t.length&&(process.exitCode=1)}$r();var co=t=>new X(t);async function lo(t,e){let r=await re(t.baseUrl);return e(r)}async function Ji(t,e,r,n){return n.yes?!0:ht()?await mt(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(B("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(B(g.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function ZE(t){return t.visibility!=="published"?g.dim("draft"):t.in_current_release?g.green("live"):g.yellow("unreleased")}function zy(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function qE(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(`${zy(g.bold(s.slug),e)} ${zy(ZE(s),10)} ${s.surfaces.join(",")||g.dim("none")}`),s.description&&r.push(` ${g.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 Ny(t,e=co){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&v(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await lo(t,e),o;try{o=await ie("reading the skills",()=>n.skillsList(r))}catch(s){oe(s,"skills:publish","read the instance skills"),v(`could not read the skills: ${s instanceof Error?s.message:String(s)}`)}x(qE(o).join(`
2151
+ `))}async function jy(t,e,r=co){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&v("name at least one skill slug. `turbobase skills list` shows them.");let o=await lo(e,r);if(!await Ji(`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 ie("publishing",()=>o.skillsPublish(n))}catch(a){oe(a,"skills:publish","publish a skill"),v(`publish failed: ${a instanceof Error?a.message:String(a)}`)}x(g.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(B(g.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),B(g.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function Ly(t,e,r=co){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&v("name at least one skill slug. `turbobase skills list` shows them.");let o=await lo(e,r);if(!await Ji(`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 ie("unpublishing",()=>o.skillsUnpublish(n))}catch(a){oe(a,"skills:publish","unpublish a skill"),v(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}x(g.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),B(g.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(B(g.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function Dy(t,e,r=co){let n=Number(t);(!Number.isInteger(n)||n<1)&&v(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let o=await lo(e,r);if(await Ji(`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 ie("rolling back",()=>o.skillsRollback(n));x(g.green(`rolled back to v${i.version.version_no}.`))}catch(i){oe(i,"skills:publish","roll back a skills release"),v(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function My(t,e=co){let r=await lo(t,e),n;try{n=await ie("reading the releases",()=>r.skillsReleases())}catch(o){oe(o,"skills:publish","read the skills releases"),v(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){B("no releases yet.");return}for(let o of n.items){let s=o.is_current?g.green("*"):" ",i=o.release_note?` \u2014 ${o.release_note}`:"";x(`${s} v${o.version_no} ${o.skill_count} skill(s) ${g.dim(o.published_at)}${o.published_by?g.dim(` by ${o.published_by}`):""}${g.dim(i)}`)}}async function Uy(t,e,r=co){let n=[...new Set((t??[]).map(l=>l.trim()).filter(Boolean))];n.length===0&&v("name at least one skill to delete. `turbobase skills list` shows the slugs.");let o=await lo(e,r);if(!await Ji(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
1960
2152
  ${n.join(`
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 ge&&u.status===404){a.push(l);continue}i.length>0&&H(w.dim(`deleted before the error: ${i.map(d=>d.slug).join(", ")}`)),ce(u,"skills:publish","delete a skill"),x(`delete failed on '${l}': ${u instanceof Error?u.message:String(u)}`)}i.length>0&&S(w.green(`deleted ${i.length} skill(s).`));let c=i.filter(l=>l.wasPublished).map(l=>l.slug);c.length>0&&H(w.yellow(`Published until now, so no longer injected: ${c.join(", ")}`)),a.length>0&&(H(w.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as ky}from"node:fs";import{join as mE,relative as gE,resolve as yE,sep as bE}from"node:path";var wE=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),_E=new Set([".mcp.json",".env"]);function vE(t){return _E.has(t)||t.startsWith(".env.")&&t!==".env.example"}function xE(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function kE(t){return t.includes(0)}async function $y(t){let e=yE(t),r={},n=[],o=[],s=[];async function i(a){let c=await ky.readdir(a,{withFileTypes:!0});for(let l of c){let u=mE(a,l.name);if(l.isDirectory()){if(wE.has(l.name))continue;await i(u);continue}if(!l.isFile())continue;let d=gE(e,u).split(bE).join("/");if(vE(l.name)){o.push(d);continue}let b=await ky.readFile(u);if(!xE(b)){n.push(d);continue}kE(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 SE="/_tb/app-assets",TE=16,EE=/^[0-9a-f]{32}$/;function Sy(){return $E(TE).toString("hex")}function RE(t){return EE.test(t)}function Ty(t){if(!RE(t))throw new Error(`not a build id: ${t}`);return`${SE}/${t}/`}var Ey=7;import Hi from"node:fs/promises";import cs from"node:path";var Vl={esbuild:"0.28.1","isolated-vm":"6.1.2"},Hl="@turbobase/isolated-vm-prebuilds";function Kl(t,e){return`${t}-${e}`}function Gl(t=process.versions){return`abi${t.modules}`}var Ry=["darwin-x64","win32-arm64"];async function Py(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=Kl(e,r),o=cs.join(t.home,"node_modules"),s=cs.join(o,...Hl.split("/"),"prebuilds",n),i=cs.join(o,"isolated-vm","prebuilds",n),a;try{a=await Hi.readdir(s)}catch{return[]}let c=[];await Hi.mkdir(i,{recursive:!0});for(let l of a){if(!l.endsWith(".node"))continue;let u=cs.join(i,l);try{await Hi.copyFile(cs.join(s,l),u,Hi.constants?.COPYFILE_EXCL??1),c.push(l)}catch{}}return c}import{homedir as PE}from"node:os";import{join as Ay}from"node:path";import{promises as Wl}from"node:fs";function Oy(){let t=process.env.TURBOBASE_HOME??Ay(PE(),".turbobase");return{dir:t,file:Ay(t,"sandboxes.json")}}var AE={s:1e3,m:6e4,h:36e5,d:864e5};function IE(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*AE[e[2]]}function OE(t,e=Date.now()){return new Date(e+IE(t)).toISOString()}function CE(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function zE(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 NE(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 jE="[REDACTED]",ls=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},Jl=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 LE(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new Jl(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:jE:n[o]=s}return n}function DE(t,e,r){return e.map(n=>LE(t,n,r))}var Iy=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),ME=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function UE(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 Yl(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 ME)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=UE(t);if(!Iy.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...Iy].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function ZE(t,e=qE){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function qE(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function FE(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function BE(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function Xl(){let{file:t}=Oy();try{let e=await Wl.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function Cy(t){let{dir:e,file:r}=Oy();await Wl.mkdir(e,{recursive:!0}),await Wl.writeFile(r,`${JSON.stringify(t,null,2)}
1962
- `,{mode:384})}async function VE(t){let e=await Xl();e.push(t),await Cy(e)}async function zy(t){let e=await Xl(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Cy(e),n??null}async function Ki(){return Xl()}function Ql(t,e=Date.now()){let r=[],n=[];for(let o of t)CE(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function Ny(t,e){Yl(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new ls(r);let n=zE(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>ZE(l)))(e.fromTenant),i=FE(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=NE(l.rows,n),d=DE(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:OE(e.ttl,o),sampleFraction:n,url:BE(s,e.baseUrl)};return await VE(c),c}async function jy(t,e){Yl(t.target());let n=(await Ki()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await zy(e),n):null}async function eu(t,e=Date.now()){Yl(t.target());let r=await Ki(),{expired:n}=Ql(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await zy(s.name),o.push(s)}return o}var us={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"}},WU=Object.keys(us).filter(t=>us[t].mintable);var XU=us.pat.prefix,HE=Object.entries(us).map(([t,e])=>[e.prefix,t]),KE=/^[A-Za-z0-9_-]{20,}$/;function GE(t){if(typeof t!="string")return null;for(let[e,r]of HE)if(t.startsWith(e)&&KE.test(t.slice(e.length)))return r;return null}function Ly(t){return GE(t)==="pat"}var ds="bundle.json",Gi="turbobase";function My(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 WE(a)}function WE(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(Dy)),tables:[...t.sync.tables].sort(e(r=>r.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(Dy)),conduits:[...t.guardrails.conduits].sort(e(r=>r.conduitId))},schedules:[...t.schedules].sort(e(r=>r.name))}}function Dy(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function Uy(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}")`}}Qo();var JE=8e3,YE={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 XE(t){return YE[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function QE(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(JE)})}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 Zy(t){return t.state==="accepted"?Xe()?w.green("accepted"):"accepted":t.state==="rejected"?Xe()?w.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Xe()?w.yellow("unreachable"):"unreachable"}async function qy(t={},e=fetch){let r=await xr(),{file:n}=Ni();if(r.length===0){S("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),H(w.dim(`no sign-ins stored in ${n}.`));return}let o=await Jt(),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 QE(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)S(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Xe())S(Zr(s.map(i=>[i.active?w.green("*"):" ",w.bold(i.baseUrl),Zy(i.check),w.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)S(`${i.active?"* ":" "}${i.baseUrl} ${Zy(i.check)} (updated ${i.updatedAt})`);H(w.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(H(w.red(`${i.baseUrl}: ${XE(i.check.reason)}.`)),H(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"&&H(w.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||H("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function kL(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 xr();e.length===0&&x("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Rt()||x("this command needs an explicit <base-url> in a non-interactive shell.");try{return await Pt(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{x("cancelled.")}}async function SL(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 TL(t){H(""),H("Sharing is ON. Two things reach the Turbobase product team from this instance:"),H(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),H(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),H(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),H(" about OUR platform, with instance name, user names and ids masked before they leave."),H(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),H("")}async function EL(t,e,r){let n=await bg({baseUrl:t,token:e}),o=(await xr()).length-1;if(S(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),TL(n.baseUrl),!r)return;let s=await SL(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(H(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),H(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),H(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?H(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):H(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function RL(t){let e=await ns(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)&&x(`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)&&x(`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 Uo(t,e,r,n){try{return await ye.access(t),"skipped"}catch{}return await ye.mkdir(Mo(t),{recursive:!0}),await ye.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await ye.chmod(t,n),"wrote"}async function z$(t,e){if(N$(t)!==".gitignore")return Uo(t,e.content,e.executable,e.mode);let r=await ye.readFile(t,"utf8").catch(()=>null);if(r===null)return Uo(t,e.content,e.executable,e.mode);let n=Yg(r);return n===null?"skipped":(await ye.writeFile(t,n,"utf8"),"merged")}function gm(t){if(t!==void 0){if(t==="junit"||t==="json")return t;x(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function PL(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 AL(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 IL(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 xm({includeInternal:t=!0}={}){let e=new Zm;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.1.19").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",p=>p.command.parent?"":`${jl()}
1963
- `),e.hook("preAction",(p,h)=>{ty(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=jt(p.baseUrl);p.token||x(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
1964
- ${ss} auth login --base-url ${h} --token tb_pat_\u2026`),Ly(p.token)||x("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await EL(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=>qy({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 ji(h);if(!_){let $=await xr();x(`no stored sign-in for ${jt(h)}.`+($.length?` Stored: ${$.map(k=>k.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${jt(h)} --token tb_pat_\u2026\`.`)}S(`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 $=await xr();for(let k of $)await Sl(k.baseUrl);S(`removed ${$.length} stored sign-in${$.length===1?"":"s"}.`);return}let h=await Sl(p.baseUrl);h||x(p.baseUrl?`no stored sign-in for ${jt(p.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let _=await Jt();S(`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),$;try{$=await Lr({baseUrl:h,token:_,recordsOnly:p.recordsOnly})}catch(g){let T=g instanceof Error?g.message:String(g);if(!p.recordsOnly&&/openapi\.json failed \(401/.test(T)){let R=await kL(h,_);if(R)try{$=await Lr({baseUrl:h,token:R,recordsOnly:!1});let C=$e(process.cwd(),p.out);await ye.writeFile(C,$,"utf8"),S(`wrote ${C} (${$.split(`
1965
- `).length} lines).`);return}catch{}H("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 Lr({baseUrl:h,token:_,recordsOnly:!0})}catch(C){x(`types generation failed: ${C instanceof Error?C.message:String(C)}`)}}else x(`types generation failed: ${T}`)}let k=$e(process.cwd(),p.out);await ye.writeFile(k,$,"utf8"),S(`wrote ${k} (${$.split(`
1966
- `).length} lines).`)}),oy(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),$=new URLSearchParams;p.records&&$.set("records",p.records),p.query&&$.set("query",p.query);let k=$.toString(),g=await fetch(`${h}/v1/catalog/grounding${k?`?${k}`:""}`,{headers:{Authorization:`Bearer ${_}`,Accept:"application/json"}});g.ok||x(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${g.status}`);let R=((await g.json()).markdown??"").trim(),C=$e(process.cwd(),p.out),D=p.records?` records=${p.records}`:"",U=`<!-- GENERATED by \`turbobase project grounding\` against ${h}${D} \u2014 do not edit; re-run to refresh. -->
2153
+ `)}`,"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 ie(`deleting ${l}`,()=>o.skillsDelete(l)))}catch(u){if(u instanceof pe&&u.status===404){a.push(l);continue}i.length>0&&B(g.dim(`deleted before the error: ${i.map(d=>d.slug).join(", ")}`)),oe(u,"skills:publish","delete a skill"),v(`delete failed on '${l}': ${u instanceof Error?u.message:String(u)}`)}i.length>0&&x(g.green(`deleted ${i.length} skill(s).`));let c=i.filter(l=>l.wasPublished).map(l=>l.slug);c.length>0&&B(g.yellow(`Published until now, so no longer injected: ${c.join(", ")}`)),a.length>0&&(B(g.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as Zy}from"node:fs";import{join as FE,relative as BE,resolve as VE,sep as HE}from"node:path";var KE=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),GE=new Set([".mcp.json",".env"]);function WE(t){return GE.has(t)||t.startsWith(".env.")&&t!==".env.example"}function JE(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function YE(t){return t.includes(0)}async function qy(t){let e=VE(t),r={},n=[],o=[],s=[];async function i(a){let c=await Zy.readdir(a,{withFileTypes:!0});for(let l of c){let u=FE(a,l.name);if(l.isDirectory()){if(KE.has(l.name))continue;await i(u);continue}if(!l.isFile())continue;let d=BE(e,u).split(HE).join("/");if(WE(l.name)){o.push(d);continue}let w=await Zy.readFile(u);if(!JE(w)){n.push(d);continue}YE(w)&&s.push(d),r[d]=w.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as XE}from"node:crypto";var QE="/_tb/app-assets",eR=16,tR=/^[0-9a-f]{32}$/;function Fy(){return XE(eR).toString("hex")}function rR(t){return tR.test(t)}function By(t){if(!rR(t))throw new Error(`not a build id: ${t}`);return`${QE}/${t}/`}var Vy=7;import Yi from"node:fs/promises";import ls from"node:path";var Ql={esbuild:"0.28.1","isolated-vm":"6.1.2"},eu="@turbobase/isolated-vm-prebuilds";function tu(t,e){return`${t}-${e}`}function ru(t=process.versions){return`abi${t.modules}`}var Hy=["darwin-x64","win32-arm64"];async function Ky(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=tu(e,r),o=ls.join(t.home,"node_modules"),s=ls.join(o,...eu.split("/"),"prebuilds",n),i=ls.join(o,"isolated-vm","prebuilds",n),a;try{a=await Yi.readdir(s)}catch{return[]}let c=[];await Yi.mkdir(i,{recursive:!0});for(let l of a){if(!l.endsWith(".node"))continue;let u=ls.join(i,l);try{await Yi.copyFile(ls.join(s,l),u,Yi.constants?.COPYFILE_EXCL??1),c.push(l)}catch{}}return c}import{homedir as nR}from"node:os";import{join as Gy}from"node:path";import{promises as nu}from"node:fs";function Jy(){let t=process.env.TURBOBASE_HOME??Gy(nR(),".turbobase");return{dir:t,file:Gy(t,"sandboxes.json")}}var oR={s:1e3,m:6e4,h:36e5,d:864e5};function sR(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*oR[e[2]]}function iR(t,e=Date.now()){return new Date(e+sR(t)).toISOString()}function aR(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function cR(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 lR(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 uR="[REDACTED]",us=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},ou=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 dR(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new ou(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:uR:n[o]=s}return n}function pR(t,e,r){return e.map(n=>dR(t,n,r))}var Wy=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),fR=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function hR(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 su(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 fR)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=hR(t);if(!Wy.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...Wy].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function mR(t,e=gR){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function gR(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function yR(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function bR(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function iu(){let{file:t}=Jy();try{let e=await nu.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function Yy(t){let{dir:e,file:r}=Jy();await nu.mkdir(e,{recursive:!0}),await nu.writeFile(r,`${JSON.stringify(t,null,2)}
2154
+ `,{mode:384})}async function wR(t){let e=await iu();e.push(t),await Yy(e)}async function Xy(t){let e=await iu(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Yy(e),n??null}async function Xi(){return iu()}function au(t,e=Date.now()){let r=[],n=[];for(let o of t)aR(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function Qy(t,e){su(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new us(r);let n=cR(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>mR(l)))(e.fromTenant),i=yR(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=lR(l.rows,n),d=pR(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:iR(e.ttl,o),sampleFraction:n,url:bR(s,e.baseUrl)};return await wR(c),c}async function eb(t,e){su(t.target());let n=(await Xi()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await Xy(e),n):null}async function cu(t,e=Date.now()){su(t.target());let r=await Xi(),{expired:n}=au(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await Xy(s.name),o.push(s)}return o}var ds={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"}},RZ=Object.keys(ds).filter(t=>ds[t].mintable);var IZ=ds.pat.prefix,_R=Object.entries(ds).map(([t,e])=>[e.prefix,t]),vR=/^[A-Za-z0-9_-]{20,}$/;function xR(t){if(typeof t!="string")return null;for(let[e,r]of _R)if(t.startsWith(e)&&vR.test(t.slice(e.length)))return r;return null}function tb(t){return xR(t)==="pat"}var ps="bundle.json",Qi="turbobase";function nb(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 kR(a)}function kR(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(rb)),tables:[...t.sync.tables].sort(e(r=>r.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(rb)),conduits:[...t.guardrails.conduits].sort(e(r=>r.conduitId))},schedules:[...t.schedules].sort(e(r=>r.name))}}function rb(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function ob(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}")`}}es();var $R=8e3,SR={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 TR(t){return SR[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function ER(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($R)})}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 sb(t){return t.state==="accepted"?Qe()?g.green("accepted"):"accepted":t.state==="rejected"?Qe()?g.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Qe()?g.yellow("unreachable"):"unreachable"}async function ib(t={},e=fetch){let r=await kr(),{file:n}=Li();if(r.length===0){x("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),B(g.dim(`no sign-ins stored in ${n}.`));return}let o=await Yt(),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 ER(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)x(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Qe())x(Xt(s.map(i=>[i.active?g.green("*"):" ",g.bold(i.baseUrl),sb(i.check),g.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)x(`${i.active?"* ":" "}${i.baseUrl} ${sb(i.check)} (updated ${i.updatedAt})`);B(g.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(B(g.red(`${i.baseUrl}: ${TR(i.check.reason)}.`)),B(g.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"&&B(g.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||B("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function YL(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 XL(t){let e=await kr();e.length===0&&v("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),ht()||v("this command needs an explicit <base-url> in a non-interactive shell.");try{return await mt(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{v("cancelled.")}}async function QL(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 eD(t){B(""),B("Sharing is ON. Two things reach the Turbobase product team from this instance:"),B(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),B(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),B(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),B(" about OUR platform, with instance name, user names and ids masked before they leave."),B(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),B("")}async function tD(t,e,r){let n=await Tg({baseUrl:t,token:e}),o=(await kr()).length-1;if(x(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),eD(n.baseUrl),!r)return;let s=await QL(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(B(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),B(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),B(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?B(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):B(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function rD(t){let e=await os(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)&&v(`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)&&v(`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 Zo(t,e,r,n){try{return await ye.access(t),"skipped"}catch{}return await ye.mkdir(Uo(t),{recursive:!0}),await ye.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await ye.chmod(t,n),"wrote"}async function X$(t,e){if(Q$(t)!==".gitignore")return Zo(t,e.content,e.executable,e.mode);let r=await ye.readFile(t,"utf8").catch(()=>null);if(r===null)return Zo(t,e.content,e.executable,e.mode);let n=sy(r);return n===null?"skipped":(await ye.writeFile(t,n,"utf8"),"merged")}function $m(t){if(t!==void 0){if(t==="junit"||t==="json")return t;v(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function Hc(t){process.exit(t)}function nD(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 oD(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 sD(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 Am({includeInternal:t=!0}={}){let e=new Wm;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.1.20").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",p=>p.command.parent?"":`${Fl()}
2155
+ `),e.hook("preAction",(p,h)=>{ly(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=Lt(p.baseUrl);p.token||v(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
2156
+ ${is} auth login --base-url ${h} --token tb_pat_\u2026`),tb(p.token)||v("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await tD(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=>ib({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 XL("Pick the active instance:"),_=await Di(h);if(!_){let S=await kr();v(`no stored sign-in for ${Lt(h)}.`+(S.length?` Stored: ${S.map($=>$.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${Lt(h)} --token tb_pat_\u2026\`.`)}x(`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 S=await kr();for(let $ of S)await Ol($.baseUrl);x(`removed ${S.length} stored sign-in${S.length===1?"":"s"}.`);return}let h=await Ol(p.baseUrl);h||v(p.baseUrl?`no stored sign-in for ${Lt(p.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let _=await Yt();x(`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 re(p.baseUrl),S;try{S=await Ur({baseUrl:h,token:_,recordsOnly:p.recordsOnly})}catch(y){let T=y instanceof Error?y.message:String(y);if(!p.recordsOnly&&/openapi\.json failed \(401/.test(T)){let R=await YL(h,_);if(R)try{S=await Ur({baseUrl:h,token:R,recordsOnly:!1});let C=$e(process.cwd(),p.out);await ye.writeFile(C,S,"utf8"),x(`wrote ${C} (${S.split(`
2157
+ `).length} lines).`);return}catch{}B("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{S=await Ur({baseUrl:h,token:_,recordsOnly:!0})}catch(C){v(`types generation failed: ${C instanceof Error?C.message:String(C)}`)}}else v(`types generation failed: ${T}`)}let $=$e(process.cwd(),p.out);await ye.writeFile($,S,"utf8"),x(`wrote ${$} (${S.split(`
2158
+ `).length} lines).`)}),py(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 re(p.baseUrl),S=new URLSearchParams;p.records&&S.set("records",p.records),p.query&&S.set("query",p.query);let $=S.toString(),y=await fetch(`${h}/v1/catalog/grounding${$?`?${$}`:""}`,{headers:{Authorization:`Bearer ${_}`,Accept:"application/json"}});y.ok||v(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${y.status}`);let R=((await y.json()).markdown??"").trim(),C=$e(process.cwd(),p.out),j=p.records?` records=${p.records}`:"",U=`<!-- GENERATED by \`turbobase project grounding\` against ${h}${j} \u2014 do not edit; re-run to refresh. -->
1967
2159
 
1968
2160
  `;await ye.writeFile(C,U+(R?`${R}
1969
2161
  `:`(no grounding available yet)
1970
- `),"utf8"),S(`wrote ${C}${R?"":" (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 (${is.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=>ay(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=>ly(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)=>uy(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)=>dy(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=>py(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)=>fy(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)=>hy(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=>my(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=>yy(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)=>by(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)=>wy(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=>vy(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)=>_y(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)=>xy(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=no("hook",{recordType:p.record,event:p.event,template:p.template,field:p.field,regex:p.regex,source:p.source,id:p.id})}catch(k){x(k instanceof Error?k.message:String(k))}let _=$e(process.cwd(),h.relativePath);await Uo(_,h.content)==="skipped"&&x(`refusing to overwrite existing file: ${_}`),S(`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=no("conduit",{recordType:p.record,source:p.source,to:p.to,toRecordType:p.toRecord,event:p.event,id:p.id})}catch(k){x(k instanceof Error?k.message:String(k))}let _=$e(process.cwd(),h.relativePath);await Uo(_,h.content)==="skipped"&&x(`refusing to overwrite existing file: ${_}`),S(`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 _=gm(h.reporter),$=await ns($e(process.cwd(),p)),k=$e(process.cwd(),h.samples),g=await rs(k);g.length===0&&!_&&S(`no samples found under ${k} \u2014 add JSON fixtures to dry-run against.`);let T;try{T=await Mi($,g.map(D=>D.fixture))}catch(D){x(`bundle failed: ${D instanceof Error?D.message:String(D)}`)}if(_){let D=PL(T);S(Zi(D,_)),D.cases.some(U=>U.status==="failed")&&process.exit(1);return}let R=0;for(let D of T){let U=D.pass?w.green("PASS"):w.red("FAIL");D.pass||(R+=1);let oe=D.error?` (error: ${D.error})`:D.observed!==D.expected?` (expected ${D.expected}, observed ${D.observed})`:D.rejection?` (rejected: ${D.rejection.code??"rejected"})`:"";S(` ${U} ${D.name}${oe}`)}let C=`${T.length-R}/${T.length} sample(s) passed.`;S(`
1971
- ${R===0?w.green(C):w.yellow(C)}`),R>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 T=await ym(),{baseUrl:R,token:C}=await ne(h.baseUrl),D=new Q({baseUrl:R,token:C});try{let U=await se(`applying bundle to ${h.to}`,()=>D.configApply(T));S(`applied bundle to ${h.to}: +${U.applied.add} ~${U.applied.change} -${U.applied.destroy}`+(U.backfillsQueued.length?` (${U.backfillsQueued.length} backfill(s) queued)`:""))}catch(U){U instanceof ge&&U.status===403&&x("apply forbidden (403) \u2014 the stored PAT is not for an admin."),x(`bundle apply failed: ${U instanceof Error?U.message:String(U)}`)}return}p||x("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:_,token:$}=await ne(h.baseUrl),k=await RL($e(process.cwd(),p)),g=new Q({baseUrl:_,token:$});try{let T=await se(`deploying ${N$(p)}`,()=>g.deploy(k));Xe()?S(Ur("Deployed",[`${w.bold(T.id)} ${ro(T.status)} ${w.dim(T.outcome)}`])):S(`deployed ${T.id} \u2192 status=${T.status} (${T.outcome}).`)}catch(T){T instanceof ge&&T.status===403&&x("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),x(`deploy failed: ${T instanceof Error?T.message:String(T)}`)}});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.").option("--replace [preview-id]","Re-deploy onto an OPEN preview instead of opening a second one \u2014 the URL is unchanged, so whoever holds the link sees the new build. Omit the id when the app has exactly one open preview. Implies --preview.").action(async(p,h,_)=>{let $=!!(_.preview||_.replace),k=$e(process.cwd(),h??".");await ye.mkdir(k,{recursive:!0});let g=_.proposal??await y(k),{baseUrl:T,token:R}=await ne(_.baseUrl),C=new Q({baseUrl:T,token:R}),D=!1;try{D=(await C.appsList()).some(Re=>Re.slug===p||Re.id===p)}catch(Re){ce(Re,"extensions:deploy","deploy"),x(`could not reach ${T}: ${Re instanceof Error?Re.message:String(Re)}`)}if(!D){_.create||x(`no app "${p}" on ${T} \u2014 create it with \`turbobase apps create ${p}\`, or pass --create.`);let Re=await se(`creating app ${p}`,()=>u(T,R,{slug:p},{tolerateExisting:!0}));Re.existed||S(`created ${Re.slug??p}.`)}let U;if(_.replace)if(typeof _.replace=="string")U=_.replace;else{let{previews:Re}=await V(T,R,p);if(Re.length===0&&x(`no open preview on ${p} to replace \u2014 drop --replace to open the first one, or name a handle from \`turbobase apps preview list\`.`),Re.length>1){for(let ct of Re)S(` ${ct.previewId} v${ct.version}${ct.label?` ${ct.label}`:""} ${ct.url}`);x(`${p} has ${Re.length} open previews \u2014 pass the one to replace, e.g. \`--replace ${Re[0].previewId}\`.`)}U=Re[0].previewId}let oe=Re=>ye.stat(Ct(k,Re)).then(()=>!0).catch(()=>!1),M=p,ue=k,Ee=_.build!==!1;if(Ee&&!await oe("package.json"))if(await oe("index.html"))S("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),Ee=!1;else if(_.pull===!1)x(`${k} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let Re=await se(`pulling ${p}`,()=>d(T,R,p));M=Re.slug??p,await b(k,Re.files,!0),S(`pulled generated source (rev ${Re.rev}).`)}let Pe;if(Ee){let Re=Sy();if(Pe={buildId:Re,assetBase:Ty(Re)},_.install!==!1&&!await oe("node_modules")){S("installing dependencies\u2026");try{await E(["install"],k)}catch(ct){x(`npm install failed: ${ct instanceof Error?ct.message:String(ct)}`)}}S("building\u2026");try{await E(["run","build"],k,{TURBOBASE_ASSET_BASE:Pe.assetBase})}catch(ct){x(`build failed: ${ct instanceof Error?ct.message:String(ct)}`)}await oe("dist")||x(`no dist/ after build in ${k} \u2014 check the app's build script.`),ue=Ct(k,"dist")}$&&!Pe&&x(`--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 at=await Y(T,R,M,ue,_.entry,g,Pe,$?{label:_.label,replacePreviewId:U}:void 0);if($){let Re=at.previewUrl??"(no url returned)",ct=at.expiresAt?new Date(at.expiresAt).toLocaleDateString():`${Ey} days`,Fo=at.replacedVersion==null?null:`replaced v${at.replacedVersion} \u2014 same URL`;if(Xe())S(Ur(Fo?"Preview replaced":"Preview deployed",[`${w.bold(M)} ${w.green(`v${at.version??"?"}`)} ${w.dim("not live")}`,`${w.bold(Re)}`,...Fo?[w.dim(Fo)]:[],w.dim(`expires ${ct}`)]));else{let D$=Fo?`; ${Fo}`:"";S(`preview ${M} v${at.version??"?"} \u2192 ${Re} (expires ${ct}; /a/${M} unchanged${D$}).`)}S(`next: turbobase apps promote ${M} ${at.previewId??"<preview-id>"} # make it live`),S(` turbobase apps preview discard ${at.previewId??"<preview-id>"}`);return}Xe()?S(Ur("Deployed",[`${w.bold(M)} ${w.green(`v${at.version??"?"}`)} ${w.dim(at.url??`/a/${M}`)}`])):S(`deployed ${M} \u2192 v${at.version??"?"} (${at.url??`/a/${M}`}).`),await Ke(at,k)}),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:$,token:k}=await ne(_.baseUrl),g=await se(`promoting ${h}`,()=>z($,k,p,"promote",{previewId:h}));Xe()?S(Ur("Promoted",[`${w.bold(p)} ${w.green(`v${g.version??"?"}`)} ${w.dim(g.url??`/a/${p}`)}`])):S(`promoted ${p} \u2192 v${g.version??"?"} is now live at ${g.url??`/a/${p}`}.`),await Ke(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:$}=await ne(h.baseUrl),k=await V(_,$,p);if(k.previews.length===0){S(`no open previews for ${p}.`);return}for(let g of k.previews){let T=g.label?` ${g.label}`:"",R=g.expiresAt?new Date(g.expiresAt).toLocaleDateString():"?";S(`v${g.version} ${g.previewId}${T} ${g.url} (expires ${R})`)}}),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:$,token:k}=await ne(_.baseUrl);await se(`discarding ${h}`,()=>z($,k,p,"discard",{previewId:h})),S(`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:$}=await ne(h.baseUrl),k=await se(`creating ${p}`,()=>u(_,$,{slug:p,name:h.name,description:h.description})),g=k.slug??p;Xe()?S(Ur("Created",[`${w.bold(g)} ${w.dim(k.url??`/a/${g}`)}`])):S(`created ${g} (${k.url??`/a/${g}`}).`),S(`next: turbobase apps push ${g} . # store the source`),S(` turbobase apps deploy ${g} # build + go live`)});async function u(p,h,_,$={}){let k=`${p.replace(/\/+$/,"")}/v1/apps`,g;try{g=await fetch(k,{method:"POST",headers:{Authorization:`Bearer ${h}`,"content-type":"application/json"},body:JSON.stringify({slug:_.slug,name:_.name??_.slug,description:_.description})})}catch(T){x(`create request failed: ${T instanceof Error?T.message:String(T)}`)}if(g.status===401&&x("create unauthorized (401) \u2014 re-run `turbobase auth login`."),g.status===403&&x("create forbidden (403) \u2014 the PAT is not for an admin."),g.status===409){if($.tolerateExisting)return{slug:_.slug,existed:!0};x(`an app with slug "${_.slug}" already exists.`)}return g.ok||x(`create failed: HTTP ${g.status} ${(await g.text().catch(()=>"")).slice(0,200)}`),await g.json().catch(()=>({}))}async function d(p,h,_){let $=`${p.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(_)}/pull`,k;try{k=await fetch($,{headers:{Authorization:`Bearer ${h}`}})}catch(g){x(`pull request failed: ${g instanceof Error?g.message:String(g)}`)}return k.status===401&&x("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),k.status===403&&x("pull forbidden (403) \u2014 the PAT is not for an admin."),k.status===404&&x(`no generated source for "${_}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),k.ok||x(`pull failed: HTTP ${k.status} ${(await k.text().catch(()=>"")).slice(0,200)}`),await k.json()}async function b(p,h,_){let $=$e(p),k=0;for(let[g,T]of Object.entries(h)){let R=$e($,g);R!==$&&!R.startsWith($+_m)&&x(`refusing to write outside ${$}: ${g}`),_||await ye.stat(R).then(()=>!0).catch(()=>!1)&&x(`${R} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await ye.mkdir(Mo(R),{recursive:!0}),await ye.writeFile(R,T,"utf8"),k+=1}return k}function m(p){let h=p.indexOf(","),_=p.startsWith("data:")?h>=0?p.slice(h+1):"":p;if(!_)return null;try{let $=Buffer.from(_,"base64");return $.length>0?new Uint8Array($):null}catch{return null}}async function f(p,h,_){let $=$e(p),k=async(T,R)=>{let C=$e($,T);C!==$&&!C.startsWith($+_m)&&x(`refusing to write outside ${$}: ${T}`),_||await ye.stat(C).then(()=>!0).catch(()=>!1)&&x(`${C} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await ye.mkdir(Mo(C),{recursive:!0}),await ye.writeFile(C,R)},g=`# ${h.title||"App change request"}
2162
+ `),"utf8"),x(`wrote ${C}${R?"":" (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 (${as.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=>my(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=>yy(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)=>by(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)=>wy(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=>_y(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)=>vy(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)=>xy(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=>ky(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=>Ny(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)=>jy(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)=>Ly(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=>My(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)=>Dy(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)=>Uy(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=Br("hook",{recordType:p.record,event:p.event,template:p.template,field:p.field,regex:p.regex,source:p.source,id:p.id})}catch($){v($ instanceof Error?$.message:String($))}let _=$e(process.cwd(),h.relativePath);await Zo(_,h.content)==="skipped"&&v(`refusing to overwrite existing file: ${_}`),x(`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=Br("conduit",{recordType:p.record,source:p.source,to:p.to,toRecordType:p.toRecord,event:p.event,id:p.id})}catch($){v($ instanceof Error?$.message:String($))}let _=$e(process.cwd(),h.relativePath);await Zo(_,h.content)==="skipped"&&v(`refusing to overwrite existing file: ${_}`),x(`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 _=$m(h.reporter),S=await os($e(process.cwd(),p)),$=$e(process.cwd(),h.samples),y=await ns($);y.length===0&&!_&&x(`no samples found under ${$} \u2014 add JSON fixtures to dry-run against.`);let T;try{T=await Zi(S,y.map(j=>j.fixture))}catch(j){v(`bundle failed: ${j instanceof Error?j.message:String(j)}`)}if(_){let j=nD(T);x(Fi(j,_)),Hc(j.cases.some(U=>U.status==="failed")?1:0)}let R=0;for(let j of T){let U=j.pass?g.green("PASS"):g.red("FAIL");j.pass||(R+=1);let se=j.error?` (error: ${j.error})`:j.observed!==j.expected?` (expected ${j.expected}, observed ${j.observed})`:j.rejection?` (rejected: ${j.rejection.code??"rejected"})`:"";x(` ${U} ${j.name}${se}`)}let C=`${T.length-R}/${T.length} sample(s) passed.`;x(`
2163
+ ${R===0?g.green(C):g.yellow(C)}`),Hc(R>0?1:0)}),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 T=await Sm(),{baseUrl:R,token:C}=await re(h.baseUrl),j=new X({baseUrl:R,token:C});try{let U=await ie(`applying bundle to ${h.to}`,()=>j.configApply(T));x(`applied bundle to ${h.to}: +${U.applied.add} ~${U.applied.change} -${U.applied.destroy}`+(U.backfillsQueued.length?` (${U.backfillsQueued.length} backfill(s) queued)`:""))}catch(U){U instanceof pe&&U.status===403&&v("apply forbidden (403) \u2014 the stored PAT is not for an admin."),v(`bundle apply failed: ${U instanceof Error?U.message:String(U)}`)}return}p||v("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:_,token:S}=await re(h.baseUrl),$=await rD($e(process.cwd(),p)),y=new X({baseUrl:_,token:S});try{let T=await ie(`deploying ${Q$(p)}`,()=>y.deploy($));Qe()?x(qr("Deployed",[`${g.bold(T.id)} ${no(T.status)} ${g.dim(T.outcome)}`])):x(`deployed ${T.id} \u2192 status=${T.status} (${T.outcome}).`)}catch(T){T instanceof pe&&T.status===403&&v("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),v(`deploy failed: ${T instanceof Error?T.message:String(T)}`)}});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.").option("--replace [preview-id]","Re-deploy onto an OPEN preview instead of opening a second one \u2014 the URL is unchanged, so whoever holds the link sees the new build. Omit the id when the app has exactly one open preview. Implies --preview.").action(async(p,h,_)=>{let S=!!(_.preview||_.replace),$=$e(process.cwd(),h??".");await ye.mkdir($,{recursive:!0});let y=_.proposal??await b($),{baseUrl:T,token:R}=await re(_.baseUrl),C=new X({baseUrl:T,token:R}),j=!1;try{j=(await C.appsList()).some(Re=>Re.slug===p||Re.id===p)}catch(Re){oe(Re,"extensions:deploy","deploy"),v(`could not reach ${T}: ${Re instanceof Error?Re.message:String(Re)}`)}if(!j){_.create||v(`no app "${p}" on ${T} \u2014 create it with \`turbobase apps create ${p}\`, or pass --create.`);let Re=await ie(`creating app ${p}`,()=>u(T,R,{slug:p},{tolerateExisting:!0}));Re.existed||x(`created ${Re.slug??p}.`)}let U;if(_.replace)if(typeof _.replace=="string")U=_.replace;else{let{previews:Re}=await H(T,R,p);if(Re.length===0&&v(`no open preview on ${p} to replace \u2014 drop --replace to open the first one, or name a handle from \`turbobase apps preview list\`.`),Re.length>1){for(let lt of Re)x(` ${lt.previewId} v${lt.version}${lt.label?` ${lt.label}`:""} ${lt.url}`);v(`${p} has ${Re.length} open previews \u2014 pass the one to replace, e.g. \`--replace ${Re[0].previewId}\`.`)}U=Re[0].previewId}let se=Re=>ye.stat(zt($,Re)).then(()=>!0).catch(()=>!1),M=p,ue=$,Ee=_.build!==!1;if(Ee&&!await se("package.json"))if(await se("index.html"))x("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),Ee=!1;else if(_.pull===!1)v(`${$} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let Re=await ie(`pulling ${p}`,()=>d(T,R,p));M=Re.slug??p,await w($,Re.files,!0),x(`pulled generated source (rev ${Re.rev}).`)}let Pe;if(Ee){let Re=Fy();if(Pe={buildId:Re,assetBase:By(Re)},_.install!==!1&&!await se("node_modules")){x("installing dependencies\u2026");try{await E(["install"],$)}catch(lt){v(`npm install failed: ${lt instanceof Error?lt.message:String(lt)}`)}}x("building\u2026");try{await E(["run","build"],$,{TURBOBASE_ASSET_BASE:Pe.assetBase})}catch(lt){v(`build failed: ${lt instanceof Error?lt.message:String(lt)}`)}await se("dist")||v(`no dist/ after build in ${$} \u2014 check the app's build script.`),ue=zt($,"dist")}S&&!Pe&&v(`--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 ct=await Y(T,R,M,ue,_.entry,y,Pe,S?{label:_.label,replacePreviewId:U}:void 0);if(S){let Re=ct.previewUrl??"(no url returned)",lt=ct.expiresAt?new Date(ct.expiresAt).toLocaleDateString():`${Vy} days`,Bo=ct.replacedVersion==null?null:`replaced v${ct.replacedVersion} \u2014 same URL`;if(Qe())x(qr(Bo?"Preview replaced":"Preview deployed",[`${g.bold(M)} ${g.green(`v${ct.version??"?"}`)} ${g.dim("not live")}`,`${g.bold(Re)}`,...Bo?[g.dim(Bo)]:[],g.dim(`expires ${lt}`)]));else{let rS=Bo?`; ${Bo}`:"";x(`preview ${M} v${ct.version??"?"} \u2192 ${Re} (expires ${lt}; /a/${M} unchanged${rS}).`)}x(`next: turbobase apps promote ${M} ${ct.previewId??"<preview-id>"} # make it live`),x(` turbobase apps preview discard ${ct.previewId??"<preview-id>"}`);return}Qe()?x(qr("Deployed",[`${g.bold(M)} ${g.green(`v${ct.version??"?"}`)} ${g.dim(ct.url??`/a/${M}`)}`])):x(`deployed ${M} \u2192 v${ct.version??"?"} (${ct.url??`/a/${M}`}).`),await Ge(ct,$)}),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:S,token:$}=await re(_.baseUrl),y=await ie(`promoting ${h}`,()=>z(S,$,p,"promote",{previewId:h}));Qe()?x(qr("Promoted",[`${g.bold(p)} ${g.green(`v${y.version??"?"}`)} ${g.dim(y.url??`/a/${p}`)}`])):x(`promoted ${p} \u2192 v${y.version??"?"} is now live at ${y.url??`/a/${p}`}.`),await Ge(y)});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:S}=await re(h.baseUrl),$=await H(_,S,p);if($.previews.length===0){x(`no open previews for ${p}.`);return}for(let y of $.previews){let T=y.label?` ${y.label}`:"",R=y.expiresAt?new Date(y.expiresAt).toLocaleDateString():"?";x(`v${y.version} ${y.previewId}${T} ${y.url} (expires ${R})`)}}),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:S,token:$}=await re(_.baseUrl);await ie(`discarding ${h}`,()=>z(S,$,p,"discard",{previewId:h})),x(`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:S}=await re(h.baseUrl),$=await ie(`creating ${p}`,()=>u(_,S,{slug:p,name:h.name,description:h.description})),y=$.slug??p;Qe()?x(qr("Created",[`${g.bold(y)} ${g.dim($.url??`/a/${y}`)}`])):x(`created ${y} (${$.url??`/a/${y}`}).`),x(`next: turbobase apps push ${y} . # store the source`),x(` turbobase apps deploy ${y} # build + go live`)});async function u(p,h,_,S={}){let $=`${p.replace(/\/+$/,"")}/v1/apps`,y;try{y=await fetch($,{method:"POST",headers:{Authorization:`Bearer ${h}`,"content-type":"application/json"},body:JSON.stringify({slug:_.slug,name:_.name??_.slug,description:_.description})})}catch(T){v(`create request failed: ${T instanceof Error?T.message:String(T)}`)}if(y.status===401&&v("create unauthorized (401) \u2014 re-run `turbobase auth login`."),y.status===403&&v("create forbidden (403) \u2014 the PAT is not for an admin."),y.status===409){if(S.tolerateExisting)return{slug:_.slug,existed:!0};v(`an app with slug "${_.slug}" already exists.`)}return y.ok||v(`create failed: HTTP ${y.status} ${(await y.text().catch(()=>"")).slice(0,200)}`),await y.json().catch(()=>({}))}async function d(p,h,_){let S=`${p.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(_)}/pull`,$;try{$=await fetch(S,{headers:{Authorization:`Bearer ${h}`}})}catch(y){v(`pull request failed: ${y instanceof Error?y.message:String(y)}`)}return $.status===401&&v("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),$.status===403&&v("pull forbidden (403) \u2014 the PAT is not for an admin."),$.status===404&&v(`no generated source for "${_}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),$.ok||v(`pull failed: HTTP ${$.status} ${(await $.text().catch(()=>"")).slice(0,200)}`),await $.json()}async function w(p,h,_){let S=$e(p),$=0;for(let[y,T]of Object.entries(h)){let R=$e(S,y);R!==S&&!R.startsWith(S+Rm)&&v(`refusing to write outside ${S}: ${y}`),_||await ye.stat(R).then(()=>!0).catch(()=>!1)&&v(`${R} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await ye.mkdir(Uo(R),{recursive:!0}),await ye.writeFile(R,T,"utf8"),$+=1}return $}function m(p){let h=p.indexOf(","),_=p.startsWith("data:")?h>=0?p.slice(h+1):"":p;if(!_)return null;try{let S=Buffer.from(_,"base64");return S.length>0?new Uint8Array(S):null}catch{return null}}async function f(p,h,_){let S=$e(p),$=async(T,R)=>{let C=$e(S,T);C!==S&&!C.startsWith(S+Rm)&&v(`refusing to write outside ${S}: ${T}`),_||await ye.stat(C).then(()=>!0).catch(()=>!1)&&v(`${C} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await ye.mkdir(Uo(C),{recursive:!0}),await ye.writeFile(C,R)},y=`# ${h.title||"App change request"}
1972
2164
 
1973
2165
  > Widget proposal \`${h.proposalId}\` \u2014 build this change, then ship it with
1974
2166
  > \`turbobase apps deploy ${h.appSlug}\`. The deploy stamps this proposal complete.
@@ -1978,34 +2170,34 @@ ${h.bodyMarkdown||"_No description provided._"}
1978
2170
  ## Screen context
1979
2171
 
1980
2172
  `+(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.
1981
- `);if(await k("PROPOSAL.md",g),h.screenshot){let T=m(h.screenshot);T&&await k("proposal-screenshot.png",T)}await k(Ct(".turbobase","proposal.json"),`${JSON.stringify({proposalId:h.proposalId},null,2)}
1982
- `)}async function y(p){try{let h=await ye.readFile(Ct(p,".turbobase","proposal.json"),"utf8"),_=JSON.parse(h);return typeof _.proposalId=="string"&&_.proposalId?_.proposalId:void 0}catch{return}}async function v(p,h,_,$,k,g){let T=new Q({baseUrl:p,token:h});try{return await T.appsPush(_,$,{note:k,proposalId:g})}catch(R){if(R instanceof ge){let C=R.body;if(R.status===401&&x("push unauthorized (401) \u2014 re-run `turbobase auth login`."),R.status===403&&C?.error==="admin_required"&&x("push forbidden (403) \u2014 the PAT is not for an admin."),R.status===403&&ce(R,"extensions:deploy","push app source"),R.status===404&&x(`no app "${_}" on this instance \u2014 create it with \`turbobase apps create ${_}\`.`),R.status===413&&(C?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&x("push rejected: the request body exceeded the instance limit."),x(`push rejected: ${C?.error??"too large"} (limit ${C?.limit??"?"}).`)),R.status===400){let D=C?.path?` in ${C.path}`:"",U=C?.reason?` (${C.reason})`:"";x(`push rejected: ${C?.error??"bad request"}${U}${D}.`)}}x(`push failed: ${R instanceof Error?R.message:String(R)}`)}}function E(p,h,_){return new Promise(($,k)=>{let g=vm("npm",p,{cwd:h,stdio:"inherit",..._?{env:{...process.env,..._}}:{}});g.on("error",k),g.on("exit",T=>T===0?$():k(new Error(`npm ${p.join(" ")} exited ${T??"?"}`)))})}async function P(p,h,_,$){let k=`${p.replace(/\/+$/,"")}${_}`,g;try{g=await fetch(k,{method:$.method,headers:{Authorization:`Bearer ${h}`,...$.body?{"content-type":"application/json"}:{}},...$.body?{body:JSON.stringify($.body)}:{}})}catch(T){x(`request failed: ${T instanceof Error?T.message:String(T)}`)}if(g.status===401&&x("unauthorized (401) \u2014 re-run `turbobase auth login`."),g.status===403&&x("forbidden (403) \u2014 the PAT is not for an admin."),!g.ok){let T=await g.text().catch(()=>""),R=T.slice(0,300);try{let C=JSON.parse(T);R=C.message??C.error??R}catch{}x(`failed: HTTP ${g.status} ${R}`)}return await g.json().catch(()=>({}))}async function z(p,h,_,$,k){return await P(p,h,`/v1/apps/${encodeURIComponent(_)}/preview/${$}`,{method:"POST",body:k})}async function V(p,h,_){return{previews:(await P(p,h,`/v1/apps/${encodeURIComponent(_)}/previews`,{method:"GET"})).previews??[]}}async function Y(p,h,_,$,k,g,T,R){let C;try{C=await se(`zipping ${$}`,()=>Ng($))}catch(M){x(`could not zip ${$}: ${M instanceof Error?M.message:String(M)}`)}C.fileCount===0&&x(`${$} is empty \u2014 the build produced nothing.`);let D={Authorization:`Bearer ${h}`,"Content-Type":"application/zip"};k&&(D["x-app-entry"]=k),g&&(D["x-proposal-id"]=g),T&&(D["x-app-build-id"]=T.buildId,D["x-app-asset-base"]=T.assetBase),R&&(D["x-app-channel"]="preview",R.label&&(D["x-app-preview-label"]=encodeURIComponent(R.label)),R.replacePreviewId&&(D["x-app-preview-replace"]=R.replacePreviewId));let U=`${p.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(_)}/deploy`,oe;try{oe=await se(`deploying ${_} (${C.fileCount} file${C.fileCount===1?"":"s"})`,()=>fetch(U,{method:"POST",headers:D,body:new Uint8Array(C.buffer)}))}catch(M){x(`deploy request failed: ${M instanceof Error?M.message:String(M)}`)}if(oe.status===401&&x("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),oe.status===403&&x("deploy forbidden (403) \u2014 the PAT is not for an admin."),oe.status===404){let M=await oe.text().catch(()=>""),ue={};try{ue=JSON.parse(M)}catch{}ue.error==="no_preview"&&x(`${ue.message??`no open preview to replace on ${_}`} \u2014 list them with \`turbobase apps preview list ${_}\`.`),x(`no app "${_}" on ${p} \u2014 create it with \`turbobase apps create ${_}\`.`)}if(!oe.ok){let M=await oe.text().catch(()=>""),ue=M.slice(0,300);try{let Ee=JSON.parse(M);ue=Ee.message??Ee.error??ue}catch{}x(`deploy failed: HTTP ${oe.status} ${ue}`)}return await oe.json().catch(()=>({}))}async function Ke(p,h){let _=Kg(p,{localDocsModifiedAt:await et(h)});_&&S(_.level==="warn"?w.yellow(_.message):w.dim(_.message))}async function et(p){if(!p)return null;let h=null;for(let _ of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let $=await ye.stat(Ct(p,_));(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,_)=>{let{baseUrl:$,token:k}=await ne(_.baseUrl);if(_.proposal){let C=new Q({baseUrl:$,token:k}),D;try{D=await se(`fetching proposal ${_.proposal}`,()=>C.appPullContext(_.proposal))}catch(Ee){ce(Ee,"extensions:deploy","pull proposal"),Ee instanceof ge&&Ee.status===404&&x(`no widget proposal "${_.proposal}" on ${$}.`),x(`could not fetch proposal ${_.proposal}: ${Ee instanceof Error?Ee.message:String(Ee)}`)}let U=await se(`pulling ${D.appSlug}`,()=>d($,k,D.appSlug)),oe=h??p,M=$e(process.cwd(),oe??D.appSlug);await ye.mkdir(M,{recursive:!0});let ue=await b(M,U.files,!!_.force);await f(M,D,!!_.force),S(`pulled ${ue} file${ue===1?"":"s"} \u2192 ${M} (rev ${U.rev}), linked to proposal ${D.proposalId}.`),S(`next: cd ${Zc(process.cwd(),M)||"."} && turbobase apps deploy ${D.appSlug}`);return}p||x("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let g=await se(`pulling ${p}`,()=>d($,k,p)),T=$e(process.cwd(),h??g.slug??p);await ye.mkdir(T,{recursive:!0});let R=await b(T,g.files,!!_.force);S(`pulled ${R} file${R===1?"":"s"} \u2192 ${T} (rev ${g.rev}).`),S(`next: cd ${Zc(process.cwd(),T)||"."} && 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 $=$e(process.cwd(),h??p),k=await Jt(_.baseUrl).catch(()=>null),{scaffoldAppFiles:g,starterApp:T}=await Promise.resolve().then(()=>(nb(),rb)),R=_.title??p,C=g({slug:p,title:R,appTsx:T(R),instanceOrigin:k?.baseUrl});await ye.mkdir($,{recursive:!0});let D=await b($,C,!!_.force);if(S(`scaffolded ${D} file${D===1?"":"s"} \u2192 ${$}`),_.claude!==!1){let oe=Ul({baseUrl:k?.baseUrl,token:k?.token,appSlug:p}),M=0;for(let ue of oe){let Ee=await z$(Ct($,ue.path),ue);(Ee==="wrote"||Ee==="merged")&&(M+=1)}S(`wired Claude Code: ${M} file${M===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),k||H("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 U=Zc(process.cwd(),$)||".";S(`next: cd ${U} && npm install && npm run dev`),S(` turbobase apps create ${p}`),S(` turbobase apps push ${p} .`),S(` 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),$=new Q({baseUrl:h,token:_}),k;try{k=await $.appsList()}catch(g){ce(g,"extensions:deploy","list apps"),x(`list apps failed: ${g instanceof Error?g.message:String(g)}`)}if(p.json)return S(JSON.stringify(k,null,2));if(k.length===0)return S("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");S(Zr(k.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 $=$e(process.cwd(),h??".");await ye.stat($).then(Pe=>Pe.isDirectory()).catch(()=>!1)||x(`${$} is not a directory.`);let{baseUrl:g,token:T}=await ne(_.baseUrl),R=_.proposal??await y($),{files:C,skipped:D,secrets:U,unstorable:oe}=await $y($),M=Object.keys(C).length;if(M===0&&x(`no source files found under ${$} (build output and node_modules are skipped).`),oe.length>0){for(let Pe of oe)H(`${Pe} contains a NUL byte (U+0000), which cannot be stored.`);x(`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 Pe of D)H(w.dim(`skipped binary file ${Pe}`));for(let Pe of U)H(w.dim(`skipped ${Pe} (holds credentials \u2014 never pushed)`));let ue=await se(`pushing ${M} file${M===1?"":"s"}`,()=>v(g,T,p,C,_.note,R));S(`pushed ${ue.files} file${ue.files===1?"":"s"} \u2192 ${ue.slug} rev ${ue.rev} (source only, nothing deployed).`);let Ee=await as(new Q({baseUrl:g,token:T}),ue.slug);Ee&&Ee.entriesAdded>0&&S(`${Ee.entriesAdded} new finding(s) queued \u2014 run \`turbobase skills push\` / \`turbobase kb push\` to act on them.`),S(`next: turbobase apps deploy ${ue.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 ym(),{baseUrl:_,token:$}=await ne(p.baseUrl),k=new Q({baseUrl:_,token:$}),g;try{g=await se(`planning against ${p.to??_}`,()=>k.configPlan(h))}catch(T){x(`plan failed: ${T instanceof Error?T.message:String(T)}`)}CL(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 ym(),{baseUrl:_,token:$}=await ne(p.baseUrl),k=h.tenant??zL(_),g=Uy(p.confirm,k);g.ok||x(`promote refused (fail-closed): ${g.reason}`);let T=new Q({baseUrl:_,token:$});try{let R=await se(`promoting ${p.from} \u2192 ${p.to} (${k})`,()=>T.configApply(h));if(Xe()){let C=[`${w.bold(`${p.from} \u2192 ${p.to}`)} ${w.dim(k??"")}`,`${Mr.add(String(R.applied.add))} ${Mr.change(String(R.applied.change))} ${Mr.destroy(String(R.applied.destroy))}`];R.backfillsQueued.length&&C.push(w.dim(`${R.backfillsQueued.length} backfill(s) queued`)),S(Ur("Promoted",C))}else S(`promoted ${p.from} \u2192 ${p.to} (${k}): +${R.applied.add} ~${R.applied.change} -${R.applied.destroy}`+(R.backfillsQueued.length?` (${R.backfillsQueued.length} backfill(s) queued)`:""))}catch(R){R instanceof ge&&R.status===403&&x("promote forbidden (403) \u2014 the stored PAT is not for an admin."),x(`promote failed: ${R instanceof Error?R.message:String(R)}`)}});let Ar=async(p,h)=>{let{baseUrl:_,token:$}=await ne(h.baseUrl),k=new Q({baseUrl:_,token:$}),g=h.limit?Number(h.limit):void 0;if(h.follow){try{await Bg(k,p,{follow:!0,limit:g,intervalMs:h.intervalMs?Number(h.intervalMs):void 0,sink:S})}catch(T){x(`logs --follow failed: ${T instanceof Error?T.message:String(T)}`)}return}try{let T=await k.logs(p,g);T.length===0&&S(`no logs for ${p}.`);for(let R of T)S(` [${R.level}] ${R.ts??""} ${R.message}`)}catch(T){x(`logs failed: ${T instanceof Error?T.message:String(T)}`)}};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(Ar),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 _=gm(h.reporter),$=$e(process.cwd(),p),k=await ns($),g=Lg(k);_?S(Zi(AL(p,g),_)):S(Dg(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 _=gm(h.reporter),$=await Pg($e(process.cwd(),p));if(h.against){h.against!=="sandbox"&&x(`unknown --against target '${h.against}' (only 'sandbox' is supported).`);try{await Eg(Ol($))}catch(T){x(T instanceof Error?T.message:String(T))}return}h.fixture||x("replay needs a --fixture <file> (offline) or --against sandbox (online).");let k;try{k=await Rg($e(process.cwd(),h.fixture))}catch(T){x(`could not read fixture ${h.fixture}: ${T instanceof Error?T.message:String(T)}`)}let g=await Tg($,k,h.fixture);if(_){let T=IL(g);S(Zi(T,_)),T.cases.some(R=>R.status==="failed")&&process.exit(1);return}S(Ag(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),$=new Q({baseUrl:h,token:_});try{await Vg($,{status:p.status,retry:p.retry,limit:p.limit?Number(p.limit):void 0,sink:S})}catch(k){k instanceof ge&&k.status===403&&x("forbidden (403) \u2014 binding --retry requires an admin PAT."),k instanceof ge&&k.status===409&&x("binding is not retryable (only divergent/blocked bindings can be retried)."),x(`ext binding failed: ${k instanceof Error?k.message:String(k)}`)}}),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("@"),$=_>0?p.slice(0,_):p,k=_>0?p.slice(_+1):void 0,g=Tl();g||x(`marketplace not configured \u2014 set ${Qn} and ${Li}.
1983
- Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let T=El(g.registryUrl);T&&x(T);let{baseUrl:R,token:C}=await ne(h.baseUrl),D=new es(g),U;try{U=await se(`fetching ${p}`,()=>D.fetchBundle($,k))}catch(Pe){x(`marketplace fetch failed for ${p}: ${Pe instanceof Error?Pe.message:String(Pe)}`)}let oe=Ai(U.manifest),M=null;if(oe.length>0){if(!h.connection){let Pe=oe.map(at=>at.source_system).join(", ");x(`${U.name}@${U.version} declares a connection input (source: ${Pe}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}M=h.connection}let ue=OL(U.bundle,U.name,U.kind),Ee=new Q({baseUrl:R,token:C});try{let Pe=await se(`installing ${U.name}@${U.version}`,()=>Ee.deploy({...ue,provenance:"marketplace",...M?{connectionId:M}:{}}));S(`installed ${U.name}@${U.version} \u2192 ${Pe.id} (status=${Pe.status}, ${Pe.outcome})`+(M?` bound to connection ${M}.`:"."))}catch(Pe){Pe instanceof ge&&Pe.status===403&&x("install forbidden (403) \u2014 the stored PAT is not for an admin."),x(`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 _=Tl();_||x(`marketplace not configured \u2014 set ${Qn} and ${Li}.
1984
- Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let $=El(_.registryUrl);$&&x($);let k=$e(process.cwd(),p),g=await ns(k),T=/\bdefineConduit\s*[<(]/.test(g)?"conduit":"hook",R={};if(h.manifest){let U=$e(process.cwd(),h.manifest),oe;try{oe=await ye.readFile(U,"utf8")}catch{x(`manifest not found at ${h.manifest}.`)}let M;try{M=JSON.parse(oe)}catch{x(`manifest is not valid JSON: ${h.manifest}.`)}(typeof M!="object"||M===null||Array.isArray(M))&&x("manifest must be a JSON object."),R=M}try{dl(R,g)}catch(U){U instanceof jr&&x(U.message),x(`manifest validation failed: ${U instanceof Error?U.message:String(U)}`)}let C=new es(_);try{await se(`publishing ${h.name}@${h.pkgVersion}`,()=>C.publish({name:h.name,version:h.pkgVersion,kind:T,bundle:g,manifest:R}))}catch(U){U instanceof ge&&U.status===403&&x("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),U instanceof ge&&U.status===409&&x(`version already published \u2014 ${h.name}@${h.pkgVersion} exists. Bump the version.`),x(`publish failed: ${U instanceof Error?U.message:String(U)}`)}let D=Ai(R);S(`published ${h.name}@${h.pkgVersion} (kind=${T}) to the marketplace.`),D.length>0&&S(` declares ${D.length} connection input(s): ${D.map(U=>U.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 Jt(p.baseUrl).catch(()=>null),_=Ul({baseUrl:h?.baseUrl,token:h?.token}),$=0,k=0,g=0;for(let T of _){let R=$e(process.cwd(),T.path),C=await z$(R,T);C==="wrote"?($+=1,S(` wrote ${T.path}`)):C==="merged"?(g+=1,S(` merged ${T.path} (added the .mcp.json rule)`)):(k+=1,S(` skipped ${T.path} (exists)`))}S(`
1985
- project init: ${$} written, ${g} merged, ${k} skipped.`)}),n.command("ci").description(`Write the reusable release-deploy GitHub Action to ${Ml} (non-destructive).`).action(async()=>{let p=Gg(),h=0,_=0;for(let $ of p){let k=$e(process.cwd(),$.path);await Uo(k,$.content,$.executable)==="wrote"?(h+=1,S(` wrote ${$.path}`)):(_+=1,S(` skipped ${$.path} (exists)`))}S(`
1986
- project ci: ${h} written, ${_} skipped.`),h>0&&(S(`
1987
- Next: mint a releases:write PAT in your Turbobase app (Settings \u203A Access tokens),`),S("store it as the GitHub Actions secret TURBOBASE_RELEASE_PAT, and set the repo"),S("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),$=new Q({baseUrl:h,token:_}),k;try{k=await $.catalogRecords()}catch(D){D instanceof ge&&(D.status===401||D.status===403)&&x("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),x(`catalog fetch failed: ${D instanceof Error?D.message:String(D)}`)}if(k.length===0){S("no records in the instance catalog \u2014 nothing to generate.");return}let g=$e(process.cwd(),p.out),T=Og(k,{event:p.event}),R=0,C=0;for(let{recordType:D,fixture:U}of T){let oe=Ct(g,`${D}.json`),M=`${JSON.stringify(U,null,2)}
1988
- `;p.force?(await ye.mkdir(Mo(oe),{recursive:!0}),await ye.writeFile(oe,M,{mode:420}),R+=1,S(` wrote ${p.out}/${D}.json`)):await Uo(oe,M)==="wrote"?(R+=1,S(` wrote ${p.out}/${D}.json`)):(C+=1,S(` skipped ${p.out}/${D}.json (exists \u2014 use --force to overwrite)`))}S(`
1989
- samples init: ${R} written, ${C} skipped.`)});let sr=e.command("guardrails").description("Control PG\u2192source write-back with policy rules (staged write rollout)."),sn=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??""],Zo=["NAME","STATUS","DECISION","PRIO","SOURCE","RECORD","ACTOR","WHEN","REASON"];sr.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),$=new Q({baseUrl:h,token:_}),k;try{k=await $.guardrailsList()}catch(g){ce(g,"extensions:deploy","list guardrails"),x(`list guardrails failed: ${g instanceof Error?g.message:String(g)}`)}if(p.json)return S(JSON.stringify(k,null,2));if(k.length===0)return S(`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>`"));S(Zr(k.map(sn),{head:Zo})),S(w.dim(" first match wins; lower PRIO is evaluated first."))}),sr.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:$}=await ne(h.baseUrl),k=new Q({baseUrl:_,token:$}),g;try{g=await k.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(T){ce(T,"extensions:deploy","create a guardrail"),x(`create guardrail failed: ${T instanceof Error?T.message:String(T)}`)}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)`)}`),S(w.dim(` ${g.decision} ${g.source}/${g.record??g.op}${g.actor?` actor=${g.actor}`:""}${g.when?` where ${g.when}`:""} @prio ${g.priority}`)),S(w.dim(` verify with: turbobase guardrails test --source ${g.source==="*"?"<source>":g.source} --record <record>`))}),sr.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&&x("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:_,token:$}=await ne(h.baseUrl),k=new Q({baseUrl:_,token:$}),g;try{g=await k.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(T){ce(T,"extensions:deploy","edit a guardrail"),x(`edit guardrail failed: ${T instanceof Error?T.message:String(T)}`)}S(`${w.green("\u2713")} guardrail ${w.bold(g.name??g.id)} updated`),S(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"]])sr.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($,k)=>{let{baseUrl:g,token:T}=await ne(k.baseUrl),R=new Q({baseUrl:g,token:T});try{await R.guardrailUpdate($,{status:h})}catch(C){ce(C,"extensions:deploy",`${p} a guardrail`),x(`${p} guardrail failed: ${C instanceof Error?C.message:String(C)}`)}S(`${w.green("\u2713")} guardrail ${w.bold($)} ${_}`),h==="inactive"&&S(w.dim(" writes it was gating now fall through to the other rules."))});sr.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:$}=await ne(h.baseUrl),k=new Q({baseUrl:_,token:$});try{await k.guardrailDelete(p)}catch(g){ce(g,"extensions:deploy","delete a guardrail"),x(`delete guardrail failed: ${g instanceof Error?g.message:String(g)}`)}S(`${w.green("\u2713")} guardrail ${w.bold(p)} deleted`)}),sr.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(R){x(`--fields must be valid JSON: ${R instanceof Error?R.message:String(R)}`)}let{baseUrl:_,token:$}=await ne(p.baseUrl),k=new Q({baseUrl:_,token:$}),g;try{g=await k.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(R){ce(R,"extensions:deploy","test guardrails"),x(`guardrails test failed: ${R instanceof Error?R.message:String(R)}`)}if(p.json)return S(JSON.stringify(g,null,2));let T=`${p.source}/${p.record}`;g.degraded?(S(`${w.red("\u2717")} ${T} \u2014 guardrail policy is UNREADABLE; writes fail closed`),S(w.dim(` ${g.reason}`))):g.allowed?S(`${w.green("\u2713")} ${T} \u2014 ${g.decision}`+(g.blockedBy?w.dim(` (rule ${g.blockedBy})`):w.dim(" (no rule matched)"))):(S(`${w.red("\u2717")} ${T} \u2014 ${g.decision} by ${w.bold(g.blockedBy??"?")} at the ${g.phase} gate`),g.message&&S(w.dim(` ${g.message}`))),g.decision==="require_confirm"&&S(w.yellow(" this write is HELD for operator approval, not refused.")),g.allowed||(process.exitCode=1)});let Ir=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),qn=(p,h={})=>{let _=`${w.bold(p.table)} ${w.dim(p.displayName)}`;S(p.exists===!1?`${_} ${w.dim("(new)")}`:_);for(let $ of p.fields){let k=[$.required?"required":null].filter(Boolean).join(", "),g=h.showClaimants&&$.claimedBy?.length?` ${w.dim(`\u2190 ${$.claimedBy.join(", ")}`)}`:"";S(` ${$.column.padEnd(28)} ${$.type}${k?` (${k})`:""}${g}`)}h.showClaimants&&p.claimants.length>1&&S(w.dim(` claimed by ${p.claimants.join(", ")}`))};function qo(p){if(p instanceof ge&&p.status===409){let h=p.body;h?.error==="table_conflict"&&h.message&&(H(h.message),process.exit(1))}x(`tables: ${p instanceof Error?p.message:String(p)}`)}let km=async p=>{let h=Ct($e(process.cwd(),p),"public","turbobase.json"),_=await ye.readFile(h,"utf8").catch(()=>null);if(_===null)return null;let $;try{$=JSON.parse(_)}catch(g){x(`${h} is not valid JSON: ${g instanceof Error?g.message:String(g)}`)}let k=$.tables;return k===void 0?{tables:[],manifestPath:h}:(Array.isArray(k)||x(`${h}: "tables" must be an array.`),{tables:k,manifestPath:h})};Ir.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),$=new Q({baseUrl:h,token:_}),k;try{k=await $.tablesList()}catch(g){ce(g,"extensions:deploy","list tables"),x(`list tables failed: ${g instanceof Error?g.message:String(g)}`)}if(p.json)return S(JSON.stringify(k,null,2));if(k.length===0)return S("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");S(Zr(k.map(g=>[g.table,g.displayName,String(g.fields.length),g.status,g.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),Ir.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 km(p??".");if(_||x(`no public/turbobase.json under ${$e(process.cwd(),p??".")}.`),_.tables.length===0)return S(`${_.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:$,token:k}=await ne(h.baseUrl),g=new Q({baseUrl:$,token:k}),T;try{T=await se("planning tables",()=>g.tablesPlan({claimedBy:h.as,tables:_.tables}))}catch(R){ce(R,"extensions:deploy","plan tables"),qo(R)}S(`claiming as ${w.bold(T.claimedBy)}`);for(let R of T.tables)qn(R,{showClaimants:!0});S(""),S(w.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),Ir.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 km(p??".");if(_||x(`no public/turbobase.json under ${$e(process.cwd(),p??".")}.`),_.tables.length===0)return S(`${_.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:$,token:k}=await ne(h.baseUrl),g=new Q({baseUrl:$,token:k}),T;try{T=await se("applying tables",()=>g.tablesApply({claimedBy:h.as,tables:_.tables}))}catch(R){ce(R,"extensions:deploy","apply tables"),qo(R)}for(let R of T.tables)qn(R,{showClaimants:!0});S(`applied ${T.tables.length} table${T.tables.length===1?"":"s"} as ${T.claimedBy}.`)}),Ir.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(R=>{let[C,D,U]=R.split(":");return(!C||!D)&&x(`--field "${R}" must be name:type[:required] (e.g. title:text:required).`),U!==void 0&&U!=="required"&&x(`--field "${R}": the third part may only be "required".`),{name:C,type:D,...U==="required"?{required:!0}:{}}}),{baseUrl:$,token:k}=await ne(h.baseUrl),g=new Q({baseUrl:$,token:k}),T;try{T=await se(`creating cr_${p}`,()=>g.tablesApply({tables:[{slug:p,displayName:h.name??p,fields:_,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(R){ce(R,"extensions:deploy","create a table"),qo(R)}for(let R of T.tables)qn(R);S(""),S(w.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),Ir.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&&x(`drop refused: --confirm "${h.confirm}" does not match "${p}".`);let{baseUrl:_,token:$}=await ne(h.baseUrl),k=new Q({baseUrl:_,token:$}),g;try{g=await se(`dropping cr_${p}`,()=>k.tablesDrop(p,h.confirm))}catch(T){ce(T,"extensions:deploy","drop a table"),x(`drop failed: ${T instanceof Error?T.message:String(T)}`)}if(!g.removed)return S(`no table named "${p}" on this instance \u2014 nothing dropped.`);S(`dropped ${g.table} and every row in it.`)});let qc=e.command("sandbox").description("Ephemeral local authoring sandboxes.");qc.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=bm(),_;try{_=await Ny(h,{fromTenant:p.from,ttl:p.ttl,sample:p.sample,baseUrl:p.baseUrl})}catch($){$ instanceof ls&&x($.message),x(`sandbox create failed: ${$ instanceof Error?$.message:String($)}`)}S(`sandbox ${_.name} ready.`),S(` source: ${_.fromTenant} (sampled ${Math.round(_.sampleFraction*100)}%, redacted)`),S(` url: ${_.url}`),S(` expires: ${_.expiresAt}`)}),qc.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=bm();await eu(h).catch(()=>[]);let _;try{_=await jy(h,p)}catch($){x(`sandbox destroy failed: ${$ instanceof Error?$.message:String($)}`)}_||x(`no sandbox named '${p}'.`),S(`destroyed sandbox ${_.name} (dropped ${_.database}).`)}),qc.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let p=bm(),h=await eu(p).catch(()=>[]),_=await Ki(),{active:$}=Ql(_);if($.length===0)S("no active sandboxes.");else{for(let k of $)S(` ${k.name} from=${k.fromTenant} expires=${k.expiresAt} ${k.url}`);S(`
1991
- ${$.length} active sandbox(es).`)}h.length>0&&S(`(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.",Gi).action(async p=>{let{baseUrl:h,token:_}=await ne(p.baseUrl),$=new Q({baseUrl:h,token:_}),k;try{k=await se("exporting instance config",()=>$.configExport())}catch(R){R instanceof ge&&(R.status===401||R.status===403)&&x("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),x(`ext export failed: ${R instanceof Error?R.message:String(R)}`)}let g=typeof k.serialized=="string"?k.serialized:`${JSON.stringify(k.manifest??k,null,2)}
1992
- `,T=$e(process.cwd(),p.out,ds);await ye.mkdir(Mo(T),{recursive:!0}),await ye.writeFile(T,g,"utf8"),S(`wrote ${p.out}/${ds} (${g.split(`
1993
- `).length} lines).`)});let $m=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),j$=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Sm=()=>process.env.TURBOBASE_HOME?.trim()||Ct(xL(),".turbobase"),L$=()=>"1.1.19",yi=async()=>Promise.all(j$.map(async p=>{try{return await import(p.name),{...p,present:!0}}catch{return{...p,present:!1}}}));$m.command("status").description("Report which optional native packages are installed.").action(async()=>{let p=await yi();for(let h of p)S(`${h.present?ft.success("installed"):ft.warn("missing")} ${w.bold(h.name)} \u2014 ${h.needs}`);p.some(h=>!h.present)&&S(`
1994
- run \`${ss} ext extras install\` to fetch them into ${Sm()}.`)}),$m.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let p=await yi();if(p.every(C=>C.present)){S(ft.success("extras already installed \u2014 nothing to do."));return}let h=Sm();await ye.mkdir(h,{recursive:!0});let _=p.filter(C=>!C.present).map(C=>C.name),$=Kl(process.platform,process.arch),k=async(C,D)=>{let{code:U,stderr:oe}=await gi("npm",["install","--prefix",h,"--no-audit","--no-fund",...C]);U!==0&&x(`extras install failed while installing ${D} (npm exited ${U}).
1995
- ${oe.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(D=>`${D}@${Vl[D]??"latest"}`);S(`installing ${C.join(", ")} \u2192 ${h}/node_modules \u2026`),await k(C,g.join(", "))}if(_.includes("isolated-vm")){let C=`isolated-vm@${Vl["isolated-vm"]}`;if(S(`installing ${C} \u2192 ${h}/node_modules \u2026`),await k(["--ignore-scripts",C],"isolated-vm"),Ry.includes($)){let U=`${Hl}@${L$()}`;S(`fetching ${U} (no upstream binary for ${$}) \u2026`);let{code:oe}=await gi("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",U]);oe!==0&&S(ft.warn(`could not fetch ${U} \u2014 falling back to a source build.`))}let D=await Py({home:h});D.length>0&&S(` ${ft.success("prebuilt")} ${D.join(", ")} \u2192 isolated-vm/prebuilds/${$}`)}let T=await yi(),R=T.filter(C=>!C.present).map(C=>C.name);if(R.includes("isolated-vm")){S(ft.warn(`no prebuilt isolated-vm for ${$} / Node ${process.versions.node} (${Gl()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:C}=await gi("npm",["rebuild","--prefix",h,"isolated-vm"]);C===0&&(T=await yi(),R=T.filter(D=>!D.present).map(D=>D.name))}R.length>0&&x(`npm succeeded but ${R.join(", ")} still will not load \u2014 no prebuilt binary for ${$} / Node ${process.versions.node} (${Gl()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),S(ft.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let Fn=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return Fn.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||x(`--target must be 'auto' or 'approved' (got '${p.target}').`);let _=await NL($e(process.cwd(),p.project??".")),$=Object.keys(_).length;!p.solution&&$===0&&x("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 wm(["rev-parse",p.ref])??p.ref:null)??process.env.GITHUB_SHA??await wm(["rev-parse","HEAD"]),T=p.gitRepo??process.env.GITHUB_REPOSITORY??await wm(["remote","get-url","origin"]),R=p.gitRef??process.env.GITHUB_REF??null,C=p.prUrl??process.env.PR_URL??null,{baseUrl:D,token:U}=await ne(p.baseUrl),oe=new Q({baseUrl:D,token:U}),M;try{M=await oe.releaseDeploy({solutionId:p.solution??null,target:h,approvedBy:p.approvedBy??null,files:$>0?_:null,gitRepo:T,gitRef:R,gitSha:g,prUrl:C})}catch(ue){ce(ue,"releases:write","release deploy"),ue instanceof ge&&ue.status===404&&x("solution_not_found \u2014 no solution with that id."),x(`release deploy failed: ${ue instanceof Error?ue.message:String(ue)}`)}S(`release ${M.releaseId} enqueued \u2192 taskId=${M.taskId} (target=${h}`+($>0?`, uploaded ${$} bundle file(s)`:", live-fetch")+")."),p.follow&&await ql(()=>oe.releaseStatus(M.releaseId),`release ${M.releaseId}`,p.intervalMs)}),Fn.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:$}=await ne(h.baseUrl),k=new Q({baseUrl:_,token:$}),g;try{g=await k.releaseFiles(p)}catch(C){C instanceof ge&&C.status===404&&x(`release ${p} not found.`),C instanceof ge&&C.status===409&&x(`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.`),ce(C,"releases:write","pull a release"),x(`release pull failed: ${C instanceof Error?C.message:String(C)}`)}let T=$e(process.cwd(),h.dir),R=0;for(let[C,D]of[["owned",g.owned],["context",g.context]])for(let[U,oe]of Object.entries(D)){let M=Ct(T,C,U);await ye.mkdir(Mo(M),{recursive:!0}),await ye.writeFile(M,oe,"utf8"),R++}await ye.writeFile(Ct(T,".turbobase-release.json"),JSON.stringify({releaseId:g.releaseId,version:g.version,contentDigest:g.contentDigest},null,2),"utf8"),S(`pulled release ${g.releaseId} (${g.status}) \u2192 ${T}
1997
- ${Object.keys(g.owned).length} owned file(s), ${Object.keys(g.context).length} context file(s), ${R} total
1998
- `+(g.logTail?`
2173
+ `);if(await $("PROPOSAL.md",y),h.screenshot){let T=m(h.screenshot);T&&await $("proposal-screenshot.png",T)}await $(zt(".turbobase","proposal.json"),`${JSON.stringify({proposalId:h.proposalId},null,2)}
2174
+ `)}async function b(p){try{let h=await ye.readFile(zt(p,".turbobase","proposal.json"),"utf8"),_=JSON.parse(h);return typeof _.proposalId=="string"&&_.proposalId?_.proposalId:void 0}catch{return}}async function k(p,h,_,S,$,y){let T=new X({baseUrl:p,token:h});try{return await T.appsPush(_,S,{note:$,proposalId:y})}catch(R){if(R instanceof pe){let C=R.body;if(R.status===401&&v("push unauthorized (401) \u2014 re-run `turbobase auth login`."),R.status===403&&C?.error==="admin_required"&&v("push forbidden (403) \u2014 the PAT is not for an admin."),R.status===403&&oe(R,"extensions:deploy","push app source"),R.status===404&&v(`no app "${_}" on this instance \u2014 create it with \`turbobase apps create ${_}\`.`),R.status===413&&(C?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&v("push rejected: the request body exceeded the instance limit."),v(`push rejected: ${C?.error??"too large"} (limit ${C?.limit??"?"}).`)),R.status===400){let j=C?.path?` in ${C.path}`:"",U=C?.reason?` (${C.reason})`:"";v(`push rejected: ${C?.error??"bad request"}${U}${j}.`)}}v(`push failed: ${R instanceof Error?R.message:String(R)}`)}}function E(p,h,_){return new Promise((S,$)=>{let y=Pm("npm",p,{cwd:h,stdio:"inherit",..._?{env:{...process.env,..._}}:{}});y.on("error",$),y.on("exit",T=>T===0?S():$(new Error(`npm ${p.join(" ")} exited ${T??"?"}`)))})}async function P(p,h,_,S){let $=`${p.replace(/\/+$/,"")}${_}`,y;try{y=await fetch($,{method:S.method,headers:{Authorization:`Bearer ${h}`,...S.body?{"content-type":"application/json"}:{}},...S.body?{body:JSON.stringify(S.body)}:{}})}catch(T){v(`request failed: ${T instanceof Error?T.message:String(T)}`)}if(y.status===401&&v("unauthorized (401) \u2014 re-run `turbobase auth login`."),y.status===403&&v("forbidden (403) \u2014 the PAT is not for an admin."),!y.ok){let T=await y.text().catch(()=>""),R=T.slice(0,300);try{let C=JSON.parse(T);R=C.message??C.error??R}catch{}v(`failed: HTTP ${y.status} ${R}`)}return await y.json().catch(()=>({}))}async function z(p,h,_,S,$){return await P(p,h,`/v1/apps/${encodeURIComponent(_)}/preview/${S}`,{method:"POST",body:$})}async function H(p,h,_){return{previews:(await P(p,h,`/v1/apps/${encodeURIComponent(_)}/previews`,{method:"GET"})).previews??[]}}async function Y(p,h,_,S,$,y,T,R){let C;try{C=await ie(`zipping ${S}`,()=>Fg(S))}catch(M){v(`could not zip ${S}: ${M instanceof Error?M.message:String(M)}`)}C.fileCount===0&&v(`${S} is empty \u2014 the build produced nothing.`);let j={Authorization:`Bearer ${h}`,"Content-Type":"application/zip"};$&&(j["x-app-entry"]=$),y&&(j["x-proposal-id"]=y),T&&(j["x-app-build-id"]=T.buildId,j["x-app-asset-base"]=T.assetBase),R&&(j["x-app-channel"]="preview",R.label&&(j["x-app-preview-label"]=encodeURIComponent(R.label)),R.replacePreviewId&&(j["x-app-preview-replace"]=R.replacePreviewId));let U=`${p.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(_)}/deploy`,se;try{se=await ie(`deploying ${_} (${C.fileCount} file${C.fileCount===1?"":"s"})`,()=>fetch(U,{method:"POST",headers:j,body:new Uint8Array(C.buffer)}))}catch(M){v(`deploy request failed: ${M instanceof Error?M.message:String(M)}`)}if(se.status===401&&v("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),se.status===403&&v("deploy forbidden (403) \u2014 the PAT is not for an admin."),se.status===404){let M=await se.text().catch(()=>""),ue={};try{ue=JSON.parse(M)}catch{}ue.error==="no_preview"&&v(`${ue.message??`no open preview to replace on ${_}`} \u2014 list them with \`turbobase apps preview list ${_}\`.`),v(`no app "${_}" on ${p} \u2014 create it with \`turbobase apps create ${_}\`.`)}if(!se.ok){let M=await se.text().catch(()=>""),ue=M.slice(0,300);try{let Ee=JSON.parse(M);ue=Ee.message??Ee.error??ue}catch{}v(`deploy failed: HTTP ${se.status} ${ue}`)}return await se.json().catch(()=>({}))}async function Ge(p,h){let _=ty(p,{localDocsModifiedAt:await tt(h)});_&&x(_.level==="warn"?g.yellow(_.message):g.dim(_.message))}async function tt(p){if(!p)return null;let h=null;for(let _ of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let S=await ye.stat(zt(p,_));(h===null||S.mtimeMs>h)&&(h=S.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:S,token:$}=await re(_.baseUrl);if(_.proposal){let C=new X({baseUrl:S,token:$}),j;try{j=await ie(`fetching proposal ${_.proposal}`,()=>C.appPullContext(_.proposal))}catch(Ee){oe(Ee,"extensions:deploy","pull proposal"),Ee instanceof pe&&Ee.status===404&&v(`no widget proposal "${_.proposal}" on ${S}.`),v(`could not fetch proposal ${_.proposal}: ${Ee instanceof Error?Ee.message:String(Ee)}`)}let U=await ie(`pulling ${j.appSlug}`,()=>d(S,$,j.appSlug)),se=h??p,M=$e(process.cwd(),se??j.appSlug);await ye.mkdir(M,{recursive:!0});let ue=await w(M,U.files,!!_.force);await f(M,j,!!_.force),x(`pulled ${ue} file${ue===1?"":"s"} \u2192 ${M} (rev ${U.rev}), linked to proposal ${j.proposalId}.`),x(`next: cd ${Kc(process.cwd(),M)||"."} && turbobase apps deploy ${j.appSlug}`);return}p||v("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let y=await ie(`pulling ${p}`,()=>d(S,$,p)),T=$e(process.cwd(),h??y.slug??p);await ye.mkdir(T,{recursive:!0});let R=await w(T,y.files,!!_.force);x(`pulled ${R} file${R===1?"":"s"} \u2192 ${T} (rev ${y.rev}).`),x(`next: cd ${Kc(process.cwd(),T)||"."} && turbobase apps deploy ${y.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 S=$e(process.cwd(),h??p),$=await Yt(_.baseUrl).catch(()=>null),{scaffoldAppFiles:y,starterApp:T}=await Promise.resolve().then(()=>(vb(),_b)),R=_.title??p,C=y({slug:p,title:R,appTsx:T(R),instanceOrigin:$?.baseUrl});await ye.mkdir(S,{recursive:!0});let j=await w(S,C,!!_.force);if(x(`scaffolded ${j} file${j===1?"":"s"} \u2192 ${S}`),_.claude!==!1){let se=Hl({baseUrl:$?.baseUrl,token:$?.token,appSlug:p}),M=0;for(let ue of se){let Ee=await X$(zt(S,ue.path),ue);(Ee==="wrote"||Ee==="merged")&&(M+=1)}x(`wired Claude Code: ${M} file${M===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),$||B("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 U=Kc(process.cwd(),S)||".";x(`next: cd ${U} && npm install && npm run dev`),x(` turbobase apps create ${p}`),x(` turbobase apps push ${p} .`),x(` 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 re(p.baseUrl),S=new X({baseUrl:h,token:_}),$;try{$=await S.appsList()}catch(y){oe(y,"extensions:deploy","list apps"),v(`list apps failed: ${y instanceof Error?y.message:String(y)}`)}if(p.json)return x(JSON.stringify($,null,2));if($.length===0)return x("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");x(Xt($.map(y=>[y.slug,y.name,y.deployed?"yes":"no",y.sourceRev===null?"\u2014":`rev ${y.sourceRev}`,y.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 S=$e(process.cwd(),h??".");await ye.stat(S).then(Pe=>Pe.isDirectory()).catch(()=>!1)||v(`${S} is not a directory.`);let{baseUrl:y,token:T}=await re(_.baseUrl),R=_.proposal??await b(S),{files:C,skipped:j,secrets:U,unstorable:se}=await qy(S),M=Object.keys(C).length;if(M===0&&v(`no source files found under ${S} (build output and node_modules are skipped).`),se.length>0){for(let Pe of se)B(`${Pe} contains a NUL byte (U+0000), which cannot be stored.`);v(`push aborted: ${se.length} ${se.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let Pe of j)B(g.dim(`skipped binary file ${Pe}`));for(let Pe of U)B(g.dim(`skipped ${Pe} (holds credentials \u2014 never pushed)`));let ue=await ie(`pushing ${M} file${M===1?"":"s"}`,()=>k(y,T,p,C,_.note,R));x(`pushed ${ue.files} file${ue.files===1?"":"s"} \u2192 ${ue.slug} rev ${ue.rev} (source only, nothing deployed).`);let Ee=await cs(new X({baseUrl:y,token:T}),ue.slug);Ee&&Ee.entriesAdded>0&&x(`${Ee.entriesAdded} new finding(s) queued \u2014 run \`turbobase skills push\` / \`turbobase kb push\` to act on them.`),x(`next: turbobase apps deploy ${ue.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 Sm(),{baseUrl:_,token:S}=await re(p.baseUrl),$=new X({baseUrl:_,token:S}),y;try{y=await ie(`planning against ${p.to??_}`,()=>$.configPlan(h))}catch(T){v(`plan failed: ${T instanceof Error?T.message:String(T)}`)}aD(y,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 Sm(),{baseUrl:_,token:S}=await re(p.baseUrl),$=h.tenant??cD(_),y=ob(p.confirm,$);y.ok||v(`promote refused (fail-closed): ${y.reason}`);let T=new X({baseUrl:_,token:S});try{let R=await ie(`promoting ${p.from} \u2192 ${p.to} (${$})`,()=>T.configApply(h));if(Qe()){let C=[`${g.bold(`${p.from} \u2192 ${p.to}`)} ${g.dim($??"")}`,`${Zr.add(String(R.applied.add))} ${Zr.change(String(R.applied.change))} ${Zr.destroy(String(R.applied.destroy))}`];R.backfillsQueued.length&&C.push(g.dim(`${R.backfillsQueued.length} backfill(s) queued`)),x(qr("Promoted",C))}else x(`promoted ${p.from} \u2192 ${p.to} (${$}): +${R.applied.add} ~${R.applied.change} -${R.applied.destroy}`+(R.backfillsQueued.length?` (${R.backfillsQueued.length} backfill(s) queued)`:""))}catch(R){R instanceof pe&&R.status===403&&v("promote forbidden (403) \u2014 the stored PAT is not for an admin."),v(`promote failed: ${R instanceof Error?R.message:String(R)}`)}});let Or=async(p,h)=>{let{baseUrl:_,token:S}=await re(h.baseUrl),$=new X({baseUrl:_,token:S}),y=h.limit?Number(h.limit):void 0;if(h.follow){try{await Xg($,p,{follow:!0,limit:y,intervalMs:h.intervalMs?Number(h.intervalMs):void 0,sink:x})}catch(T){v(`logs --follow failed: ${T instanceof Error?T.message:String(T)}`)}return}try{let T=await $.logs(p,y);T.length===0&&x(`no logs for ${p}.`);for(let R of T)x(` [${R.level}] ${R.ts??""} ${R.message}`)}catch(T){v(`logs failed: ${T instanceof Error?T.message:String(T)}`)}};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(Or),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 _=$m(h.reporter),S=$e(process.cwd(),p),$=await os(S),y=Vg($);_?x(Fi(oD(p,y),_)):x(Hg(p,y,{warn:g.yellow,ok:g.green,dim:g.dim})),h.ci&&y.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 _=$m(h.reporter),S=await Lg($e(process.cwd(),p));if(h.against){h.against!=="sandbox"&&v(`unknown --against target '${h.against}' (only 'sandbox' is supported).`);try{await Ng(Ml(S))}catch(T){v(T instanceof Error?T.message:String(T))}return}h.fixture||v("replay needs a --fixture <file> (offline) or --against sandbox (online).");let $;try{$=await jg($e(process.cwd(),h.fixture))}catch(T){v(`could not read fixture ${h.fixture}: ${T instanceof Error?T.message:String(T)}`)}let y=await zg(S,$,h.fixture);if(_){let T=sD(y);x(Fi(T,_)),Hc(T.cases.some(R=>R.status==="failed")?1:0)}x(Dg(y,!!h.trace)),Hc(y.error?1:0)}),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 re(p.baseUrl),S=new X({baseUrl:h,token:_});try{await Qg(S,{status:p.status,retry:p.retry,limit:p.limit?Number(p.limit):void 0,sink:x})}catch($){$ instanceof pe&&$.status===403&&v("forbidden (403) \u2014 binding --retry requires an admin PAT."),$ instanceof pe&&$.status===409&&v("binding is not retryable (only divergent/blocked bindings can be retried)."),v(`ext binding failed: ${$ instanceof Error?$.message:String($)}`)}});let Cr=o.command("proposals").description("Review the hook proposals waiting on a decision \u2014 list, promote, retract, reject.");Cr.command("list").description("List hook proposals and the evidence behind each (defaults to the pending queue).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <list>","proposed | active | rejected (comma-joined). Default: proposed.").option("--provenance <list>","mechanic | operator | learning | code-baseline (comma-joined).").option("--record-type <type>","Only proposals for this record type.").option("--source <system>","Only proposals for this adapter id.").option("--limit <n>","Max rows listed (default 200).").option("--json","Emit raw JSON instead of a table.").action(async p=>{await Ay(p)}),Cr.command("promote [ids...]").description("Arm hook proposals so the loader enforces them \u2014 by id, or by filter with --auto.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--auto","Select by filter instead of by id. Prints the plan; writes nothing without --apply.").option("--apply","With --auto: actually arm the planned proposals.").option("--provenance <list>","Restrict --auto to these provenances (mechanic | operator | code-baseline).").option("--record-type <type>","Restrict --auto to this record type.").option("--source <system>","Restrict --auto to this adapter id.").option("--limit <n>","Cap how many proposals --auto considers.").option("--all","Required to --apply an UNFILTERED plan (arm the whole queue).").option("-y, --yes","Skip the confirmation prompt (required on a non-interactive terminal).").option("--json","Emit the plan as JSON.").action(async(p,h)=>{await Iy(p??[],h)}),Cr.command("retract <ids...>").description("Send armed hooks back to proposed \u2014 inert immediately, source kept, re-promotable.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,h)=>{await Oy(p,h)}),Cr.command("reject <ids...>").description("Decline proposals for good \u2014 the id becomes the denylist. Prefer `retract` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--reason <text>","Why \u2014 recorded on the row and in the audit log.").action(async(p,h)=>{await Cy(p,h)}),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("@"),S=_>0?p.slice(0,_):p,$=_>0?p.slice(_+1):void 0,y=Cl();y||v(`marketplace not configured \u2014 set ${eo} and ${Mi}.
2175
+ Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let T=zl(y.registryUrl);T&&v(T);let{baseUrl:R,token:C}=await re(h.baseUrl),j=new ts(y),U;try{U=await ie(`fetching ${p}`,()=>j.fetchBundle(S,$))}catch(Pe){v(`marketplace fetch failed for ${p}: ${Pe instanceof Error?Pe.message:String(Pe)}`)}let se=Oi(U.manifest),M=null;if(se.length>0){if(!h.connection){let Pe=se.map(ct=>ct.source_system).join(", ");v(`${U.name}@${U.version} declares a connection input (source: ${Pe}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}M=h.connection}let ue=iD(U.bundle,U.name,U.kind),Ee=new X({baseUrl:R,token:C});try{let Pe=await ie(`installing ${U.name}@${U.version}`,()=>Ee.deploy({...ue,provenance:"marketplace",...M?{connectionId:M}:{}}));x(`installed ${U.name}@${U.version} \u2192 ${Pe.id} (status=${Pe.status}, ${Pe.outcome})`+(M?` bound to connection ${M}.`:"."))}catch(Pe){Pe instanceof pe&&Pe.status===403&&v("install forbidden (403) \u2014 the stored PAT is not for an admin."),v(`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 _=Cl();_||v(`marketplace not configured \u2014 set ${eo} and ${Mi}.
2176
+ Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let S=zl(_.registryUrl);S&&v(S);let $=$e(process.cwd(),p),y=await os($),T=/\bdefineConduit\s*[<(]/.test(y)?"conduit":"hook",R={};if(h.manifest){let U=$e(process.cwd(),h.manifest),se;try{se=await ye.readFile(U,"utf8")}catch{v(`manifest not found at ${h.manifest}.`)}let M;try{M=JSON.parse(se)}catch{v(`manifest is not valid JSON: ${h.manifest}.`)}(typeof M!="object"||M===null||Array.isArray(M))&&v("manifest must be a JSON object."),R=M}try{bl(R,y)}catch(U){U instanceof Mr&&v(U.message),v(`manifest validation failed: ${U instanceof Error?U.message:String(U)}`)}let C=new ts(_);try{await ie(`publishing ${h.name}@${h.pkgVersion}`,()=>C.publish({name:h.name,version:h.pkgVersion,kind:T,bundle:y,manifest:R}))}catch(U){U instanceof pe&&U.status===403&&v("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),U instanceof pe&&U.status===409&&v(`version already published \u2014 ${h.name}@${h.pkgVersion} exists. Bump the version.`),v(`publish failed: ${U instanceof Error?U.message:String(U)}`)}let j=Oi(R);x(`published ${h.name}@${h.pkgVersion} (kind=${T}) to the marketplace.`),j.length>0&&x(` declares ${j.length} connection input(s): ${j.map(U=>U.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 Yt(p.baseUrl).catch(()=>null),_=Hl({baseUrl:h?.baseUrl,token:h?.token}),S=0,$=0,y=0;for(let T of _){let R=$e(process.cwd(),T.path),C=await X$(R,T);C==="wrote"?(S+=1,x(` wrote ${T.path}`)):C==="merged"?(y+=1,x(` merged ${T.path} (added the .mcp.json rule)`)):($+=1,x(` skipped ${T.path} (exists)`))}x(`
2177
+ project init: ${S} written, ${y} merged, ${$} skipped.`)}),n.command("ci").description(`Write the reusable release-deploy GitHub Action to ${Vl} (non-destructive).`).action(async()=>{let p=ry(),h=0,_=0;for(let S of p){let $=$e(process.cwd(),S.path);await Zo($,S.content,S.executable)==="wrote"?(h+=1,x(` wrote ${S.path}`)):(_+=1,x(` skipped ${S.path} (exists)`))}x(`
2178
+ project ci: ${h} written, ${_} skipped.`),h>0&&(x(`
2179
+ Next: mint a releases:write PAT in your Turbobase app (Settings \u203A Access tokens),`),x("store it as the GitHub Actions secret TURBOBASE_RELEASE_PAT, and set the repo"),x("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 re(p.baseUrl),S=new X({baseUrl:h,token:_}),$;try{$=await S.catalogRecords()}catch(j){j instanceof pe&&(j.status===401||j.status===403)&&v("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),v(`catalog fetch failed: ${j instanceof Error?j.message:String(j)}`)}if($.length===0){x("no records in the instance catalog \u2014 nothing to generate.");return}let y=$e(process.cwd(),p.out),T=Ug($,{event:p.event}),R=0,C=0;for(let{recordType:j,fixture:U}of T){let se=zt(y,`${j}.json`),M=`${JSON.stringify(U,null,2)}
2180
+ `;p.force?(await ye.mkdir(Uo(se),{recursive:!0}),await ye.writeFile(se,M,{mode:420}),R+=1,x(` wrote ${p.out}/${j}.json`)):await Zo(se,M)==="wrote"?(R+=1,x(` wrote ${p.out}/${j}.json`)):(C+=1,x(` skipped ${p.out}/${j}.json (exists \u2014 use --force to overwrite)`))}x(`
2181
+ samples init: ${R} written, ${C} skipped.`)});let At=e.command("guardrails").description("Control PG\u2192source write-back with policy rules (staged write rollout)."),qo=p=>[p.name??g.dim(p.id.slice(0,8)),p.status==="active"?g.green("active"):p.status==="proposed"?g.yellow("proposed"):g.dim("inactive"),p.decision==="deny"?g.red(p.decision):p.decision==="require_confirm"?g.yellow(p.decision):g.green(p.decision),String(p.priority),p.source,p.record??p.op,p.actor??g.dim("any"),p.when||g.dim("(always)"),p.reason??""],bi=["NAME","STATUS","DECISION","PRIO","SOURCE","RECORD","ACTOR","WHEN","REASON"];At.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 re(p.baseUrl),S=new X({baseUrl:h,token:_}),$;try{$=await S.guardrailsList()}catch(y){oe(y,"extensions:deploy","list guardrails"),v(`list guardrails failed: ${y instanceof Error?y.message:String(y)}`)}if(p.json)return x(JSON.stringify($,null,2));if($.length===0)return x(`no write guardrails \u2014 every record the admin entitlement allows is writable.
2182
+ `+g.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));x(Xt($.map(qo),{head:bi})),x(g.dim(" first match wins; lower PRIO is evaluated first."))}),At.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:S}=await re(h.baseUrl),$=new X({baseUrl:_,token:S}),y;try{y=await $.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(T){oe(T,"extensions:deploy","create a guardrail"),v(`create guardrail failed: ${T instanceof Error?T.message:String(T)}`)}x(`${g.green("\u2713")} guardrail ${g.bold(y.name??y.id)} created${y.status==="active"?"":g.dim(` (${y.status} \u2014 activate it to take effect)`)}`),x(g.dim(` ${y.decision} ${y.source}/${y.record??y.op}${y.actor?` actor=${y.actor}`:""}${y.when?` where ${y.when}`:""} @prio ${y.priority}`)),x(g.dim(` verify with: turbobase guardrails test --source ${y.source==="*"?"<source>":y.source} --record <record>`))}),At.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&&v("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:_,token:S}=await re(h.baseUrl),$=new X({baseUrl:_,token:S}),y;try{y=await $.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(T){oe(T,"extensions:deploy","edit a guardrail"),v(`edit guardrail failed: ${T instanceof Error?T.message:String(T)}`)}x(`${g.green("\u2713")} guardrail ${g.bold(y.name??y.id)} updated`),x(g.dim(` ${y.decision} ${y.source}/${y.record??y.op}${y.when?` where ${y.when}`:""} @prio ${y.priority}`))});for(let[p,h,_]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])At.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(S,$)=>{let{baseUrl:y,token:T}=await re($.baseUrl),R=new X({baseUrl:y,token:T});try{await R.guardrailUpdate(S,{status:h})}catch(C){oe(C,"extensions:deploy",`${p} a guardrail`),v(`${p} guardrail failed: ${C instanceof Error?C.message:String(C)}`)}x(`${g.green("\u2713")} guardrail ${g.bold(S)} ${_}`),h==="inactive"&&x(g.dim(" writes it was gating now fall through to the other rules."))});At.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:S}=await re(h.baseUrl),$=new X({baseUrl:_,token:S});try{await $.guardrailDelete(p)}catch(y){oe(y,"extensions:deploy","delete a guardrail"),v(`delete guardrail failed: ${y instanceof Error?y.message:String(y)}`)}x(`${g.green("\u2713")} guardrail ${g.bold(p)} deleted`)}),At.command("posture [mode]").description("Show or set the GLOBAL default. 'allow' = deny-list (unmatched writes allowed, carve with deny rules). 'deny' = allow-list (unmatched writes denied, open with allow rules).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,h)=>{let{baseUrl:_,token:S}=await re(h.baseUrl),$=new X({baseUrl:_,token:S}),y=C=>C==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(p===void 0){let C;try{C=await $.guardrailPostureGet()}catch(j){oe(j,"extensions:deploy","read the guardrail posture"),v(`read posture failed: ${j instanceof Error?j.message:String(j)}`)}x(`guardrail posture: ${g.bold(y(C.mode))}`),x(g.dim(C.mode==="deny"?" Unmatched writes are DENIED. Open records with `guardrails create <name> --decision allow`.":" Unmatched writes are allowed-with-audit. Freeze records with `guardrails create <name> --decision deny`."));return}let T=p.trim().toLowerCase();T!=="allow"&&T!=="deny"&&v("posture must be 'allow' or 'deny'.");let R;try{R=await $.guardrailPostureSet(T)}catch(C){oe(C,"extensions:deploy","set the guardrail posture"),v(`set posture failed: ${C instanceof Error?C.message:String(C)}`)}x(`${g.green("\u2713")} guardrail posture set to ${g.bold(y(R.mode))}`),R.mode==="deny"&&x(g.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),At.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(R){v(`--fields must be valid JSON: ${R instanceof Error?R.message:String(R)}`)}let{baseUrl:_,token:S}=await re(p.baseUrl),$=new X({baseUrl:_,token:S}),y;try{y=await $.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(R){oe(R,"extensions:deploy","test guardrails"),v(`guardrails test failed: ${R instanceof Error?R.message:String(R)}`)}if(p.json)return x(JSON.stringify(y,null,2));let T=`${p.source}/${p.record}`;y.degraded?(x(`${g.red("\u2717")} ${T} \u2014 guardrail policy is UNREADABLE; writes fail closed`),x(g.dim(` ${y.reason}`))):y.allowed?x(`${g.green("\u2713")} ${T} \u2014 ${y.decision}`+(y.blockedBy?g.dim(` (rule ${y.blockedBy})`):g.dim(" (no rule matched)"))):(x(`${g.red("\u2717")} ${T} \u2014 ${y.decision} by ${g.bold(y.blockedBy??"?")} at the ${y.phase} gate`),y.message&&x(g.dim(` ${y.message}`))),y.decision==="require_confirm"&&x(g.yellow(" this write is HELD for operator approval, not refused.")),y.allowed||(process.exitCode=1)});let zr=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),Fo=(p,h={})=>{let _=`${g.bold(p.table)} ${g.dim(p.displayName)}`;x(p.exists===!1?`${_} ${g.dim("(new)")}`:_);for(let S of p.fields){let $=[S.required?"required":null].filter(Boolean).join(", "),y=h.showClaimants&&S.claimedBy?.length?` ${g.dim(`\u2190 ${S.claimedBy.join(", ")}`)}`:"";x(` ${S.column.padEnd(28)} ${S.type}${$?` (${$})`:""}${y}`)}h.showClaimants&&p.claimants.length>1&&x(g.dim(` claimed by ${p.claimants.join(", ")}`))};function Gc(p){if(p instanceof pe&&p.status===409){let h=p.body;h?.error==="table_conflict"&&h.message&&(B(h.message),process.exit(1))}v(`tables: ${p instanceof Error?p.message:String(p)}`)}let Im=async p=>{let h=zt($e(process.cwd(),p),"public","turbobase.json"),_=await ye.readFile(h,"utf8").catch(()=>null);if(_===null)return null;let S;try{S=JSON.parse(_)}catch(y){v(`${h} is not valid JSON: ${y instanceof Error?y.message:String(y)}`)}let $=S.tables;return $===void 0?{tables:[],manifestPath:h}:(Array.isArray($)||v(`${h}: "tables" must be an array.`),{tables:$,manifestPath:h})};zr.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 re(p.baseUrl),S=new X({baseUrl:h,token:_}),$;try{$=await S.tablesList()}catch(y){oe(y,"extensions:deploy","list tables"),v(`list tables failed: ${y instanceof Error?y.message:String(y)}`)}if(p.json)return x(JSON.stringify($,null,2));if($.length===0)return x("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");x(Xt($.map(y=>[y.table,y.displayName,String(y.fields.length),y.status,y.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),zr.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 Im(p??".");if(_||v(`no public/turbobase.json under ${$e(process.cwd(),p??".")}.`),_.tables.length===0)return x(`${_.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:S,token:$}=await re(h.baseUrl),y=new X({baseUrl:S,token:$}),T;try{T=await ie("planning tables",()=>y.tablesPlan({claimedBy:h.as,tables:_.tables}))}catch(R){oe(R,"extensions:deploy","plan tables"),Gc(R)}x(`claiming as ${g.bold(T.claimedBy)}`);for(let R of T.tables)Fo(R,{showClaimants:!0});x(""),x(g.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),zr.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 Im(p??".");if(_||v(`no public/turbobase.json under ${$e(process.cwd(),p??".")}.`),_.tables.length===0)return x(`${_.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:S,token:$}=await re(h.baseUrl),y=new X({baseUrl:S,token:$}),T;try{T=await ie("applying tables",()=>y.tablesApply({claimedBy:h.as,tables:_.tables}))}catch(R){oe(R,"extensions:deploy","apply tables"),Gc(R)}for(let R of T.tables)Fo(R,{showClaimants:!0});x(`applied ${T.tables.length} table${T.tables.length===1?"":"s"} as ${T.claimedBy}.`)}),zr.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(R=>{let[C,j,U]=R.split(":");return(!C||!j)&&v(`--field "${R}" must be name:type[:required] (e.g. title:text:required).`),U!==void 0&&U!=="required"&&v(`--field "${R}": the third part may only be "required".`),{name:C,type:j,...U==="required"?{required:!0}:{}}}),{baseUrl:S,token:$}=await re(h.baseUrl),y=new X({baseUrl:S,token:$}),T;try{T=await ie(`creating cr_${p}`,()=>y.tablesApply({tables:[{slug:p,displayName:h.name??p,fields:_,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(R){oe(R,"extensions:deploy","create a table"),Gc(R)}for(let R of T.tables)Fo(R);x(""),x(g.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),zr.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&&v(`drop refused: --confirm "${h.confirm}" does not match "${p}".`);let{baseUrl:_,token:S}=await re(h.baseUrl),$=new X({baseUrl:_,token:S}),y;try{y=await ie(`dropping cr_${p}`,()=>$.tablesDrop(p,h.confirm))}catch(T){oe(T,"extensions:deploy","drop a table"),v(`drop failed: ${T instanceof Error?T.message:String(T)}`)}if(!y.removed)return x(`no table named "${p}" on this instance \u2014 nothing dropped.`);x(`dropped ${y.table} and every row in it.`)});let Wc=e.command("sandbox").description("Ephemeral local authoring sandboxes.");Wc.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=Tm(),_;try{_=await Qy(h,{fromTenant:p.from,ttl:p.ttl,sample:p.sample,baseUrl:p.baseUrl})}catch(S){S instanceof us&&v(S.message),v(`sandbox create failed: ${S instanceof Error?S.message:String(S)}`)}x(`sandbox ${_.name} ready.`),x(` source: ${_.fromTenant} (sampled ${Math.round(_.sampleFraction*100)}%, redacted)`),x(` url: ${_.url}`),x(` expires: ${_.expiresAt}`)}),Wc.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=Tm();await cu(h).catch(()=>[]);let _;try{_=await eb(h,p)}catch(S){v(`sandbox destroy failed: ${S instanceof Error?S.message:String(S)}`)}_||v(`no sandbox named '${p}'.`),x(`destroyed sandbox ${_.name} (dropped ${_.database}).`)}),Wc.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let p=Tm(),h=await cu(p).catch(()=>[]),_=await Xi(),{active:S}=au(_);if(S.length===0)x("no active sandboxes.");else{for(let $ of S)x(` ${$.name} from=${$.fromTenant} expires=${$.expiresAt} ${$.url}`);x(`
2183
+ ${S.length} active sandbox(es).`)}h.length>0&&x(`(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.",Qi).action(async p=>{let{baseUrl:h,token:_}=await re(p.baseUrl),S=new X({baseUrl:h,token:_}),$;try{$=await ie("exporting instance config",()=>S.configExport())}catch(R){R instanceof pe&&(R.status===401||R.status===403)&&v("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),v(`ext export failed: ${R instanceof Error?R.message:String(R)}`)}let y=typeof $.serialized=="string"?$.serialized:`${JSON.stringify($.manifest??$,null,2)}
2184
+ `,T=$e(process.cwd(),p.out,ps);await ye.mkdir(Uo(T),{recursive:!0}),await ye.writeFile(T,y,"utf8"),x(`wrote ${p.out}/${ps} (${y.split(`
2185
+ `).length} lines).`)});let Om=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),eS=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Cm=()=>process.env.TURBOBASE_HOME?.trim()||zt(JL(),".turbobase"),tS=()=>"1.1.20",wi=async()=>Promise.all(eS.map(async p=>{try{return await import(p.name),{...p,present:!0}}catch{return{...p,present:!1}}}));Om.command("status").description("Report which optional native packages are installed.").action(async()=>{let p=await wi();for(let h of p)x(`${h.present?Ve.success("installed"):Ve.warn("missing")} ${g.bold(h.name)} \u2014 ${h.needs}`);p.some(h=>!h.present)&&x(`
2186
+ run \`${is} ext extras install\` to fetch them into ${Cm()}.`)}),Om.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let p=await wi();if(p.every(C=>C.present)){x(Ve.success("extras already installed \u2014 nothing to do."));return}let h=Cm();await ye.mkdir(h,{recursive:!0});let _=p.filter(C=>!C.present).map(C=>C.name),S=tu(process.platform,process.arch),$=async(C,j)=>{let{code:U,stderr:se}=await yi("npm",["install","--prefix",h,"--no-audit","--no-fund",...C]);U!==0&&v(`extras install failed while installing ${j} (npm exited ${U}).
2187
+ ${se.trim()}
2188
+ These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},y=_.filter(C=>C!=="isolated-vm");if(y.length>0){let C=y.map(j=>`${j}@${Ql[j]??"latest"}`);x(`installing ${C.join(", ")} \u2192 ${h}/node_modules \u2026`),await $(C,y.join(", "))}if(_.includes("isolated-vm")){let C=`isolated-vm@${Ql["isolated-vm"]}`;if(x(`installing ${C} \u2192 ${h}/node_modules \u2026`),await $(["--ignore-scripts",C],"isolated-vm"),Hy.includes(S)){let U=`${eu}@${tS()}`;x(`fetching ${U} (no upstream binary for ${S}) \u2026`);let{code:se}=await yi("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",U]);se!==0&&x(Ve.warn(`could not fetch ${U} \u2014 falling back to a source build.`))}let j=await Ky({home:h});j.length>0&&x(` ${Ve.success("prebuilt")} ${j.join(", ")} \u2192 isolated-vm/prebuilds/${S}`)}let T=await wi(),R=T.filter(C=>!C.present).map(C=>C.name);if(R.includes("isolated-vm")){x(Ve.warn(`no prebuilt isolated-vm for ${S} / Node ${process.versions.node} (${ru()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:C}=await yi("npm",["rebuild","--prefix",h,"isolated-vm"]);C===0&&(T=await wi(),R=T.filter(j=>!j.present).map(j=>j.name))}R.length>0&&v(`npm succeeded but ${R.join(", ")} still will not load \u2014 no prebuilt binary for ${S} / Node ${process.versions.node} (${ru()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),x(Ve.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let Bn=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return Bn.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||v(`--target must be 'auto' or 'approved' (got '${p.target}').`);let _=await lD($e(process.cwd(),p.project??".")),S=Object.keys(_).length;!p.solution&&S===0&&v("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let y=(p.ref?await Em(["rev-parse",p.ref])??p.ref:null)??process.env.GITHUB_SHA??await Em(["rev-parse","HEAD"]),T=p.gitRepo??process.env.GITHUB_REPOSITORY??await Em(["remote","get-url","origin"]),R=p.gitRef??process.env.GITHUB_REF??null,C=p.prUrl??process.env.PR_URL??null,{baseUrl:j,token:U}=await re(p.baseUrl),se=new X({baseUrl:j,token:U}),M;try{M=await se.releaseDeploy({solutionId:p.solution??null,target:h,approvedBy:p.approvedBy??null,files:S>0?_:null,gitRepo:T,gitRef:R,gitSha:y,prUrl:C})}catch(ue){oe(ue,"releases:write","release deploy"),ue instanceof pe&&ue.status===404&&v("solution_not_found \u2014 no solution with that id."),v(`release deploy failed: ${ue instanceof Error?ue.message:String(ue)}`)}x(`release ${M.releaseId} enqueued \u2192 taskId=${M.taskId} (target=${h}`+(S>0?`, uploaded ${S} bundle file(s)`:", live-fetch")+")."),p.follow&&await Gl(()=>se.releaseStatus(M.releaseId),`release ${M.releaseId}`,p.intervalMs)}),Bn.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:S}=await re(h.baseUrl),$=new X({baseUrl:_,token:S}),y;try{y=await $.releaseFiles(p)}catch(C){C instanceof pe&&C.status===404&&v(`release ${p} not found.`),C instanceof pe&&C.status===409&&v(`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.`),oe(C,"releases:write","pull a release"),v(`release pull failed: ${C instanceof Error?C.message:String(C)}`)}let T=$e(process.cwd(),h.dir),R=0;for(let[C,j]of[["owned",y.owned],["context",y.context]])for(let[U,se]of Object.entries(j)){let M=zt(T,C,U);await ye.mkdir(Uo(M),{recursive:!0}),await ye.writeFile(M,se,"utf8"),R++}await ye.writeFile(zt(T,".turbobase-release.json"),JSON.stringify({releaseId:y.releaseId,version:y.version,contentDigest:y.contentDigest},null,2),"utf8"),x(`pulled release ${y.releaseId} (${y.status}) \u2192 ${T}
2189
+ ${Object.keys(y.owned).length} owned file(s), ${Object.keys(y.context).length} context file(s), ${R} total
2190
+ `+(y.logTail?`
1999
2191
  the failure these bytes produced:
2000
- ${g.logTail.trim()}
2192
+ ${y.logTail.trim()}
2001
2193
  `:"")+`
2002
2194
  edit the files under owned/, then:
2003
- turbobase release push ${g.releaseId} --dir ${h.dir}`)}),Fn.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:$}=await ne(h.baseUrl),k=new Q({baseUrl:_,token:$}),g=$e(process.cwd(),h.dir),T;try{T=await k.releaseFiles(p)}catch(M){M instanceof ge&&M.status===404&&x(`release ${p} not found.`),ce(M,"releases:write","push a release"),x(`release push failed: ${M instanceof Error?M.message:String(M)}`)}let R=async(M,ue)=>{try{return await ye.readFile(Ct(g,M,ue),"utf8")}catch{return null}},C=[];for(let[M,ue]of Object.entries(T.context)){let Ee=await R("context",M);Ee!==null&&Ee!==ue&&C.push(M)}C.length>0&&x(`refusing to push \u2014 these context/ files were modified, and they belong to other solutions in the same bundle:
2195
+ turbobase release push ${y.releaseId} --dir ${h.dir}`)}),Bn.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:S}=await re(h.baseUrl),$=new X({baseUrl:_,token:S}),y=$e(process.cwd(),h.dir),T;try{T=await $.releaseFiles(p)}catch(M){M instanceof pe&&M.status===404&&v(`release ${p} not found.`),oe(M,"releases:write","push a release"),v(`release push failed: ${M instanceof Error?M.message:String(M)}`)}let R=async(M,ue)=>{try{return await ye.readFile(zt(y,M,ue),"utf8")}catch{return null}},C=[];for(let[M,ue]of Object.entries(T.context)){let Ee=await R("context",M);Ee!==null&&Ee!==ue&&C.push(M)}C.length>0&&v(`refusing to push \u2014 these context/ files were modified, and they belong to other solutions in the same bundle:
2004
2196
  `+C.map(M=>` context/${M}`).join(`
2005
- `)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let D={...T.context},U=0;for(let[M,ue]of Object.entries(T.owned)){let Ee=await R("owned",M);D[M]=Ee??ue,Ee!==null&&Ee!==ue&&U++}U===0&&S("nothing changed under owned/ \u2014 pushing the same bytes the release already built.");let oe=h.target==="approved"?"approved":"auto";try{let M=await k.releasePush(p,{files:D,target:oe,...h.approvedBy?{approvedBy:h.approvedBy}:{}});S(`pushed ${Object.keys(D).length} file(s) (${U} edited) \u2192 release ${M.releaseId} (task ${M.taskId}).
2197
+ `)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let j={...T.context},U=0;for(let[M,ue]of Object.entries(T.owned)){let Ee=await R("owned",M);j[M]=Ee??ue,Ee!==null&&Ee!==ue&&U++}U===0&&x("nothing changed under owned/ \u2014 pushing the same bytes the release already built.");let se=h.target==="approved"?"approved":"auto";try{let M=await $.releasePush(p,{files:j,target:se,...h.approvedBy?{approvedBy:h.approvedBy}:{}});x(`pushed ${Object.keys(j).length} file(s) (${U} edited) \u2192 release ${M.releaseId} (task ${M.taskId}).
2006
2198
  follow it with:
2007
- turbobase release status ${M.releaseId} --follow`)}catch(M){M instanceof ge&&M.status===403&&x("an approved target needs --approved-by (the deploy gate fails closed)."),M instanceof ge&&M.status===409&&x("that solution already has an active release \u2014 roll it back or wait for it."),ce(M,"releases:write","push a release"),x(`release push failed: ${M instanceof Error?M.message:String(M)}`)}}),Fn.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:$}=await ne(h.baseUrl),k=new Q({baseUrl:_,token:$});if(h.follow){await ql(()=>k.releaseStatus(p),`release ${p}`,h.intervalMs);return}let g;try{g=await k.releaseStatus(p)}catch(T){ce(T,"releases:write","release status"),T instanceof ge&&T.status===404&&x(`release ${p} not found.`),x(`release status failed: ${T instanceof Error?T.message:String(T)}`)}S(`release ${p}: status=${g.releaseStatus??"?"} stage=${g.stage} ${g.percent}%`+(g.runStatus?` (${g.runStatus})`:"")),g.outputTail&&S(g.outputTail.replace(/\n+$/,""))}),Fn.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:$}=await ne(h.baseUrl),k=new Q({baseUrl:_,token:$}),g;try{g=await k.releaseRollback(p)}catch(T){ce(T,"releases:write","release rollback"),T instanceof ge&&T.status===404&&x(`release ${p} not found.`),T instanceof ge&&T.status===409&&x(`release ${p} cannot be rolled back (not live, or a newer release advanced past it).`),x(`release rollback failed: ${T instanceof Error?T.message:String(T)}`)}S(`release ${g.releaseId} rolled back \u2192 status=${g.release?.status??"rolled_back"}.`)}),Fn.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),$=new Q({baseUrl:h,token:_}),k;try{k=await $.releaseList()}catch(g){ce(g,"releases:write","release list"),x(`release list failed: ${g instanceof Error?g.message:String(g)}`)}if(k.length===0){S("no releases.");return}if(Xe())S(Zr(k.map(g=>[g.id,ro(g.status),g.target,g.backend,g.solutionTitles?.length?g.solutionTitles.map(T=>`"${T}"`).join(", "):w.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let g of k){let T=g.solutionTitles?.length?` "${g.solutionTitles.join('", "')}"`:"";S(` ${g.id} ${g.status.padEnd(11)} target=${g.target} backend=${g.backend}${T}`)}S(`
2008
- ${k.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(()=>(C$(),O$));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 OL(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 ym(){let t=$e(process.cwd(),Gi,ds),e;try{e=await ye.readFile(t,"utf8")}catch{x(`no bundle found at ${Gi}/${ds} \u2014 run \`turbobase ext export\` first.`)}try{return My(e)}catch(r){x(`bundle is invalid: ${r instanceof Error?r.message:String(r)}`)}}function CL(t,e){S(`plan against ${e}:`);for(let r of t.add)S(` ${Mr.add(`${r.kind} ${r.id}`)}`);for(let r of t.change)S(` ${Mr.change(`${r.kind} ${r.id}`)}`);for(let r of t.destroy)S(` ${Mr.destroy(`${r.kind} ${r.id}`)}`);S(`
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 zL(t){try{let r=new URL(t).hostname.split(".")[0];return r&&r!=="localhost"?r:void 0}catch{return}}function gi(t,e,r){return new Promise(n=>{let o=vm(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 bm(){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 gi("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 gi("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 NL(t){let e=$e(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=Ct(o,i.name);if(i.isDirectory())await n(a);else if(i.isFile()){let c=Zc(e,a).split(_m).join("/");r[c]=await ye.readFile(a,"utf8")}}};return await n(e),r}function wm(t){return new Promise(e=>{let r=vm("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 jL=!1;jL&&xm().parseAsync(process.argv).catch(t=>x(t instanceof Error?t.message:String(t)));xm().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
2199
+ turbobase release status ${M.releaseId} --follow`)}catch(M){M instanceof pe&&M.status===403&&v("an approved target needs --approved-by (the deploy gate fails closed)."),M instanceof pe&&M.status===409&&v("that solution already has an active release \u2014 roll it back or wait for it."),oe(M,"releases:write","push a release"),v(`release push failed: ${M instanceof Error?M.message:String(M)}`)}}),Bn.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:S}=await re(h.baseUrl),$=new X({baseUrl:_,token:S});if(h.follow){await Gl(()=>$.releaseStatus(p),`release ${p}`,h.intervalMs);return}let y;try{y=await $.releaseStatus(p)}catch(T){oe(T,"releases:write","release status"),T instanceof pe&&T.status===404&&v(`release ${p} not found.`),v(`release status failed: ${T instanceof Error?T.message:String(T)}`)}x(`release ${p}: status=${y.releaseStatus??"?"} stage=${y.stage} ${y.percent}%`+(y.runStatus?` (${y.runStatus})`:"")),y.outputTail&&x(y.outputTail.replace(/\n+$/,""))}),Bn.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:S}=await re(h.baseUrl),$=new X({baseUrl:_,token:S}),y;try{y=await $.releaseRollback(p)}catch(T){oe(T,"releases:write","release rollback"),T instanceof pe&&T.status===404&&v(`release ${p} not found.`),T instanceof pe&&T.status===409&&v(`release ${p} cannot be rolled back (not live, or a newer release advanced past it).`),v(`release rollback failed: ${T instanceof Error?T.message:String(T)}`)}x(`release ${y.releaseId} rolled back \u2192 status=${y.release?.status??"rolled_back"}.`)}),Bn.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 re(p.baseUrl),S=new X({baseUrl:h,token:_}),$;try{$=await S.releaseList()}catch(y){oe(y,"releases:write","release list"),v(`release list failed: ${y instanceof Error?y.message:String(y)}`)}if($.length===0){x("no releases.");return}if(Qe())x(Xt($.map(y=>[y.id,no(y.status),y.target,y.backend,y.solutionTitles?.length?y.solutionTitles.map(T=>`"${T}"`).join(", "):g.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let y of $){let T=y.solutionTitles?.length?` "${y.solutionTitles.join('", "')}"`:"";x(` ${y.id} ${y.status.padEnd(11)} target=${y.target} backend=${y.backend}${T}`)}x(`
2200
+ ${$.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(()=>(Y$(),J$));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(`
2201
+ `)),t&&void 0,e}function iD(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 Sm(){let t=$e(process.cwd(),Qi,ps),e;try{e=await ye.readFile(t,"utf8")}catch{v(`no bundle found at ${Qi}/${ps} \u2014 run \`turbobase ext export\` first.`)}try{return nb(e)}catch(r){v(`bundle is invalid: ${r instanceof Error?r.message:String(r)}`)}}function aD(t,e){x(`plan against ${e}:`);for(let r of t.add)x(` ${Zr.add(`${r.kind} ${r.id}`)}`);for(let r of t.change)x(` ${Zr.change(`${r.kind} ${r.id}`)}`);for(let r of t.destroy)x(` ${Zr.destroy(`${r.kind} ${r.id}`)}`);x(`
2202
+ ${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 cD(t){try{let r=new URL(t).hostname.split(".")[0];return r&&r!=="localhost"?r:void 0}catch{return}}function yi(t,e,r){return new Promise(n=>{let o=Pm(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 Tm(){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 yi("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 yi("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 lD(t){let e=$e(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=zt(o,i.name);if(i.isDirectory())await n(a);else if(i.isFile()){let c=Kc(e,a).split(Rm).join("/");r[c]=await ye.readFile(a,"utf8")}}};return await n(e),r}function Em(t){return new Promise(e=>{let r=Pm("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 uD=!1;uD&&Am().parseAsync(process.argv).catch(t=>v(t instanceof Error?t.message:String(t)));Am().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
2011
2203
  `),process.exit(1)});