@turbobase/cli 1.23.0 → 1.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,49 +1,49 @@
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 oT=Object.create;var ml=Object.defineProperty;var sT=Object.getOwnPropertyDescriptor;var iT=Object.getOwnPropertyNames;var aT=Object.getPrototypeOf,cT=Object.prototype.hasOwnProperty;var Jo=(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 C=(t,e)=>()=>(t&&(e=t(t=0)),e);var Z=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Yo=(t,e)=>{for(var r in e)ml(t,r,{get:e[r],enumerable:!0})},lT=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of iT(e))!cT.call(t,o)&&o!==r&&ml(t,o,{get:()=>e[o],enumerable:!(n=sT(e,o))||n.enumerable});return t};var gl=(t,e,r)=>(r=t!=null?oT(aT(t)):{},lT(e||!t||!t.__esModule?ml(r,"default",{value:t,enumerable:!0}):r,t));var Xo=Z(bl=>{var Ri=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}},yl=class extends Ri{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};bl.CommanderError=Ri;bl.InvalidArgumentError=yl});var Pi=Z(vl=>{var{InvalidArgumentError:uT}=Xo(),wl=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 uT(`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 dT(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}vl.Argument=wl;vl.humanReadableArgName=dT});var xl=Z(cg=>{var{humanReadableArgName:pT}=Pi(),_l=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=>pT(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(h,b){if(b){let $=`${h.padEnd(n+i)}${b}`;return r.wrap($,o-s,n+i)}return h}function c(h){return h.join(`
4
+ var aT=Object.create;var yl=Object.defineProperty;var cT=Object.getOwnPropertyDescriptor;var lT=Object.getOwnPropertyNames;var uT=Object.getPrototypeOf,dT=Object.prototype.hasOwnProperty;var Jo=(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 C=(t,e)=>()=>(t&&(e=t(t=0)),e);var Z=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Yo=(t,e)=>{for(var r in e)yl(t,r,{get:e[r],enumerable:!0})},pT=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of lT(e))!dT.call(t,o)&&o!==r&&yl(t,o,{get:()=>e[o],enumerable:!(n=cT(e,o))||n.enumerable});return t};var bl=(t,e,r)=>(r=t!=null?aT(uT(t)):{},pT(e||!t||!t.__esModule?yl(r,"default",{value:t,enumerable:!0}):r,t));var Xo=Z(vl=>{var Ri=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}},wl=class extends Ri{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};vl.CommanderError=Ri;vl.InvalidArgumentError=wl});var Pi=Z(xl=>{var{InvalidArgumentError:hT}=Xo(),_l=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 hT(`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 fT(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}xl.Argument=_l;xl.humanReadableArgName=fT});var $l=Z(ug=>{var{humanReadableArgName:mT}=Pi(),kl=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=>mT(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(h,b){if(b){let $=`${h.padEnd(n+i)}${b}`;return r.wrap($,o-s,n+i)}return h}function c(h){return h.join(`
5
5
  `).replace(/^/gm," ".repeat(s))}let l=[`Usage: ${r.commandUsage(e)}`,""],u=r.commandDescription(e);u.length>0&&(l=l.concat([r.wrap(u,o,0),""]));let p=r.visibleArguments(e).map(h=>a(r.argumentTerm(h),r.argumentDescription(h)));p.length>0&&(l=l.concat(["Arguments:",c(p),""]));let w=r.visibleOptions(e).map(h=>a(r.optionTerm(h),r.optionDescription(h)));if(w.length>0&&(l=l.concat(["Options:",c(w),""])),this.showGlobalOptions){let h=r.visibleGlobalOptions(e).map(b=>a(r.optionTerm(b),r.optionDescription(b)));h.length>0&&(l=l.concat(["Global Options:",c(h),""]))}let f=r.visibleCommands(e).map(h=>a(r.subcommandTerm(h),r.subcommandDescription(h)));return f.length>0&&(l=l.concat(["Commands:",c(f),""])),l.join(`
6
6
  `)}padWidth(e,r){return Math.max(r.longestOptionTermLength(e,r),r.longestGlobalOptionTermLength(e,r),r.longestSubcommandTermLength(e,r),r.longestArgumentTermLength(e,r))}wrap(e,r,n,o=40){let s=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",i=new RegExp(`[\\n][${s}]+`);if(e.match(i))return e;let a=r-n;if(a<o)return e;let c=e.slice(0,n),l=e.slice(n).replace(`\r
7
7
  `,`
8
8
  `),u=" ".repeat(n),w="\\s\u200B",f=new RegExp(`
9
9
  |.{1,${a-1}}([${w}]|$)|[^${w}]+?([${w}]|$)`,"g"),h=l.match(f)||[];return c+h.map((b,$)=>b===`
10
10
  `?"":($>0?u:"")+b.trimEnd()).join(`
11
- `)}};cg.Help=_l});var Sl=Z(Ai=>{var{InvalidArgumentError:hT}=Xo(),kl=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=lg(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 hT(`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 fT(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},$l=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 fT(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function lg(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}}Ai.Option=kl;Ai.splitOptionFlags=lg;Ai.DualOptions=$l});var dg=Z(ug=>{function mT(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 gT(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=mT(t,i),c=Math.max(t.length,i.length);(c-a)/c>s&&(a<o?(o=a,n=[i]):a===o&&n.push(i))}),n.sort((i,a)=>i.localeCompare(a)),r&&(n=n.map(i=>`--${i}`)),n.length>1?`
11
+ `)}};ug.Help=kl});var El=Z(Ai=>{var{InvalidArgumentError:gT}=Xo(),Sl=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=dg(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 gT(`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 yT(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Tl=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 yT(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function dg(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}}Ai.Option=Sl;Ai.splitOptionFlags=dg;Ai.DualOptions=Tl});var hg=Z(pg=>{function bT(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 wT(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=bT(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]}?)`:""}ug.suggestSimilar=gT});var yg=Z(gg=>{var yT=Jo("events").EventEmitter,Tl=Jo("child_process"),kr=Jo("path"),El=Jo("fs"),Me=Jo("process"),{Argument:bT,humanReadableArgName:wT}=Pi(),{CommanderError:Rl}=Xo(),{Help:vT}=xl(),{Option:pg,splitOptionFlags:_T,DualOptions:xT}=Sl(),{suggestSimilar:hg}=dg(),Pl=class t extends yT{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 vT,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 bT(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 pg(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 pg)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,p){let w=kr.resolve(u,p);if(El.existsSync(w))return w;if(o.includes(kr.extname(p)))return;let f=o.find(h=>El.existsSync(`${w}${h}`));if(f)return`${w}${f}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=El.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=kr.resolve(kr.dirname(u),a)}if(a){let u=s(a,i);if(!u&&!e._executableFile&&this._scriptPath){let p=kr.basename(this._scriptPath,kr.extname(this._scriptPath));p!==this._name&&(u=s(a,`${p}-${e._name}`))}i=u||i}n=o.includes(kr.extname(i));let c;Me.platform!=="win32"?n?(r.unshift(i),r=mg(Me.execArgv).concat(r),c=Tl.spawn(Me.argv[0],r,{stdio:"inherit"})):c=Tl.spawn(i,r,{stdio:"inherit"}):(r.unshift(i),r=mg(Me.execArgv).concat(r),c=Tl.spawn(Me.execPath,r,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{Me.on(p,()=>{c.killed===!1&&c.exitCode===null&&c.kill(p)})});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 p=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
13
+ (Did you mean ${n[0]}?)`:""}pg.suggestSimilar=wT});var wg=Z(bg=>{var vT=Jo("events").EventEmitter,Rl=Jo("child_process"),kr=Jo("path"),Pl=Jo("fs"),Me=Jo("process"),{Argument:_T,humanReadableArgName:xT}=Pi(),{CommanderError:Al}=Xo(),{Help:kT}=$l(),{Option:fg,splitOptionFlags:$T,DualOptions:ST}=El(),{suggestSimilar:mg}=hg(),Il=class t extends vT{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 kT,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 _T(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 Al(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 fg(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 fg)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,p){let w=kr.resolve(u,p);if(Pl.existsSync(w))return w;if(o.includes(kr.extname(p)))return;let f=o.find(h=>Pl.existsSync(`${w}${h}`));if(f)return`${w}${f}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=Pl.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=kr.resolve(kr.dirname(u),a)}if(a){let u=s(a,i);if(!u&&!e._executableFile&&this._scriptPath){let p=kr.basename(this._scriptPath,kr.extname(this._scriptPath));p!==this._name&&(u=s(a,`${p}-${e._name}`))}i=u||i}n=o.includes(kr.extname(i));let c;Me.platform!=="win32"?n?(r.unshift(i),r=yg(Me.execArgv).concat(r),c=Rl.spawn(Me.argv[0],r,{stdio:"inherit"})):c=Rl.spawn(i,r,{stdio:"inherit"}):(r.unshift(i),r=yg(Me.execArgv).concat(r),c=Rl.spawn(Me.execPath,r,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{Me.on(p,()=>{c.killed===!1&&c.exitCode===null&&c.kill(p)})});let l=this._exitCallback;l?c.on("close",()=>{l(new Al(Me.exitCode||0,"commander.executeSubCommandAsync","(close)"))}):c.on("close",Me.exit.bind(Me)),c.on("error",u=>{if(u.code==="ENOENT"){let p=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
- - ${p}`;throw new Error(w)}else if(u.code==="EACCES")throw new Error(`'${i}' not executable`);if(!l)Me.exit(1);else{let p=new Rl(1,"commander.executeSubCommandAsync","(error)");p.nestedError=u,l(p)}}),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 fg(this,r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),fg(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
+ - ${p}`;throw new Error(w)}else if(u.code==="EACCES")throw new Error(`'${i}' not executable`);if(!l)Me.exit(1);else{let p=new Al(1,"commander.executeSubCommandAsync","(error)");p.nestedError=u,l(p)}}),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 gg(this,r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),gg(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 xT(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(p=>p.negate&&a===p.attributeName()),u=this.options.find(p=>!p.negate&&a===p.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=hg(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=hg(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=>wT(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=kr.basename(e,kr.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=_T(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 ST(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(p=>p.negate&&a===p.attributeName()),u=this.options.find(p=>!p.negate&&a===p.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=mg(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=mg(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=>xT(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=kr.basename(e,kr.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=$T(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 fg(t,e){t._hasHelpOption&&e.find(n=>n===t._helpLongFlag||n===t._helpShortFlag)&&(t.outputHelp(),t._exit(0,"commander.helpDisplayed","(outputHelp)"))}function mg(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})}gg.Command=Pl});var _g=Z((Jt,vg)=>{var{Argument:kT}=Pi(),{Command:bg}=yg(),{CommanderError:$T,InvalidArgumentError:wg}=Xo(),{Help:ST}=xl(),{Option:TT}=Sl();Jt=vg.exports=new bg;Jt.program=Jt;Jt.Command=bg;Jt.Option=TT;Jt.Argument=kT;Jt.Help=ST;Jt.CommanderError=$T;Jt.InvalidArgumentError=wg;Jt.InvalidOptionArgumentError=wg});function hn(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var Qo=C(()=>{});var ye,Al,V,dr,es=C(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(ye||(ye={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Al||(Al={}));V=ye.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),dr=t=>{switch(typeof t){case"undefined":return V.undefined;case"string":return V.string;case"number":return Number.isNaN(t)?V.nan:V.number;case"boolean":return V.boolean;case"function":return V.function;case"bigint":return V.bigint;case"symbol":return V.symbol;case"object":return Array.isArray(t)?V.array:t===null?V.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?V.promise:typeof Map<"u"&&t instanceof Map?V.map:typeof Set<"u"&&t instanceof Set?V.set:typeof Date<"u"&&t instanceof Date?V.date:V.object;default:return V.unknown}}});var M,ET,_t,Ii=C(()=>{es();M=ye.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),ET=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),_t=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ye.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};_t.create=t=>new _t(t)});var RT,$r,Il=C(()=>{Ii();es();RT=(t,e)=>{let r;switch(t.code){case M.invalid_type:t.received===V.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case M.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ye.jsonStringifyReplacer)}`;break;case M.unrecognized_keys:r=`Unrecognized key(s) in object: ${ye.joinValues(t.keys,", ")}`;break;case M.invalid_union:r="Invalid input";break;case M.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ye.joinValues(t.options)}`;break;case M.invalid_enum_value:r=`Invalid enum value. Expected ${ye.joinValues(t.options)}, received '${t.received}'`;break;case M.invalid_arguments:r="Invalid function arguments";break;case M.invalid_return_type:r="Invalid function return type";break;case M.invalid_date:r="Invalid date";break;case M.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ye.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case M.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 M.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 M.custom:r="Invalid input";break;case M.invalid_intersection_types:r="Intersection results could not be merged";break;case M.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case M.not_finite:r="Number must be finite";break;default:r=e.defaultError,ye.assertNever(t)}return{message:r}},$r=RT});function PT(t){$g=t}function to(){return $g}var $g,Oi=C(()=>{Il();$g=$r});function F(t,e){let r=to(),n=ts({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===$r?void 0:$r].filter(o=>!!o)});t.common.issues.push(n)}var ts,AT,nt,re,fn,ut,Ci,Ni,Ur,ro,Ol=C(()=>{Oi();Il();ts=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}},AT=[];nt=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 re;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 re;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}}},re=Object.freeze({status:"aborted"}),fn=t=>({status:"dirty",value:t}),ut=t=>({status:"valid",value:t}),Ci=t=>t.status==="aborted",Ni=t=>t.status==="dirty",Ur=t=>t.status==="valid",ro=t=>typeof Promise<"u"&&t instanceof Promise});var Sg=C(()=>{});var G,Tg=C(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(G||(G={}))});function ue(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 Ag(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 KT(t){return new RegExp(`^${Ag(t)}$`)}function Ig(t){let e=`${Pg}T${Ag(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 WT(t,e){return!!((e==="v4"||!e)&&UT.test(t)||(e==="v6"||!e)&&BT.test(t))}function GT(t,e){if(!jT.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 JT(t,e){return!!((e==="v4"||!e)&&qT.test(t)||(e==="v6"||!e)&&ZT.test(t))}function YT(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 no(t){if(t instanceof kt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=xt.create(no(n))}return new kt({...t._def,shape:()=>e})}else return t instanceof Er?new Er({...t._def,type:no(t.element)}):t instanceof xt?xt.create(no(t.unwrap())):t instanceof hr?hr.create(no(t.unwrap())):t instanceof pr?pr.create(t.items.map(e=>no(e))):t}function Nl(t,e){let r=dr(t),n=dr(e);if(t===e)return{valid:!0,data:t};if(r===V.object&&n===V.object){let o=ye.objectKeys(e),s=ye.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=Nl(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===V.array&&n===V.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=Nl(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===V.date&&n===V.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function Og(t,e){return new Sn({values:t,typeName:U.ZodEnum,...ue(e)})}function Rg(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Cg(t,e={},r){return t?Br.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Rg(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Rg(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Br.create()}var jt,Eg,pe,IT,OT,CT,NT,zT,jT,LT,DT,MT,Cl,UT,qT,BT,ZT,FT,HT,Pg,VT,qr,mn,gn,yn,bn,oo,wn,vn,Br,Tr,Yt,so,Er,kt,_n,Sr,zi,xn,pr,ji,io,ao,Li,kn,$n,Sn,Tn,Zr,Lt,xt,hr,En,Rn,co,XT,rs,ns,Pn,QT,U,eE,Ng,zg,tE,rE,jg,nE,oE,sE,iE,aE,cE,lE,uE,dE,zl,pE,hE,fE,mE,gE,yE,bE,wE,vE,_E,xE,kE,$E,SE,TE,EE,RE,PE,AE,IE,OE,CE,NE,zE,Lg=C(()=>{Ii();Oi();Tg();Ol();es();jt=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}},Eg=(t,e)=>{if(Ur(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 _t(t.common.issues);return this._error=r,this._error}}};pe=class{get description(){return this._def.description}_getType(e){return dr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:dr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new nt,ctx:{common:e.parent.common,data:e.data,parsedType:dr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(ro(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:dr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Eg(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:dr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Ur(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=>Ur(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:dr(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(ro(o)?o:Promise.resolve(o));return Eg(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:M.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 Lt({schema:this,typeName:U.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 hr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Er.create(this)}promise(){return Zr.create(this,this._def)}or(e){return _n.create([this,e],this._def)}and(e){return xn.create(this,e,this._def)}transform(e){return new Lt({...ue(this._def),schema:this,typeName:U.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new En({...ue(this._def),innerType:this,defaultValue:r,typeName:U.ZodDefault})}brand(){return new rs({typeName:U.ZodBranded,type:this,...ue(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Rn({...ue(this._def),innerType:this,catchValue:r,typeName:U.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return ns.create(this,e)}readonly(){return Pn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},IT=/^c[^\s-]{8,}$/i,OT=/^[0-9a-z]+$/,CT=/^[0-9A-HJKMNP-TV-Z]{26}$/i,NT=/^[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,zT=/^[a-z0-9_-]{21}$/i,jT=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,LT=/^[-+]?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)?)??$/,DT=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,MT="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",UT=/^(?:(?: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])$/,qT=/^(?:(?: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])$/,BT=/^(([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]))$/,ZT=/^(([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])$/,FT=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,HT=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Pg="((\\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])))",VT=new RegExp(`^${Pg}$`);qr=class t extends pe{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==V.string){let s=this._getOrReturnCtx(e);return F(s,{code:M.invalid_type,expected:V.string,received:s.parsedType}),re}let n=new nt,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),F(o,{code:M.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),F(o,{code:M.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?F(o,{code:M.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&F(o,{code:M.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")DT.test(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{validation:"email",code:M.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Cl||(Cl=new RegExp(MT,"u")),Cl.test(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{validation:"emoji",code:M.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")NT.test(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{validation:"uuid",code:M.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")zT.test(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{validation:"nanoid",code:M.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")IT.test(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{validation:"cuid",code:M.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")OT.test(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{validation:"cuid2",code:M.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")CT.test(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{validation:"ulid",code:M.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),F(o,{validation:"url",code:M.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),F(o,{validation:"regex",code:M.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),F(o,{code:M.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),F(o,{code:M.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),F(o,{code:M.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Ig(s).test(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{code:M.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?VT.test(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{code:M.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?KT(s).test(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{code:M.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?LT.test(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{validation:"duration",code:M.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?WT(e.data,s.version)||(o=this._getOrReturnCtx(e,o),F(o,{validation:"ip",code:M.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?GT(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),F(o,{validation:"jwt",code:M.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?JT(e.data,s.version)||(o=this._getOrReturnCtx(e,o),F(o,{validation:"cidr",code:M.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?FT.test(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{validation:"base64",code:M.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?HT.test(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{validation:"base64url",code:M.invalid_string,message:s.message}),n.dirty()):ye.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:M.invalid_string,...G.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...G.errToObj(e)})}url(e){return this._addCheck({kind:"url",...G.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...G.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...G.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...G.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...G.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...G.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...G.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...G.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...G.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...G.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...G.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...G.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,...G.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,...G.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...G.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...G.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...G.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...G.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...G.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...G.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...G.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...G.errToObj(r)})}nonempty(e){return this.min(1,G.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}};qr.create=t=>new qr({checks:[],typeName:U.ZodString,coerce:t?.coerce??!1,...ue(t)});mn=class t extends pe{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)!==V.number){let s=this._getOrReturnCtx(e);return F(s,{code:M.invalid_type,expected:V.number,received:s.parsedType}),re}let n,o=new nt;for(let s of this._def.checks)s.kind==="int"?ye.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{code:M.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),F(n,{code:M.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),F(n,{code:M.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?YT(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),F(n,{code:M.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{code:M.not_finite,message:s.message}),o.dirty()):ye.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,G.toString(r))}gt(e,r){return this.setLimit("min",e,!1,G.toString(r))}lte(e,r){return this.setLimit("max",e,!0,G.toString(r))}lt(e,r){return this.setLimit("max",e,!1,G.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:G.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:G.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:G.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:G.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:G.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:G.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:G.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:G.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:G.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:G.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ye.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};mn.create=t=>new mn({checks:[],typeName:U.ZodNumber,coerce:t?.coerce||!1,...ue(t)});gn=class t extends pe{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)!==V.bigint)return this._getInvalidInput(e);let n,o=new nt;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),F(n,{code:M.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),F(n,{code:M.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),F(n,{code:M.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ye.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return F(r,{code:M.invalid_type,expected:V.bigint,received:r.parsedType}),re}gte(e,r){return this.setLimit("min",e,!0,G.toString(r))}gt(e,r){return this.setLimit("min",e,!1,G.toString(r))}lte(e,r){return this.setLimit("max",e,!0,G.toString(r))}lt(e,r){return this.setLimit("max",e,!1,G.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:G.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:G.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:G.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:G.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:G.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:G.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}};gn.create=t=>new gn({checks:[],typeName:U.ZodBigInt,coerce:t?.coerce??!1,...ue(t)});yn=class extends pe{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==V.boolean){let n=this._getOrReturnCtx(e);return F(n,{code:M.invalid_type,expected:V.boolean,received:n.parsedType}),re}return ut(e.data)}};yn.create=t=>new yn({typeName:U.ZodBoolean,coerce:t?.coerce||!1,...ue(t)});bn=class t extends pe{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==V.date){let s=this._getOrReturnCtx(e);return F(s,{code:M.invalid_type,expected:V.date,received:s.parsedType}),re}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return F(s,{code:M.invalid_date}),re}let n=new nt,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),F(o,{code:M.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),F(o,{code:M.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ye.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:G.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:G.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}};bn.create=t=>new bn({checks:[],coerce:t?.coerce||!1,typeName:U.ZodDate,...ue(t)});oo=class extends pe{_parse(e){if(this._getType(e)!==V.symbol){let n=this._getOrReturnCtx(e);return F(n,{code:M.invalid_type,expected:V.symbol,received:n.parsedType}),re}return ut(e.data)}};oo.create=t=>new oo({typeName:U.ZodSymbol,...ue(t)});wn=class extends pe{_parse(e){if(this._getType(e)!==V.undefined){let n=this._getOrReturnCtx(e);return F(n,{code:M.invalid_type,expected:V.undefined,received:n.parsedType}),re}return ut(e.data)}};wn.create=t=>new wn({typeName:U.ZodUndefined,...ue(t)});vn=class extends pe{_parse(e){if(this._getType(e)!==V.null){let n=this._getOrReturnCtx(e);return F(n,{code:M.invalid_type,expected:V.null,received:n.parsedType}),re}return ut(e.data)}};vn.create=t=>new vn({typeName:U.ZodNull,...ue(t)});Br=class extends pe{constructor(){super(...arguments),this._any=!0}_parse(e){return ut(e.data)}};Br.create=t=>new Br({typeName:U.ZodAny,...ue(t)});Tr=class extends pe{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ut(e.data)}};Tr.create=t=>new Tr({typeName:U.ZodUnknown,...ue(t)});Yt=class extends pe{_parse(e){let r=this._getOrReturnCtx(e);return F(r,{code:M.invalid_type,expected:V.never,received:r.parsedType}),re}};Yt.create=t=>new Yt({typeName:U.ZodNever,...ue(t)});so=class extends pe{_parse(e){if(this._getType(e)!==V.undefined){let n=this._getOrReturnCtx(e);return F(n,{code:M.invalid_type,expected:V.void,received:n.parsedType}),re}return ut(e.data)}};so.create=t=>new so({typeName:U.ZodVoid,...ue(t)});Er=class t extends pe{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==V.array)return F(r,{code:M.invalid_type,expected:V.array,received:r.parsedType}),re;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(F(r,{code:i?M.too_big:M.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&&(F(r,{code:M.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&&(F(r,{code:M.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 jt(r,i,r.path,a)))).then(i=>nt.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new jt(r,i,r.path,a)));return nt.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:G.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:G.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:G.toString(r)}})}nonempty(e){return this.min(1,e)}};Er.create=(t,e)=>new Er({type:t,minLength:null,maxLength:null,exactLength:null,typeName:U.ZodArray,...ue(e)});kt=class t extends pe{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=ye.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==V.object){let l=this._getOrReturnCtx(e);return F(l,{code:M.invalid_type,expected:V.object,received:l.parsedType}),re}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Yt&&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],p=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new jt(o,p,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Yt){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&&(F(o,{code:M.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 p=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new jt(o,p,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let p=await u.key,w=await u.value;l.push({key:p,value:w,alwaysSet:u.alwaysSet})}return l}).then(l=>nt.mergeObjectSync(n,l)):nt.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return G.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:G.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:U.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of ye.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of ye.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return no(this)}partial(e){let r={};for(let n of ye.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ye.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof xt;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Og(ye.objectKeys(this.shape))}};kt.create=(t,e)=>new kt({shape:()=>t,unknownKeys:"strip",catchall:Yt.create(),typeName:U.ZodObject,...ue(e)});kt.strictCreate=(t,e)=>new kt({shape:()=>t,unknownKeys:"strict",catchall:Yt.create(),typeName:U.ZodObject,...ue(e)});kt.lazycreate=(t,e)=>new kt({shape:t,unknownKeys:"strip",catchall:Yt.create(),typeName:U.ZodObject,...ue(e)});_n=class extends pe{_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 _t(a.ctx.common.issues));return F(r,{code:M.invalid_union,unionErrors:i}),re}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 _t(c));return F(r,{code:M.invalid_union,unionErrors:a}),re}}get options(){return this._def.options}};_n.create=(t,e)=>new _n({options:t,typeName:U.ZodUnion,...ue(e)});Sr=t=>t instanceof kn?Sr(t.schema):t instanceof Lt?Sr(t.innerType()):t instanceof $n?[t.value]:t instanceof Sn?t.options:t instanceof Tn?ye.objectValues(t.enum):t instanceof En?Sr(t._def.innerType):t instanceof wn?[void 0]:t instanceof vn?[null]:t instanceof xt?[void 0,...Sr(t.unwrap())]:t instanceof hr?[null,...Sr(t.unwrap())]:t instanceof rs||t instanceof Pn?Sr(t.unwrap()):t instanceof Rn?Sr(t._def.innerType):[],zi=class t extends pe{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==V.object)return F(r,{code:M.invalid_type,expected:V.object,received:r.parsedType}),re;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}):(F(r,{code:M.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),re)}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=Sr(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:U.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...ue(n)})}};xn=class extends pe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Ci(s)||Ci(i))return re;let a=Nl(s.value,i.value);return a.valid?((Ni(s)||Ni(i))&&r.dirty(),{status:r.value,value:a.data}):(F(n,{code:M.invalid_intersection_types}),re)};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}))}};xn.create=(t,e,r)=>new xn({left:t,right:e,typeName:U.ZodIntersection,...ue(r)});pr=class t extends pe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==V.array)return F(n,{code:M.invalid_type,expected:V.array,received:n.parsedType}),re;if(n.data.length<this._def.items.length)return F(n,{code:M.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),re;!this._def.rest&&n.data.length>this._def.items.length&&(F(n,{code:M.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 jt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>nt.mergeArray(r,i)):nt.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};pr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new pr({items:t,typeName:U.ZodTuple,rest:null,...ue(e)})};ji=class t extends pe{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!==V.object)return F(n,{code:M.invalid_type,expected:V.object,received:n.parsedType}),re;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new jt(n,a,n.path,a)),value:i._parse(new jt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?nt.mergeObjectAsync(r,o):nt.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof pe?new t({keyType:e,valueType:r,typeName:U.ZodRecord,...ue(n)}):new t({keyType:qr.create(),valueType:e,typeName:U.ZodRecord,...ue(r)})}},io=class extends pe{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!==V.map)return F(n,{code:M.invalid_type,expected:V.map,received:n.parsedType}),re;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],l)=>({key:o._parse(new jt(n,a,n.path,[l,"key"])),value:s._parse(new jt(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 re;(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 re;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}}}};io.create=(t,e,r)=>new io({valueType:e,keyType:t,typeName:U.ZodMap,...ue(r)});ao=class t extends pe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==V.set)return F(n,{code:M.invalid_type,expected:V.set,received:n.parsedType}),re;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(F(n,{code:M.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&&(F(n,{code:M.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 re;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 jt(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:G.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:G.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};ao.create=(t,e)=>new ao({valueType:t,minSize:null,maxSize:null,typeName:U.ZodSet,...ue(e)});Li=class t extends pe{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==V.function)return F(r,{code:M.invalid_type,expected:V.function,received:r.parsedType}),re;function n(a,c){return ts({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,to(),$r].filter(l=>!!l),issueData:{code:M.invalid_arguments,argumentsError:c}})}function o(a,c){return ts({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,to(),$r].filter(l=>!!l),issueData:{code:M.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Zr){let a=this;return ut(async function(...c){let l=new _t([]),u=await a._def.args.parseAsync(c,s).catch(f=>{throw l.addIssue(n(c,f)),l}),p=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(p,s).catch(f=>{throw l.addIssue(o(p,f)),l})})}else{let a=this;return ut(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new _t([n(c,l.error)]);let u=Reflect.apply(i,this,l.data),p=a._def.returns.safeParse(u,s);if(!p.success)throw new _t([o(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:pr.create(e).rest(Tr.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||pr.create([]).rest(Tr.create()),returns:r||Tr.create(),typeName:U.ZodFunction,...ue(n)})}},kn=class extends pe{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})}};kn.create=(t,e)=>new kn({getter:t,typeName:U.ZodLazy,...ue(e)});$n=class extends pe{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return F(r,{received:r.data,code:M.invalid_literal,expected:this._def.value}),re}return{status:"valid",value:e.data}}get value(){return this._def.value}};$n.create=(t,e)=>new $n({value:t,typeName:U.ZodLiteral,...ue(e)});Sn=class t extends pe{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return F(r,{expected:ye.joinValues(n),received:r.parsedType,code:M.invalid_type}),re}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 F(r,{received:r.data,code:M.invalid_enum_value,options:n}),re}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})}};Sn.create=Og;Tn=class extends pe{_parse(e){let r=ye.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==V.string&&n.parsedType!==V.number){let o=ye.objectValues(r);return F(n,{expected:ye.joinValues(o),received:n.parsedType,code:M.invalid_type}),re}if(this._cache||(this._cache=new Set(ye.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ye.objectValues(r);return F(n,{received:n.data,code:M.invalid_enum_value,options:o}),re}return ut(e.data)}get enum(){return this._def.values}};Tn.create=(t,e)=>new Tn({values:t,typeName:U.ZodNativeEnum,...ue(e)});Zr=class extends pe{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==V.promise&&r.common.async===!1)return F(r,{code:M.invalid_type,expected:V.promise,received:r.parsedType}),re;let n=r.parsedType===V.promise?r.data:Promise.resolve(r.data);return ut(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Zr.create=(t,e)=>new Zr({type:t,typeName:U.ZodPromise,...ue(e)});Lt=class extends pe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===U.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=>{F(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 re;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?re:c.status==="dirty"?fn(c.value):r.value==="dirty"?fn(c.value):c});{if(r.value==="aborted")return re;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?re:a.status==="dirty"?fn(a.value):r.value==="dirty"?fn(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"?re:(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"?re:(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(!Ur(i))return re;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=>Ur(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):re);ye.assertNever(o)}};Lt.create=(t,e,r)=>new Lt({schema:t,typeName:U.ZodEffects,effect:e,...ue(r)});Lt.createWithPreprocess=(t,e,r)=>new Lt({schema:e,effect:{type:"preprocess",transform:t},typeName:U.ZodEffects,...ue(r)});xt=class extends pe{_parse(e){return this._getType(e)===V.undefined?ut(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};xt.create=(t,e)=>new xt({innerType:t,typeName:U.ZodOptional,...ue(e)});hr=class extends pe{_parse(e){return this._getType(e)===V.null?ut(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};hr.create=(t,e)=>new hr({innerType:t,typeName:U.ZodNullable,...ue(e)});En=class extends pe{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===V.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};En.create=(t,e)=>new En({innerType:t,typeName:U.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ue(e)});Rn=class extends pe{_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 ro(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new _t(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new _t(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Rn.create=(t,e)=>new Rn({innerType:t,typeName:U.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ue(e)});co=class extends pe{_parse(e){if(this._getType(e)!==V.nan){let n=this._getOrReturnCtx(e);return F(n,{code:M.invalid_type,expected:V.nan,received:n.parsedType}),re}return{status:"valid",value:e.data}}};co.create=t=>new co({typeName:U.ZodNaN,...ue(t)});XT=Symbol("zod_brand"),rs=class extends pe{_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}},ns=class t extends pe{_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"?re:s.status==="dirty"?(r.dirty(),fn(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"?re: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:U.ZodPipeline})}},Pn=class extends pe{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Ur(o)&&(o.value=Object.freeze(o.value)),o);return ro(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Pn.create=(t,e)=>new Pn({innerType:t,typeName:U.ZodReadonly,...ue(e)});QT={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"})(U||(U={}));eE=(t,e={message:`Input not instance of ${t.name}`})=>Cg(r=>r instanceof t,e),Ng=qr.create,zg=mn.create,tE=co.create,rE=gn.create,jg=yn.create,nE=bn.create,oE=oo.create,sE=wn.create,iE=vn.create,aE=Br.create,cE=Tr.create,lE=Yt.create,uE=so.create,dE=Er.create,zl=kt.create,pE=kt.strictCreate,hE=_n.create,fE=zi.create,mE=xn.create,gE=pr.create,yE=ji.create,bE=io.create,wE=ao.create,vE=Li.create,_E=kn.create,xE=$n.create,kE=Sn.create,$E=Tn.create,SE=Zr.create,TE=Lt.create,EE=xt.create,RE=hr.create,PE=Lt.createWithPreprocess,AE=ns.create,IE=()=>Ng().optional(),OE=()=>zg().optional(),CE=()=>jg().optional(),NE={string:(t=>qr.create({...t,coerce:!0})),number:(t=>mn.create({...t,coerce:!0})),boolean:(t=>yn.create({...t,coerce:!0})),bigint:(t=>gn.create({...t,coerce:!0})),date:(t=>bn.create({...t,coerce:!0}))},zE=re});var A={};Yo(A,{BRAND:()=>XT,DIRTY:()=>fn,EMPTY_PATH:()=>AT,INVALID:()=>re,NEVER:()=>zE,OK:()=>ut,ParseStatus:()=>nt,Schema:()=>pe,ZodAny:()=>Br,ZodArray:()=>Er,ZodBigInt:()=>gn,ZodBoolean:()=>yn,ZodBranded:()=>rs,ZodCatch:()=>Rn,ZodDate:()=>bn,ZodDefault:()=>En,ZodDiscriminatedUnion:()=>zi,ZodEffects:()=>Lt,ZodEnum:()=>Sn,ZodError:()=>_t,ZodFirstPartyTypeKind:()=>U,ZodFunction:()=>Li,ZodIntersection:()=>xn,ZodIssueCode:()=>M,ZodLazy:()=>kn,ZodLiteral:()=>$n,ZodMap:()=>io,ZodNaN:()=>co,ZodNativeEnum:()=>Tn,ZodNever:()=>Yt,ZodNull:()=>vn,ZodNullable:()=>hr,ZodNumber:()=>mn,ZodObject:()=>kt,ZodOptional:()=>xt,ZodParsedType:()=>V,ZodPipeline:()=>ns,ZodPromise:()=>Zr,ZodReadonly:()=>Pn,ZodRecord:()=>ji,ZodSchema:()=>pe,ZodSet:()=>ao,ZodString:()=>qr,ZodSymbol:()=>oo,ZodTransformer:()=>Lt,ZodTuple:()=>pr,ZodType:()=>pe,ZodUndefined:()=>wn,ZodUnion:()=>_n,ZodUnknown:()=>Tr,ZodVoid:()=>so,addIssueToContext:()=>F,any:()=>aE,array:()=>dE,bigint:()=>rE,boolean:()=>jg,coerce:()=>NE,custom:()=>Cg,date:()=>nE,datetimeRegex:()=>Ig,defaultErrorMap:()=>$r,discriminatedUnion:()=>fE,effect:()=>TE,enum:()=>kE,function:()=>vE,getErrorMap:()=>to,getParsedType:()=>dr,instanceof:()=>eE,intersection:()=>mE,isAborted:()=>Ci,isAsync:()=>ro,isDirty:()=>Ni,isValid:()=>Ur,late:()=>QT,lazy:()=>_E,literal:()=>xE,makeIssue:()=>ts,map:()=>bE,nan:()=>tE,nativeEnum:()=>$E,never:()=>lE,null:()=>iE,nullable:()=>RE,number:()=>zg,object:()=>zl,objectUtil:()=>Al,oboolean:()=>CE,onumber:()=>OE,optional:()=>EE,ostring:()=>IE,pipeline:()=>AE,preprocess:()=>PE,promise:()=>SE,quotelessJson:()=>ET,record:()=>yE,set:()=>wE,setErrorMap:()=>PT,strictObject:()=>pE,string:()=>Ng,symbol:()=>oE,transformer:()=>TE,tuple:()=>gE,undefined:()=>sE,union:()=>hE,unknown:()=>cE,util:()=>ye,void:()=>uE});var Di=C(()=>{Oi();Ol();Sg();es();Lg();Ii()});var An=C(()=>{Di();Di()});function Mi(t){let e=jl.safeParse(t);return e.success?(e.data.inputs??[]).filter(r=>r.type==="connection"):[]}function Ll(t,e){let r=jl.safeParse(t);if(!r.success)throw new Fr(`invalid manifest: ${r.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}`);if(Dg.test(e))throw new Fr('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(Dg.test(n))throw new Fr("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var Mg,Ug,jl,Fr,Dg,qg=C(()=>{An();Mg=A.object({type:A.literal("connection"),source_system:A.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:A.string().min(1).max(200).optional()}),Ug=A.discriminatedUnion("type",[Mg]),jl=A.object({inputs:A.array(Ug).optional()}).passthrough(),Fr=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};Dg=/\bconnection[_-]?id\b["']?\s*[:=]/i});var Ui,Dl=C(()=>{Ui=["before_read","before_save","after_save","before_delete","after_delete","before_sync","after_sync","on_sync_failure"]});var Ml,Bg,Zg=C(()=>{An();Qo();Dl();Ml=A.object({id:A.string().min(1,"hook id must be non-empty"),recordType:A.union([A.string().min(1),A.array(A.string().min(1)).min(1),A.literal("*")]),event:A.enum(Ui),source:A.string().min(1).optional(),when:A.unknown().optional(),run:A.unknown(),failClosed:A.boolean().optional(),timeoutMs:A.number().int().positive().optional(),description:A.string().optional(),systemReserved:A.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"})}),Bg=hn({kind:"hook",schema:Ml,factoryName:"defineHook"})});var Fg=C(()=>{Zg();Dl()});var qi,Ul=C(()=>{qi=["after_canonicalize_inbound","after_sync_success_outbound"]});var Hg,ql,Vg,Kg=C(()=>{An();Qo();Ul();Hg=A.object({source:A.string().min(1,"to.source must be non-empty"),recordType:A.string().min(1,"to.recordType must be non-empty")}),ql=A.object({id:A.string().min(1,"conduit id must be non-empty"),on:A.enum(qi),from:A.object({source:A.string().min(1,"from.source must be non-empty"),recordType:A.string().min(1,"from.recordType must be non-empty"),when:A.unknown().optional()}),to:Hg.optional(),mode:A.enum(["dual-bind","one-shot"]).optional(),transform:A.unknown().optional(),sequence:A.array(A.object({to:Hg,transform:A.unknown(),awaitSource:A.boolean().optional()})).optional(),idempotencyKey:A.unknown().optional(),cycleBudget:A.number().int().positive().optional(),conflictStrategy:A.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:A.number().int().positive().optional(),description:A.string().optional(),systemReserved:A.boolean().optional()}).superRefine((t,e)=>{let r=t,n=r.to!==void 0||r.transform!==void 0,o=r.sequence!==void 0;n&&o?e.addIssue({code:"custom",path:["sequence"],message:"declare EITHER `to` + `transform` OR `sequence` \u2014 not both"}):!n&&!o?e.addIssue({code:"custom",path:["to"],message:"a conduit needs a target: `to` + `transform`, or an ordered `sequence` of them"}):o?(r.sequence.length===0&&e.addIssue({code:"custom",path:["sequence"],message:"sequence must declare at least one target"}),r.sequence.forEach((l,u)=>{typeof l.transform!="function"&&e.addIssue({code:"custom",path:["sequence",u,"transform"],message:"transform must be a function"}),r.from?.source&&l.to?.source&&r.from.source===l.to.source&&e.addIssue({code:"custom",path:["sequence",u,"to","source"],message:"a conduit must bridge two DIFFERENT sources (from.source === to.source) \u2014 use a hook for an intra-source transform"})})):(r.to===void 0&&e.addIssue({code:"custom",path:["to"],message:"`to` is required beside `transform`"}),typeof r.transform!="function"&&e.addIssue({code:"custom",path:["transform"],message:"transform must be a function"}));let s=t.from?.when;s!==void 0&&typeof s!="function"&&e.addIssue({code:"custom",path:["from","when"],message:"from.when, when present, must be a function"});let i=t.idempotencyKey;i!==void 0&&typeof i!="function"&&e.addIssue({code:"custom",path:["idempotencyKey"],message:"idempotencyKey, when present, must be a function"});let a=r.from,c=r.to;a?.source&&c?.source&&a.source===c.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"})}),Vg=hn({kind:"conduit",schema:ql,factoryName:"defineConduit"})});var Wg=C(()=>{Kg();Ul()});var Bl,Gg,Jg=C(()=>{An();Qo();Bl=A.object({id:A.string().min(1,"process id must be non-empty"),input:A.object({type:A.literal("object"),properties:A.record(A.unknown()).optional(),required:A.array(A.string()).optional()}).passthrough(),steps:A.array(A.object({id:A.string().min(1,"step id must be non-empty"),recordType:A.string().min(1,"step.recordType must be non-empty"),awaitSource:A.boolean().optional(),build:A.unknown(),description:A.string().optional()})).min(1,"a process needs at least one step"),eachRow:A.object({outstanding:A.unknown(),key:A.string().min(1,"eachRow.key must name the column that identifies an outstanding row")}).optional(),onFailure:A.enum(["stop","rollback"]).optional(),description:A.string().optional()}).superRefine((t,e)=>{let r=t.eachRow;r&&typeof r.outstanding!="function"&&e.addIssue({code:"custom",path:["eachRow","outstanding"],message:"eachRow.outstanding must be a function returning one PostgREST query for the rows still to migrate"});let n=t.steps;if(!Array.isArray(n))return;let o=new Map;n.forEach((s,i)=>{let a=s;if(typeof a.build!="function"&&e.addIssue({code:"custom",path:["steps",i,"build"],message:"build must be a function"}),typeof a.id=="string"){let c=o.get(a.id);c!==void 0?e.addIssue({code:"custom",path:["steps"],message:`duplicate step id '${a.id}' (steps ${c} and ${i}) \u2014 step ids must be unique within a process`}):o.set(a.id,i)}})}),Gg=hn({kind:"process",schema:Bl,factoryName:"defineProcess"})});var Yg=C(()=>{});var Xg=C(()=>{Jg();Yg()});async function HE(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 Bi(t,e={}){return(e.transform??HE)(t)}var Zl=C(()=>{});function Fl(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 Qg(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Hl(t){return`${Qg(t.source)}${Qg(t.recordType)}`}function VE(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function KE(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.currencyKey&&e.push(`currency from ${t.currencyKey}`),t.description&&e.push(t.description),e.join(" \xB7 ")}function Vl(t){let e=Hl(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 gg(t,e){t._hasHelpOption&&e.find(n=>n===t._helpLongFlag||n===t._helpShortFlag)&&(t.outputHelp(),t._exit(0,"commander.helpDisplayed","(outputHelp)"))}function yg(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})}bg.Command=Il});var kg=Z((Jt,xg)=>{var{Argument:TT}=Pi(),{Command:vg}=wg(),{CommanderError:ET,InvalidArgumentError:_g}=Xo(),{Help:RT}=$l(),{Option:PT}=El();Jt=xg.exports=new vg;Jt.program=Jt;Jt.Command=vg;Jt.Option=PT;Jt.Argument=TT;Jt.Help=RT;Jt.CommanderError=ET;Jt.InvalidArgumentError=_g;Jt.InvalidOptionArgumentError=_g});function hn(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var Qo=C(()=>{});var ye,Ol,V,dr,es=C(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(ye||(ye={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Ol||(Ol={}));V=ye.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),dr=t=>{switch(typeof t){case"undefined":return V.undefined;case"string":return V.string;case"number":return Number.isNaN(t)?V.nan:V.number;case"boolean":return V.boolean;case"function":return V.function;case"bigint":return V.bigint;case"symbol":return V.symbol;case"object":return Array.isArray(t)?V.array:t===null?V.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?V.promise:typeof Map<"u"&&t instanceof Map?V.map:typeof Set<"u"&&t instanceof Set?V.set:typeof Date<"u"&&t instanceof Date?V.date:V.object;default:return V.unknown}}});var M,AT,_t,Ii=C(()=>{es();M=ye.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),AT=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),_t=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ye.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};_t.create=t=>new _t(t)});var IT,$r,Cl=C(()=>{Ii();es();IT=(t,e)=>{let r;switch(t.code){case M.invalid_type:t.received===V.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case M.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ye.jsonStringifyReplacer)}`;break;case M.unrecognized_keys:r=`Unrecognized key(s) in object: ${ye.joinValues(t.keys,", ")}`;break;case M.invalid_union:r="Invalid input";break;case M.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ye.joinValues(t.options)}`;break;case M.invalid_enum_value:r=`Invalid enum value. Expected ${ye.joinValues(t.options)}, received '${t.received}'`;break;case M.invalid_arguments:r="Invalid function arguments";break;case M.invalid_return_type:r="Invalid function return type";break;case M.invalid_date:r="Invalid date";break;case M.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ye.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case M.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 M.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 M.custom:r="Invalid input";break;case M.invalid_intersection_types:r="Intersection results could not be merged";break;case M.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case M.not_finite:r="Number must be finite";break;default:r=e.defaultError,ye.assertNever(t)}return{message:r}},$r=IT});function OT(t){Tg=t}function to(){return Tg}var Tg,Oi=C(()=>{Cl();Tg=$r});function F(t,e){let r=to(),n=ts({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===$r?void 0:$r].filter(o=>!!o)});t.common.issues.push(n)}var ts,CT,nt,re,fn,ut,Ci,Ni,Ur,ro,Nl=C(()=>{Oi();Cl();ts=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}},CT=[];nt=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 re;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 re;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}}},re=Object.freeze({status:"aborted"}),fn=t=>({status:"dirty",value:t}),ut=t=>({status:"valid",value:t}),Ci=t=>t.status==="aborted",Ni=t=>t.status==="dirty",Ur=t=>t.status==="valid",ro=t=>typeof Promise<"u"&&t instanceof Promise});var Eg=C(()=>{});var G,Rg=C(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(G||(G={}))});function ue(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 Og(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 JT(t){return new RegExp(`^${Og(t)}$`)}function Cg(t){let e=`${Ig}T${Og(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 YT(t,e){return!!((e==="v4"||!e)&&ZT.test(t)||(e==="v6"||!e)&&HT.test(t))}function XT(t,e){if(!MT.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 QT(t,e){return!!((e==="v4"||!e)&&FT.test(t)||(e==="v6"||!e)&&VT.test(t))}function eE(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 no(t){if(t instanceof kt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=xt.create(no(n))}return new kt({...t._def,shape:()=>e})}else return t instanceof Er?new Er({...t._def,type:no(t.element)}):t instanceof xt?xt.create(no(t.unwrap())):t instanceof hr?hr.create(no(t.unwrap())):t instanceof pr?pr.create(t.items.map(e=>no(e))):t}function jl(t,e){let r=dr(t),n=dr(e);if(t===e)return{valid:!0,data:t};if(r===V.object&&n===V.object){let o=ye.objectKeys(e),s=ye.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=jl(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===V.array&&n===V.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=jl(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===V.date&&n===V.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function Ng(t,e){return new Sn({values:t,typeName:U.ZodEnum,...ue(e)})}function Ag(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function zg(t,e={},r){return t?Br.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Ag(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Ag(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Br.create()}var jt,Pg,pe,NT,zT,jT,LT,DT,MT,UT,qT,BT,zl,ZT,FT,HT,VT,KT,WT,Ig,GT,qr,mn,gn,yn,bn,oo,wn,vn,Br,Tr,Yt,so,Er,kt,_n,Sr,zi,xn,pr,ji,io,ao,Li,kn,$n,Sn,Tn,Zr,Lt,xt,hr,En,Rn,co,tE,rs,ns,Pn,rE,U,nE,jg,Lg,oE,sE,Dg,iE,aE,cE,lE,uE,dE,pE,hE,fE,Ll,mE,gE,yE,bE,wE,vE,_E,xE,kE,$E,SE,TE,EE,RE,PE,AE,IE,OE,CE,NE,zE,jE,LE,DE,Mg=C(()=>{Ii();Oi();Rg();Nl();es();jt=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}},Pg=(t,e)=>{if(Ur(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 _t(t.common.issues);return this._error=r,this._error}}};pe=class{get description(){return this._def.description}_getType(e){return dr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:dr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new nt,ctx:{common:e.parent.common,data:e.data,parsedType:dr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(ro(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:dr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Pg(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:dr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Ur(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=>Ur(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:dr(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(ro(o)?o:Promise.resolve(o));return Pg(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:M.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 Lt({schema:this,typeName:U.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 hr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Er.create(this)}promise(){return Zr.create(this,this._def)}or(e){return _n.create([this,e],this._def)}and(e){return xn.create(this,e,this._def)}transform(e){return new Lt({...ue(this._def),schema:this,typeName:U.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new En({...ue(this._def),innerType:this,defaultValue:r,typeName:U.ZodDefault})}brand(){return new rs({typeName:U.ZodBranded,type:this,...ue(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Rn({...ue(this._def),innerType:this,catchValue:r,typeName:U.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return ns.create(this,e)}readonly(){return Pn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},NT=/^c[^\s-]{8,}$/i,zT=/^[0-9a-z]+$/,jT=/^[0-9A-HJKMNP-TV-Z]{26}$/i,LT=/^[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,DT=/^[a-z0-9_-]{21}$/i,MT=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,UT=/^[-+]?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)?)??$/,qT=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,BT="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ZT=/^(?:(?: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])$/,FT=/^(?:(?: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])$/,HT=/^(([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]))$/,VT=/^(([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])$/,KT=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,WT=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ig="((\\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])))",GT=new RegExp(`^${Ig}$`);qr=class t extends pe{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==V.string){let s=this._getOrReturnCtx(e);return F(s,{code:M.invalid_type,expected:V.string,received:s.parsedType}),re}let n=new nt,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),F(o,{code:M.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),F(o,{code:M.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?F(o,{code:M.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&F(o,{code:M.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")qT.test(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{validation:"email",code:M.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")zl||(zl=new RegExp(BT,"u")),zl.test(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{validation:"emoji",code:M.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")LT.test(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{validation:"uuid",code:M.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")DT.test(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{validation:"nanoid",code:M.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")NT.test(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{validation:"cuid",code:M.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")zT.test(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{validation:"cuid2",code:M.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")jT.test(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{validation:"ulid",code:M.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),F(o,{validation:"url",code:M.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),F(o,{validation:"regex",code:M.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),F(o,{code:M.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),F(o,{code:M.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),F(o,{code:M.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Cg(s).test(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{code:M.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?GT.test(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{code:M.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?JT(s).test(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{code:M.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?UT.test(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{validation:"duration",code:M.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?YT(e.data,s.version)||(o=this._getOrReturnCtx(e,o),F(o,{validation:"ip",code:M.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?XT(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),F(o,{validation:"jwt",code:M.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?QT(e.data,s.version)||(o=this._getOrReturnCtx(e,o),F(o,{validation:"cidr",code:M.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?KT.test(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{validation:"base64",code:M.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?WT.test(e.data)||(o=this._getOrReturnCtx(e,o),F(o,{validation:"base64url",code:M.invalid_string,message:s.message}),n.dirty()):ye.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:M.invalid_string,...G.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...G.errToObj(e)})}url(e){return this._addCheck({kind:"url",...G.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...G.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...G.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...G.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...G.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...G.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...G.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...G.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...G.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...G.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...G.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...G.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,...G.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,...G.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...G.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...G.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...G.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...G.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...G.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...G.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...G.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...G.errToObj(r)})}nonempty(e){return this.min(1,G.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}};qr.create=t=>new qr({checks:[],typeName:U.ZodString,coerce:t?.coerce??!1,...ue(t)});mn=class t extends pe{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)!==V.number){let s=this._getOrReturnCtx(e);return F(s,{code:M.invalid_type,expected:V.number,received:s.parsedType}),re}let n,o=new nt;for(let s of this._def.checks)s.kind==="int"?ye.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{code:M.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),F(n,{code:M.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),F(n,{code:M.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?eE(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),F(n,{code:M.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),F(n,{code:M.not_finite,message:s.message}),o.dirty()):ye.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,G.toString(r))}gt(e,r){return this.setLimit("min",e,!1,G.toString(r))}lte(e,r){return this.setLimit("max",e,!0,G.toString(r))}lt(e,r){return this.setLimit("max",e,!1,G.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:G.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:G.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:G.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:G.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:G.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:G.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:G.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:G.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:G.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:G.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ye.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};mn.create=t=>new mn({checks:[],typeName:U.ZodNumber,coerce:t?.coerce||!1,...ue(t)});gn=class t extends pe{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)!==V.bigint)return this._getInvalidInput(e);let n,o=new nt;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),F(n,{code:M.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),F(n,{code:M.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),F(n,{code:M.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ye.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return F(r,{code:M.invalid_type,expected:V.bigint,received:r.parsedType}),re}gte(e,r){return this.setLimit("min",e,!0,G.toString(r))}gt(e,r){return this.setLimit("min",e,!1,G.toString(r))}lte(e,r){return this.setLimit("max",e,!0,G.toString(r))}lt(e,r){return this.setLimit("max",e,!1,G.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:G.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:G.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:G.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:G.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:G.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:G.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}};gn.create=t=>new gn({checks:[],typeName:U.ZodBigInt,coerce:t?.coerce??!1,...ue(t)});yn=class extends pe{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==V.boolean){let n=this._getOrReturnCtx(e);return F(n,{code:M.invalid_type,expected:V.boolean,received:n.parsedType}),re}return ut(e.data)}};yn.create=t=>new yn({typeName:U.ZodBoolean,coerce:t?.coerce||!1,...ue(t)});bn=class t extends pe{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==V.date){let s=this._getOrReturnCtx(e);return F(s,{code:M.invalid_type,expected:V.date,received:s.parsedType}),re}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return F(s,{code:M.invalid_date}),re}let n=new nt,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),F(o,{code:M.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),F(o,{code:M.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ye.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:G.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:G.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}};bn.create=t=>new bn({checks:[],coerce:t?.coerce||!1,typeName:U.ZodDate,...ue(t)});oo=class extends pe{_parse(e){if(this._getType(e)!==V.symbol){let n=this._getOrReturnCtx(e);return F(n,{code:M.invalid_type,expected:V.symbol,received:n.parsedType}),re}return ut(e.data)}};oo.create=t=>new oo({typeName:U.ZodSymbol,...ue(t)});wn=class extends pe{_parse(e){if(this._getType(e)!==V.undefined){let n=this._getOrReturnCtx(e);return F(n,{code:M.invalid_type,expected:V.undefined,received:n.parsedType}),re}return ut(e.data)}};wn.create=t=>new wn({typeName:U.ZodUndefined,...ue(t)});vn=class extends pe{_parse(e){if(this._getType(e)!==V.null){let n=this._getOrReturnCtx(e);return F(n,{code:M.invalid_type,expected:V.null,received:n.parsedType}),re}return ut(e.data)}};vn.create=t=>new vn({typeName:U.ZodNull,...ue(t)});Br=class extends pe{constructor(){super(...arguments),this._any=!0}_parse(e){return ut(e.data)}};Br.create=t=>new Br({typeName:U.ZodAny,...ue(t)});Tr=class extends pe{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ut(e.data)}};Tr.create=t=>new Tr({typeName:U.ZodUnknown,...ue(t)});Yt=class extends pe{_parse(e){let r=this._getOrReturnCtx(e);return F(r,{code:M.invalid_type,expected:V.never,received:r.parsedType}),re}};Yt.create=t=>new Yt({typeName:U.ZodNever,...ue(t)});so=class extends pe{_parse(e){if(this._getType(e)!==V.undefined){let n=this._getOrReturnCtx(e);return F(n,{code:M.invalid_type,expected:V.void,received:n.parsedType}),re}return ut(e.data)}};so.create=t=>new so({typeName:U.ZodVoid,...ue(t)});Er=class t extends pe{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==V.array)return F(r,{code:M.invalid_type,expected:V.array,received:r.parsedType}),re;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(F(r,{code:i?M.too_big:M.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&&(F(r,{code:M.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&&(F(r,{code:M.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 jt(r,i,r.path,a)))).then(i=>nt.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new jt(r,i,r.path,a)));return nt.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:G.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:G.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:G.toString(r)}})}nonempty(e){return this.min(1,e)}};Er.create=(t,e)=>new Er({type:t,minLength:null,maxLength:null,exactLength:null,typeName:U.ZodArray,...ue(e)});kt=class t extends pe{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=ye.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==V.object){let l=this._getOrReturnCtx(e);return F(l,{code:M.invalid_type,expected:V.object,received:l.parsedType}),re}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Yt&&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],p=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new jt(o,p,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Yt){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&&(F(o,{code:M.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 p=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new jt(o,p,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let p=await u.key,w=await u.value;l.push({key:p,value:w,alwaysSet:u.alwaysSet})}return l}).then(l=>nt.mergeObjectSync(n,l)):nt.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return G.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:G.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:U.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of ye.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of ye.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return no(this)}partial(e){let r={};for(let n of ye.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ye.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof xt;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Ng(ye.objectKeys(this.shape))}};kt.create=(t,e)=>new kt({shape:()=>t,unknownKeys:"strip",catchall:Yt.create(),typeName:U.ZodObject,...ue(e)});kt.strictCreate=(t,e)=>new kt({shape:()=>t,unknownKeys:"strict",catchall:Yt.create(),typeName:U.ZodObject,...ue(e)});kt.lazycreate=(t,e)=>new kt({shape:t,unknownKeys:"strip",catchall:Yt.create(),typeName:U.ZodObject,...ue(e)});_n=class extends pe{_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 _t(a.ctx.common.issues));return F(r,{code:M.invalid_union,unionErrors:i}),re}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 _t(c));return F(r,{code:M.invalid_union,unionErrors:a}),re}}get options(){return this._def.options}};_n.create=(t,e)=>new _n({options:t,typeName:U.ZodUnion,...ue(e)});Sr=t=>t instanceof kn?Sr(t.schema):t instanceof Lt?Sr(t.innerType()):t instanceof $n?[t.value]:t instanceof Sn?t.options:t instanceof Tn?ye.objectValues(t.enum):t instanceof En?Sr(t._def.innerType):t instanceof wn?[void 0]:t instanceof vn?[null]:t instanceof xt?[void 0,...Sr(t.unwrap())]:t instanceof hr?[null,...Sr(t.unwrap())]:t instanceof rs||t instanceof Pn?Sr(t.unwrap()):t instanceof Rn?Sr(t._def.innerType):[],zi=class t extends pe{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==V.object)return F(r,{code:M.invalid_type,expected:V.object,received:r.parsedType}),re;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}):(F(r,{code:M.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),re)}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=Sr(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:U.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...ue(n)})}};xn=class extends pe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Ci(s)||Ci(i))return re;let a=jl(s.value,i.value);return a.valid?((Ni(s)||Ni(i))&&r.dirty(),{status:r.value,value:a.data}):(F(n,{code:M.invalid_intersection_types}),re)};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}))}};xn.create=(t,e,r)=>new xn({left:t,right:e,typeName:U.ZodIntersection,...ue(r)});pr=class t extends pe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==V.array)return F(n,{code:M.invalid_type,expected:V.array,received:n.parsedType}),re;if(n.data.length<this._def.items.length)return F(n,{code:M.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),re;!this._def.rest&&n.data.length>this._def.items.length&&(F(n,{code:M.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 jt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>nt.mergeArray(r,i)):nt.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};pr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new pr({items:t,typeName:U.ZodTuple,rest:null,...ue(e)})};ji=class t extends pe{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!==V.object)return F(n,{code:M.invalid_type,expected:V.object,received:n.parsedType}),re;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new jt(n,a,n.path,a)),value:i._parse(new jt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?nt.mergeObjectAsync(r,o):nt.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof pe?new t({keyType:e,valueType:r,typeName:U.ZodRecord,...ue(n)}):new t({keyType:qr.create(),valueType:e,typeName:U.ZodRecord,...ue(r)})}},io=class extends pe{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!==V.map)return F(n,{code:M.invalid_type,expected:V.map,received:n.parsedType}),re;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],l)=>({key:o._parse(new jt(n,a,n.path,[l,"key"])),value:s._parse(new jt(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 re;(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 re;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}}}};io.create=(t,e,r)=>new io({valueType:e,keyType:t,typeName:U.ZodMap,...ue(r)});ao=class t extends pe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==V.set)return F(n,{code:M.invalid_type,expected:V.set,received:n.parsedType}),re;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(F(n,{code:M.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&&(F(n,{code:M.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 re;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 jt(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:G.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:G.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};ao.create=(t,e)=>new ao({valueType:t,minSize:null,maxSize:null,typeName:U.ZodSet,...ue(e)});Li=class t extends pe{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==V.function)return F(r,{code:M.invalid_type,expected:V.function,received:r.parsedType}),re;function n(a,c){return ts({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,to(),$r].filter(l=>!!l),issueData:{code:M.invalid_arguments,argumentsError:c}})}function o(a,c){return ts({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,to(),$r].filter(l=>!!l),issueData:{code:M.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Zr){let a=this;return ut(async function(...c){let l=new _t([]),u=await a._def.args.parseAsync(c,s).catch(f=>{throw l.addIssue(n(c,f)),l}),p=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(p,s).catch(f=>{throw l.addIssue(o(p,f)),l})})}else{let a=this;return ut(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new _t([n(c,l.error)]);let u=Reflect.apply(i,this,l.data),p=a._def.returns.safeParse(u,s);if(!p.success)throw new _t([o(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:pr.create(e).rest(Tr.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||pr.create([]).rest(Tr.create()),returns:r||Tr.create(),typeName:U.ZodFunction,...ue(n)})}},kn=class extends pe{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})}};kn.create=(t,e)=>new kn({getter:t,typeName:U.ZodLazy,...ue(e)});$n=class extends pe{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return F(r,{received:r.data,code:M.invalid_literal,expected:this._def.value}),re}return{status:"valid",value:e.data}}get value(){return this._def.value}};$n.create=(t,e)=>new $n({value:t,typeName:U.ZodLiteral,...ue(e)});Sn=class t extends pe{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return F(r,{expected:ye.joinValues(n),received:r.parsedType,code:M.invalid_type}),re}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 F(r,{received:r.data,code:M.invalid_enum_value,options:n}),re}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})}};Sn.create=Ng;Tn=class extends pe{_parse(e){let r=ye.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==V.string&&n.parsedType!==V.number){let o=ye.objectValues(r);return F(n,{expected:ye.joinValues(o),received:n.parsedType,code:M.invalid_type}),re}if(this._cache||(this._cache=new Set(ye.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ye.objectValues(r);return F(n,{received:n.data,code:M.invalid_enum_value,options:o}),re}return ut(e.data)}get enum(){return this._def.values}};Tn.create=(t,e)=>new Tn({values:t,typeName:U.ZodNativeEnum,...ue(e)});Zr=class extends pe{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==V.promise&&r.common.async===!1)return F(r,{code:M.invalid_type,expected:V.promise,received:r.parsedType}),re;let n=r.parsedType===V.promise?r.data:Promise.resolve(r.data);return ut(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Zr.create=(t,e)=>new Zr({type:t,typeName:U.ZodPromise,...ue(e)});Lt=class extends pe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===U.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=>{F(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 re;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?re:c.status==="dirty"?fn(c.value):r.value==="dirty"?fn(c.value):c});{if(r.value==="aborted")return re;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?re:a.status==="dirty"?fn(a.value):r.value==="dirty"?fn(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"?re:(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"?re:(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(!Ur(i))return re;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=>Ur(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):re);ye.assertNever(o)}};Lt.create=(t,e,r)=>new Lt({schema:t,typeName:U.ZodEffects,effect:e,...ue(r)});Lt.createWithPreprocess=(t,e,r)=>new Lt({schema:e,effect:{type:"preprocess",transform:t},typeName:U.ZodEffects,...ue(r)});xt=class extends pe{_parse(e){return this._getType(e)===V.undefined?ut(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};xt.create=(t,e)=>new xt({innerType:t,typeName:U.ZodOptional,...ue(e)});hr=class extends pe{_parse(e){return this._getType(e)===V.null?ut(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};hr.create=(t,e)=>new hr({innerType:t,typeName:U.ZodNullable,...ue(e)});En=class extends pe{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===V.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};En.create=(t,e)=>new En({innerType:t,typeName:U.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ue(e)});Rn=class extends pe{_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 ro(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new _t(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new _t(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Rn.create=(t,e)=>new Rn({innerType:t,typeName:U.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ue(e)});co=class extends pe{_parse(e){if(this._getType(e)!==V.nan){let n=this._getOrReturnCtx(e);return F(n,{code:M.invalid_type,expected:V.nan,received:n.parsedType}),re}return{status:"valid",value:e.data}}};co.create=t=>new co({typeName:U.ZodNaN,...ue(t)});tE=Symbol("zod_brand"),rs=class extends pe{_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}},ns=class t extends pe{_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"?re:s.status==="dirty"?(r.dirty(),fn(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"?re: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:U.ZodPipeline})}},Pn=class extends pe{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Ur(o)&&(o.value=Object.freeze(o.value)),o);return ro(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Pn.create=(t,e)=>new Pn({innerType:t,typeName:U.ZodReadonly,...ue(e)});rE={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"})(U||(U={}));nE=(t,e={message:`Input not instance of ${t.name}`})=>zg(r=>r instanceof t,e),jg=qr.create,Lg=mn.create,oE=co.create,sE=gn.create,Dg=yn.create,iE=bn.create,aE=oo.create,cE=wn.create,lE=vn.create,uE=Br.create,dE=Tr.create,pE=Yt.create,hE=so.create,fE=Er.create,Ll=kt.create,mE=kt.strictCreate,gE=_n.create,yE=zi.create,bE=xn.create,wE=pr.create,vE=ji.create,_E=io.create,xE=ao.create,kE=Li.create,$E=kn.create,SE=$n.create,TE=Sn.create,EE=Tn.create,RE=Zr.create,PE=Lt.create,AE=xt.create,IE=hr.create,OE=Lt.createWithPreprocess,CE=ns.create,NE=()=>jg().optional(),zE=()=>Lg().optional(),jE=()=>Dg().optional(),LE={string:(t=>qr.create({...t,coerce:!0})),number:(t=>mn.create({...t,coerce:!0})),boolean:(t=>yn.create({...t,coerce:!0})),bigint:(t=>gn.create({...t,coerce:!0})),date:(t=>bn.create({...t,coerce:!0}))},DE=re});var A={};Yo(A,{BRAND:()=>tE,DIRTY:()=>fn,EMPTY_PATH:()=>CT,INVALID:()=>re,NEVER:()=>DE,OK:()=>ut,ParseStatus:()=>nt,Schema:()=>pe,ZodAny:()=>Br,ZodArray:()=>Er,ZodBigInt:()=>gn,ZodBoolean:()=>yn,ZodBranded:()=>rs,ZodCatch:()=>Rn,ZodDate:()=>bn,ZodDefault:()=>En,ZodDiscriminatedUnion:()=>zi,ZodEffects:()=>Lt,ZodEnum:()=>Sn,ZodError:()=>_t,ZodFirstPartyTypeKind:()=>U,ZodFunction:()=>Li,ZodIntersection:()=>xn,ZodIssueCode:()=>M,ZodLazy:()=>kn,ZodLiteral:()=>$n,ZodMap:()=>io,ZodNaN:()=>co,ZodNativeEnum:()=>Tn,ZodNever:()=>Yt,ZodNull:()=>vn,ZodNullable:()=>hr,ZodNumber:()=>mn,ZodObject:()=>kt,ZodOptional:()=>xt,ZodParsedType:()=>V,ZodPipeline:()=>ns,ZodPromise:()=>Zr,ZodReadonly:()=>Pn,ZodRecord:()=>ji,ZodSchema:()=>pe,ZodSet:()=>ao,ZodString:()=>qr,ZodSymbol:()=>oo,ZodTransformer:()=>Lt,ZodTuple:()=>pr,ZodType:()=>pe,ZodUndefined:()=>wn,ZodUnion:()=>_n,ZodUnknown:()=>Tr,ZodVoid:()=>so,addIssueToContext:()=>F,any:()=>uE,array:()=>fE,bigint:()=>sE,boolean:()=>Dg,coerce:()=>LE,custom:()=>zg,date:()=>iE,datetimeRegex:()=>Cg,defaultErrorMap:()=>$r,discriminatedUnion:()=>yE,effect:()=>PE,enum:()=>TE,function:()=>kE,getErrorMap:()=>to,getParsedType:()=>dr,instanceof:()=>nE,intersection:()=>bE,isAborted:()=>Ci,isAsync:()=>ro,isDirty:()=>Ni,isValid:()=>Ur,late:()=>rE,lazy:()=>$E,literal:()=>SE,makeIssue:()=>ts,map:()=>_E,nan:()=>oE,nativeEnum:()=>EE,never:()=>pE,null:()=>lE,nullable:()=>IE,number:()=>Lg,object:()=>Ll,objectUtil:()=>Ol,oboolean:()=>jE,onumber:()=>zE,optional:()=>AE,ostring:()=>NE,pipeline:()=>CE,preprocess:()=>OE,promise:()=>RE,quotelessJson:()=>AT,record:()=>vE,set:()=>xE,setErrorMap:()=>OT,strictObject:()=>mE,string:()=>jg,symbol:()=>aE,transformer:()=>PE,tuple:()=>wE,undefined:()=>cE,union:()=>gE,unknown:()=>dE,util:()=>ye,void:()=>hE});var Di=C(()=>{Oi();Nl();Eg();es();Mg();Ii()});var An=C(()=>{Di();Di()});function Mi(t){let e=Dl.safeParse(t);return e.success?(e.data.inputs??[]).filter(r=>r.type==="connection"):[]}function Ml(t,e){let r=Dl.safeParse(t);if(!r.success)throw new Fr(`invalid manifest: ${r.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}`);if(Ug.test(e))throw new Fr('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 Fr("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var qg,Bg,Dl,Fr,Ug,Zg=C(()=>{An();qg=A.object({type:A.literal("connection"),source_system:A.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:A.string().min(1).max(200).optional()}),Bg=A.discriminatedUnion("type",[qg]),Dl=A.object({inputs:A.array(Bg).optional()}).passthrough(),Fr=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};Ug=/\bconnection[_-]?id\b["']?\s*[:=]/i});var Ui,Ul=C(()=>{Ui=["before_read","before_save","after_save","before_delete","after_delete","before_sync","after_sync","on_sync_failure"]});var ql,Fg,Hg=C(()=>{An();Qo();Ul();ql=A.object({id:A.string().min(1,"hook id must be non-empty"),recordType:A.union([A.string().min(1),A.array(A.string().min(1)).min(1),A.literal("*")]),event:A.enum(Ui),source:A.string().min(1).optional(),when:A.unknown().optional(),run:A.unknown(),failClosed:A.boolean().optional(),timeoutMs:A.number().int().positive().optional(),description:A.string().optional(),systemReserved:A.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"})}),Fg=hn({kind:"hook",schema:ql,factoryName:"defineHook"})});var Vg=C(()=>{Hg();Ul()});var qi,Bl=C(()=>{qi=["after_canonicalize_inbound","after_sync_success_outbound"]});var Kg,qE,Wg,Zl,Gg,Jg=C(()=>{An();Qo();Bl();Kg=A.string().regex(/^[a-z_][a-z0-9_]*$/i,"must be a bare column name (letters, digits, underscore)"),qE=A.object({recordType:A.string().min(1,"reads[].recordType must be non-empty"),source:A.string().min(1).optional(),columns:A.array(Kg).min(1,"reads[].columns must name at least one column"),by:A.array(Kg).optional(),maxRows:A.number().int().positive().max(500,`reads[].maxRows cannot exceed ${500}`).optional()}),Wg=A.object({source:A.string().min(1,"to.source must be non-empty"),recordType:A.string().min(1,"to.recordType must be non-empty")}),Zl=A.object({id:A.string().min(1,"conduit id must be non-empty"),on:A.enum(qi),from:A.object({source:A.string().min(1,"from.source must be non-empty"),recordType:A.string().min(1,"from.recordType must be non-empty"),when:A.unknown().optional()}),to:Wg.optional(),mode:A.enum(["dual-bind","one-shot"]).optional(),transform:A.unknown().optional(),sequence:A.array(A.object({to:Wg,transform:A.unknown(),awaitSource:A.boolean().optional()})).optional(),reads:A.array(qE).optional(),maxQueriesPerRun:A.number().int().positive().max(32,`maxQueriesPerRun cannot exceed ${32}`).optional(),idempotencyKey:A.unknown().optional(),cycleBudget:A.number().int().positive().optional(),conflictStrategy:A.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:A.number().int().positive().optional(),description:A.string().optional(),systemReserved:A.boolean().optional()}).superRefine((t,e)=>{let r=t,n=r.to!==void 0||r.transform!==void 0,o=r.sequence!==void 0;n&&o?e.addIssue({code:"custom",path:["sequence"],message:"declare EITHER `to` + `transform` OR `sequence` \u2014 not both"}):!n&&!o?e.addIssue({code:"custom",path:["to"],message:"a conduit needs a target: `to` + `transform`, or an ordered `sequence` of them"}):o?(r.sequence.length===0&&e.addIssue({code:"custom",path:["sequence"],message:"sequence must declare at least one target"}),r.sequence.forEach((l,u)=>{typeof l.transform!="function"&&e.addIssue({code:"custom",path:["sequence",u,"transform"],message:"transform must be a function"}),r.from?.source&&l.to?.source&&r.from.source===l.to.source&&e.addIssue({code:"custom",path:["sequence",u,"to","source"],message:"a conduit must bridge two DIFFERENT sources (from.source === to.source) \u2014 use a hook for an intra-source transform"})})):(r.to===void 0&&e.addIssue({code:"custom",path:["to"],message:"`to` is required beside `transform`"}),typeof r.transform!="function"&&e.addIssue({code:"custom",path:["transform"],message:"transform must be a function"}));let s=t.from?.when;s!==void 0&&typeof s!="function"&&e.addIssue({code:"custom",path:["from","when"],message:"from.when, when present, must be a function"});let i=t.idempotencyKey;i!==void 0&&typeof i!="function"&&e.addIssue({code:"custom",path:["idempotencyKey"],message:"idempotencyKey, when present, must be a function"});let a=r.from,c=r.to;a?.source&&c?.source&&a.source===c.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"})}),Gg=hn({kind:"conduit",schema:Zl,factoryName:"defineConduit"})});var Yg=C(()=>{Jg();Bl()});var Fl,Xg,Qg=C(()=>{An();Qo();Fl=A.object({id:A.string().min(1,"process id must be non-empty"),input:A.object({type:A.literal("object"),properties:A.record(A.unknown()).optional(),required:A.array(A.string()).optional()}).passthrough(),steps:A.array(A.object({id:A.string().min(1,"step id must be non-empty"),recordType:A.string().min(1,"step.recordType must be non-empty"),awaitSource:A.boolean().optional(),build:A.unknown(),description:A.string().optional()})).min(1,"a process needs at least one step"),eachRow:A.object({outstanding:A.unknown(),key:A.string().min(1,"eachRow.key must name the column that identifies an outstanding row")}).optional(),onFailure:A.enum(["stop","rollback"]).optional(),description:A.string().optional()}).superRefine((t,e)=>{let r=t.eachRow;r&&typeof r.outstanding!="function"&&e.addIssue({code:"custom",path:["eachRow","outstanding"],message:"eachRow.outstanding must be a function returning one PostgREST query for the rows still to migrate"});let n=t.steps;if(!Array.isArray(n))return;let o=new Map;n.forEach((s,i)=>{let a=s;if(typeof a.build!="function"&&e.addIssue({code:"custom",path:["steps",i,"build"],message:"build must be a function"}),typeof a.id=="string"){let c=o.get(a.id);c!==void 0?e.addIssue({code:"custom",path:["steps"],message:`duplicate step id '${a.id}' (steps ${c} and ${i}) \u2014 step ids must be unique within a process`}):o.set(a.id,i)}})}),Xg=hn({kind:"process",schema:Fl,factoryName:"defineProcess"})});var ey=C(()=>{});var ty=C(()=>{Qg();ey()});async function YE(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 Fi(t,e={}){return(e.transform??YE)(t)}var Hl=C(()=>{});function Vl(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 ry(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Kl(t){return`${ry(t.source)}${ry(t.recordType)}`}function XE(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function QE(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.currencyKey&&e.push(`currency from ${t.currencyKey}`),t.description&&e.push(t.description),e.join(" \xB7 ")}function Wl(t){let e=Kl(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=Fl(s.pgType),a=s.nullable?"?":"",c=s.nullable?" | null":"";return` /** ${KE(s)} */
32
- ${VE(s.name)}${a}: ${i}${c};`});return`${n}
31
+ }`;let o=t.columns.map(s=>{let i=Vl(s.pgType),a=s.nullable?"?":"",c=s.nullable?" | null":"";return` /** ${QE(s)} */
32
+ ${XE(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(Vl).join(`
36
+ }`}function Hi(t){return[...t.records].sort((n,o)=>`${n.source}:${n.recordType}`.localeCompare(`${o.source}:${o.recordType}`)).map(Wl).join(`
37
37
 
38
- `)}function ey(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 WE(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function Kl(t){let e=ey(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` ${WE(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 Wl=C(()=>{});function GE(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function ty(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 In(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let r=GE(t.baseUrl),n=await ty(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=[JE,"// ----- Record shapes (from /v1/catalog/records) -----",o,"// ----- Keyset seek keys (derived from column nullability) -----",Kl(n)];if(!t.recordsOnly){let i=await ty(r.openapi,t.token,e),a=await Bi(i,t.openApi);s.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return s.join(`
38
+ `)}function ny(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 eR(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function Gl(t){let e=ny(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` ${eR(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 Jl=C(()=>{});function tR(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function oy(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 In(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let r=tR(t.baseUrl),n=await oy(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=Hi(n),s=[rR,"// ----- Record shapes (from /v1/catalog/records) -----",o,"// ----- Keyset seek keys (derived from column nullability) -----",Gl(n)];if(!t.recordsOnly){let i=await oy(r.openapi,t.token,e),a=await Fi(i,t.openApi);s.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return s.join(`
40
40
 
41
41
  `)+`
42
- `}var JE,ry=C(()=>{Zl();Wl();Wl();Zl();JE=["/**"," * 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 Gl=C(()=>{Qo();qg();Fg();Wg();Xg();ry()});import{homedir as YE}from"node:os";import{join as ny}from"node:path";import{promises as Jl}from"node:fs";function Dt(t){return t.trim().replace(/\/+$/,"")}function Fi(){let t=process.env.TURBOBASE_HOME??ny(YE(),".turbobase");return{dir:t,file:ny(t,"credentials")}}function oy(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function os(){let{file:t}=Fi(),e;try{let s=await Jl.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))oy(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))oy(i)&&(n[s]={token:i.token,updatedAt:i.updatedAt});return{active:XE(n),tenants:n}}function XE(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 Yl(t){let{dir:e,file:r}=Fi();await Jl.mkdir(e,{recursive:!0,mode:448}),await Jl.writeFile(r,JSON.stringify(t,null,2)+`
44
- `,{mode:384})}async function sy(t){let e=Dt(t.baseUrl),r=await os(),n=new Date().toISOString();return r.tenants[e]={token:t.token,updatedAt:n},r.active=e,await Yl(r),{baseUrl:e,token:t.token,updatedAt:n}}async function Xt(t){let e=await os();if(t){let s=Dt(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 Hi(t){let e=Dt(t),r=await os(),n=r.tenants[e];return n?(r.active=e,await Yl(r),{baseUrl:e,token:n.token,updatedAt:n.updatedAt}):null}async function Xl(t){let e=await os(),r=t?Dt(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 Yl(e),r}async function Rr(){let t=await os();return Object.entries(t.tenants).map(([e,r])=>({baseUrl:e,token:r.token,updatedAt:r.updatedAt}))}var ss=C(()=>{});function eu(t,e){return t!==503?!1:typeof e=="string"?!0:e?.error==="instance_unavailable"}function QE(t){if(t)try{return JSON.parse(t)}catch{return t}}function eR(t,e){if(!t)return null;let r=t.trim();if(/^\d+$/.test(r))return Number(r)*1e3;let n=Date.parse(r);return Number.isNaN(n)?null:Math.max(0,n-e)}function tR(t){let e=/retry\s+after\s+(\d+)\s*s/i.exec(t);return e?Number(e[1])*1e3:null}async function rR(t,e){let r=eR(t.headers?.get?.("retry-after"),e),n="";try{n=await t.clone().text()}catch{return{maintenance:!1,delayMs:r}}let o=QE(n),s=eu(t.status,o),i=typeof o?.error=="string"?o.error:void 0;return{maintenance:s,delayMs:r??tR(n),error:i}}function nR(t){return!!(t==null||typeof t=="string"||typeof ArrayBuffer<"u"&&ArrayBuffer.isView(t)||t instanceof ArrayBuffer||typeof URLSearchParams<"u"&&t instanceof URLSearchParams||typeof Blob<"u"&&t instanceof Blob)}function iy(t){try{let e=typeof t=="string"?t:t instanceof URL?t.href:t?.url??"";return e?new URL(e).host:"the instance"}catch{return"the instance"}}function Ql(t){return`${Math.round(t/1e3)}s`}function oR(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: ${t.host} is unavailable${e} \u2014 waiting ${Ql(t.delayMs)} before retrying (${Ql(t.remainingMs)} of the retry budget left).
45
- `)}function sR(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: gave up after ${Ql(t.waitedMs)} waiting for ${t.host} to come back${e}; ${t.attempts} ${t.attempts===1?"retry":"retries"} made.
46
- `)}function Vi(t,e={}){let r=e.budgetMs??6e5,n=e.defaultDelayMs??6e4,o=e.sleep??(l=>new Promise(u=>setTimeout(u,l))),s=e.now??(()=>Date.now()),i=e.onWait??oR,a=e.onGiveUp??sR;return async(l,u)=>{let p=s(),w=0;for(;;){let f=await t(l,u);if(f.status!==503||u&&!nR(u.body))return f;let h=r-(s()-p),{maintenance:b,delayMs:$,error:E}=await rR(f,s());if(!b)return f;if(h<=0)return w>0&&a({waitedMs:s()-p,attempts:w,host:iy(l),error:E}),f;let P=$??n;P=Math.min(Math.max(P,1e3),12e4),P=Math.min(P,h),w+=1,i({attempt:w,delayMs:P,remainingMs:h,host:iy(l),error:E}),await o(P)}}}var tu=C(()=>{});function ay(t){if(typeof t=="string")return t.trim();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():""}function iR(t){let e=t.trimStart().slice(0,200).toLowerCase();return e.startsWith("<!doctype")||e.startsWith("<html")||e.startsWith("<")}function cy(t){let e=ay(t);return typeof t=="string"&&iR(e)?aR:e.slice(0,200)}function ly(t,e){return eu(t,e)}function uy(t){return t instanceof le&&ly(t.status,t.body)}function lR(){let t=(process.env.TURBOBASE_DEBUG??"").trim().toLowerCase();return t!==""&&t!=="0"&&t!=="false"}function dy(t){return t.replace(/\/+$/,"")}function ru(t=process.env){let e=(t[lo]??"").trim(),r=(t[Ki]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function nu(t){let e;try{e=new URL(t)}catch{return`${lo} 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:`${lo} 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 le,aR,cR,ee,lo,Ki,is,Pr=C(()=>{tu();le=class extends Error{constructor(r,n,o){super(r);this.status=n;this.body=o;this.name="ApiError"}status;body};aR="the request did not reach the instance \u2014 a proxy or edge answered with an HTML page, so the server gave no detail";cR="this instance is temporarily unavailable \u2014 it is upgrading or restarting. Retry shortly.";ee=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=dy(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=e.retry===!1?r:Vi(r,e.retry??{})}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){if(lR()){let l=ay(a);throw new le(`${e} ${r} \u2192 ${s.status}${l?`: ${l}`:""}`,s.status,a)}if(ly(s.status,a))throw new le(cR,s.status,a);let c=cy(a);throw new le(`${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"})}authorConduit(e){return this.request("POST","/v1/extensions/author-conduit",{intent:e.intent,from:e.from,to:e.to,...e.intentId?{intentId:e.intentId}:{},...e.columns?.length?{columns:e.columns}:{}})}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 platformEvents(e={}){let r=new URLSearchParams;e.subsystem&&r.set("subsystem",e.subsystem),e.severity&&r.set("severity",e.severity),e.code&&r.set("code",e.code),e.since&&r.set("since",e.since),e.after&&r.set("after",e.after),e.correlationId&&r.set("correlationId",e.correlationId),e.extension&&r.set("extension",e.extension),e.conduit&&r.set("conduit",e.conduit),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/events${n}`)).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,r={}){return this.request("POST","/v1/config/apply",{bundle:e,...r.prune?{prune:!0}:{}})}async tablesList(){return(await this.request("GET","/v1/tables")).tables??[]}tablesPlan(e){return this.request("POST","/v1/tables/plan",e)}appsPlan(e){return this.request("POST","/v1/apps/plan",{writes:e.writes??[],roles:e.roles??[],labels:e.labels??[]})}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`)}},lo="TURBOBASE_REGISTRY_URL",Ki="TURBOBASE_REGISTRY_TOKEN";is=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=dy(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=cy(a);throw new le(`${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}:{}})}}});import{existsSync as uR,statSync as dR}from"node:fs";import{resolve as Wi,sep as py}from"node:path";function hy(t){if(hR.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits|processes)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function mR(t,e,r){let n=Wi(e,r),o=Wi(t);if(n!==o&&!n.startsWith(o+py))return null;let s=[n];/\.(js|mjs|cjs)$/.test(n)&&s.push(n.replace(/\.js$/,".ts"),n.replace(/\.mjs$/,".mts"),n.replace(/\.cjs$/,".cts")),/\.[cm]?[jt]sx?$/.test(n)||s.push(`${n}.ts`,`${n}.tsx`,`${n}.js`,`${n}/index.ts`,`${n}/index.js`);for(let i of s)if(i.startsWith(o+py)&&uR(i)&&dR(i).isFile())return i;return null}function fy(t){return{name:"extension-self-contained-fence",setup(e){e.onResolve({filter:/.*/},r=>{if(r.kind==="entry-point")return null;if(hy(r.path))return{path:r.path,namespace:"extension-sdk"};let n=r.path.startsWith(".")||r.path.startsWith("/");if(n&&t){let s=mR(t,r.resolveDir,r.path);if(s)return{path:s}}return{errors:[{text:`extension ${n?`imports a sibling/local file ('${r.path}')${t?" that does not resolve inside the extension\u2019s own directory":""}`:r.path.startsWith("node:")||yR(r.path)?`imports a Node builtin ('${r.path}')`:`imports an external module ('${r.path}')`} \u2014 sandboxed extensions must be self-contained. The ONLY allowed imports are the SDK factory ('@/sync/hooks' or '@turbobase/extensions') and a relative sibling inside the extension's own directory; inline everything else into the extension file.`}]}}),e.onLoad({filter:/.*/,namespace:"extension-sdk"},()=>({contents:fR,loader:"js"}))}}}function yR(t){let e=t.startsWith("node:")?t.slice(5):t;return gR.has(e.split("/")[0])}function my(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 gy(){try{return(await import("esbuild")).build}catch(t){throw my("esbuild",t)}}async function bR(){try{return(await import("isolated-vm")).default}catch(t){throw my("isolated-vm",t)}}async function Yi(t,e={}){let r=await gy(),n=e.resolveDir?Wi(e.resolveDir):void 0,o;try{o=await r({stdin:{contents:t,loader:"ts",resolveDir:n??process.cwd(),sourcefile:"extension.ts"},bundle:!0,write:!1,format:"iife",globalName:"__tb_extension_module",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[fy(n)]})}catch(s){let a=s.errors?.map(c=>c.text).filter(Boolean).join("; ");throw new Gi(a||`extension bundle failed: ${String(s)}`)}return o.outputFiles?.[0]?.text??""}async function ou(t,e){if(!/(^|\n)\s*(import|export)\s[^;]*?from\s*['"](\.|\/)/.test(t)&&!/\bimport\s*\(\s*['"](\.|\/)/.test(t))return t;let r=await gy(),n=Wi(e),o=fy(n),s={name:"extension-sdk-external",setup(a){a.onResolve({filter:/.*/},c=>c.kind==="entry-point"?null:hy(c.path)?{path:c.path,external:!0}:null)}},i;try{i=await r({stdin:{contents:t,loader:"ts",resolveDir:n,sourcefile:"extension.ts"},bundle:!0,write:!1,format:"esm",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[s,o]})}catch(a){let l=a.errors?.map(u=>u.text).filter(Boolean).join("; ");throw new Gi(l||`extension bundle failed: ${String(a)}`)}return i.outputFiles?.[0]?.text??t}async function as(t,e,r={}){let n=r.timeoutMs??Ji,o=r.memoryLimitMb??pR,s=r.member??"run",i={patches:[],logs:[]},a=await bR(),c=new a.Isolate({memoryLimit:o});try{let l=await c.createContext(),u=l.global,p=new a.Callback(B=>{let W=JSON.parse(String(B));i.rejection||(i.rejection=W)}),w=new a.Callback(B=>{i.patches.push(JSON.parse(String(B)))}),f=new a.Callback(B=>{let W=JSON.parse(String(B));i.logs.push(W)}),h=new a.Callback(B=>{i.result=JSON.parse(String(B))}),b=r.query,$=new a.Reference(async B=>{if(!b)throw new Error("ctx.query is not available in this context");return JSON.stringify(await b(String(B)))});await u.set("__tb_reject",p),await u.set("__tb_patch",w),await u.set("__tb_log",f),await u.set("__tb_result",h),await u.set("__tb_query",$),await u.set("__tb_ctx_json",JSON.stringify(wR(e)));let E=_R(t,s,r.stepIndex??0),z=await(await c.compileScript(E)).run(l,{timeout:n,promise:!0});return s==="when"?{effects:i,whenResult:!!z}:{effects:i}}finally{c.isDisposed||c.dispose()}}function wR(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,materialized:t.materialized??null,process:t.process??null}}function vR(t){return`
42
+ `}var rR,sy=C(()=>{Hl();Jl();Jl();Hl();rR=["/**"," * 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 Yl=C(()=>{Qo();Zg();Vg();Yg();ty();sy()});import{homedir as nR}from"node:os";import{join as iy}from"node:path";import{promises as Xl}from"node:fs";function Dt(t){return t.trim().replace(/\/+$/,"")}function Vi(){let t=process.env.TURBOBASE_HOME??iy(nR(),".turbobase");return{dir:t,file:iy(t,"credentials")}}function ay(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function os(){let{file:t}=Vi(),e;try{let s=await Xl.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))ay(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))ay(i)&&(n[s]={token:i.token,updatedAt:i.updatedAt});return{active:oR(n),tenants:n}}function oR(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 Ql(t){let{dir:e,file:r}=Vi();await Xl.mkdir(e,{recursive:!0,mode:448}),await Xl.writeFile(r,JSON.stringify(t,null,2)+`
44
+ `,{mode:384})}async function cy(t){let e=Dt(t.baseUrl),r=await os(),n=new Date().toISOString();return r.tenants[e]={token:t.token,updatedAt:n},r.active=e,await Ql(r),{baseUrl:e,token:t.token,updatedAt:n}}async function Xt(t){let e=await os();if(t){let s=Dt(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 Ki(t){let e=Dt(t),r=await os(),n=r.tenants[e];return n?(r.active=e,await Ql(r),{baseUrl:e,token:n.token,updatedAt:n.updatedAt}):null}async function eu(t){let e=await os(),r=t?Dt(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 Ql(e),r}async function Rr(){let t=await os();return Object.entries(t.tenants).map(([e,r])=>({baseUrl:e,token:r.token,updatedAt:r.updatedAt}))}var ss=C(()=>{});function ru(t,e){return t!==503?!1:typeof e=="string"?!0:e?.error==="instance_unavailable"}function sR(t){if(t)try{return JSON.parse(t)}catch{return t}}function iR(t,e){if(!t)return null;let r=t.trim();if(/^\d+$/.test(r))return Number(r)*1e3;let n=Date.parse(r);return Number.isNaN(n)?null:Math.max(0,n-e)}function aR(t){let e=/retry\s+after\s+(\d+)\s*s/i.exec(t);return e?Number(e[1])*1e3:null}async function cR(t,e){let r=iR(t.headers?.get?.("retry-after"),e),n="";try{n=await t.clone().text()}catch{return{maintenance:!1,delayMs:r}}let o=sR(n),s=ru(t.status,o),i=typeof o?.error=="string"?o.error:void 0;return{maintenance:s,delayMs:r??aR(n),error:i}}function lR(t){return!!(t==null||typeof t=="string"||typeof ArrayBuffer<"u"&&ArrayBuffer.isView(t)||t instanceof ArrayBuffer||typeof URLSearchParams<"u"&&t instanceof URLSearchParams||typeof Blob<"u"&&t instanceof Blob)}function ly(t){try{let e=typeof t=="string"?t:t instanceof URL?t.href:t?.url??"";return e?new URL(e).host:"the instance"}catch{return"the instance"}}function tu(t){return`${Math.round(t/1e3)}s`}function uR(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: ${t.host} is unavailable${e} \u2014 waiting ${tu(t.delayMs)} before retrying (${tu(t.remainingMs)} of the retry budget left).
45
+ `)}function dR(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: gave up after ${tu(t.waitedMs)} waiting for ${t.host} to come back${e}; ${t.attempts} ${t.attempts===1?"retry":"retries"} made.
46
+ `)}function Wi(t,e={}){let r=e.budgetMs??6e5,n=e.defaultDelayMs??6e4,o=e.sleep??(l=>new Promise(u=>setTimeout(u,l))),s=e.now??(()=>Date.now()),i=e.onWait??uR,a=e.onGiveUp??dR;return async(l,u)=>{let p=s(),w=0;for(;;){let f=await t(l,u);if(f.status!==503||u&&!lR(u.body))return f;let h=r-(s()-p),{maintenance:b,delayMs:$,error:E}=await cR(f,s());if(!b)return f;if(h<=0)return w>0&&a({waitedMs:s()-p,attempts:w,host:ly(l),error:E}),f;let P=$??n;P=Math.min(Math.max(P,1e3),12e4),P=Math.min(P,h),w+=1,i({attempt:w,delayMs:P,remainingMs:h,host:ly(l),error:E}),await o(P)}}}var nu=C(()=>{});function uy(t){if(typeof t=="string")return t.trim();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():""}function pR(t){let e=t.trimStart().slice(0,200).toLowerCase();return e.startsWith("<!doctype")||e.startsWith("<html")||e.startsWith("<")}function dy(t){let e=uy(t);return typeof t=="string"&&pR(e)?hR:e.slice(0,200)}function py(t,e){return ru(t,e)}function hy(t){return t instanceof le&&py(t.status,t.body)}function mR(){let t=(process.env.TURBOBASE_DEBUG??"").trim().toLowerCase();return t!==""&&t!=="0"&&t!=="false"}function fy(t){return t.replace(/\/+$/,"")}function ou(t=process.env){let e=(t[lo]??"").trim(),r=(t[Gi]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function su(t){let e;try{e=new URL(t)}catch{return`${lo} 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:`${lo} 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 le,hR,fR,ee,lo,Gi,is,Pr=C(()=>{nu();le=class extends Error{constructor(r,n,o){super(r);this.status=n;this.body=o;this.name="ApiError"}status;body};hR="the request did not reach the instance \u2014 a proxy or edge answered with an HTML page, so the server gave no detail";fR="this instance is temporarily unavailable \u2014 it is upgrading or restarting. Retry shortly.";ee=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=fy(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=e.retry===!1?r:Wi(r,e.retry??{})}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){if(mR()){let l=uy(a);throw new le(`${e} ${r} \u2192 ${s.status}${l?`: ${l}`:""}`,s.status,a)}if(py(s.status,a))throw new le(fR,s.status,a);let c=dy(a);throw new le(`${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"})}authorConduit(e){return this.request("POST","/v1/extensions/author-conduit",{intent:e.intent,from:e.from,to:e.to,...e.intentId?{intentId:e.intentId}:{},...e.columns?.length?{columns:e.columns}:{}})}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 platformEvents(e={}){let r=new URLSearchParams;e.subsystem&&r.set("subsystem",e.subsystem),e.severity&&r.set("severity",e.severity),e.code&&r.set("code",e.code),e.since&&r.set("since",e.since),e.after&&r.set("after",e.after),e.correlationId&&r.set("correlationId",e.correlationId),e.extension&&r.set("extension",e.extension),e.conduit&&r.set("conduit",e.conduit),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/events${n}`)).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,r={}){return this.request("POST","/v1/config/apply",{bundle:e,...r.prune?{prune:!0}:{}})}async tablesList(){return(await this.request("GET","/v1/tables")).tables??[]}tablesPlan(e){return this.request("POST","/v1/tables/plan",e)}appsPlan(e){return this.request("POST","/v1/apps/plan",{writes:e.writes??[],roles:e.roles??[],labels:e.labels??[]})}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`)}},lo="TURBOBASE_REGISTRY_URL",Gi="TURBOBASE_REGISTRY_TOKEN";is=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=fy(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=dy(a);throw new le(`${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}:{}})}}});import{existsSync as gR,statSync as yR}from"node:fs";import{resolve as Ji,sep as my}from"node:path";function gy(t){if(wR.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits|processes)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function _R(t,e,r){let n=Ji(e,r),o=Ji(t);if(n!==o&&!n.startsWith(o+my))return null;let s=[n];/\.(js|mjs|cjs)$/.test(n)&&s.push(n.replace(/\.js$/,".ts"),n.replace(/\.mjs$/,".mts"),n.replace(/\.cjs$/,".cts")),/\.[cm]?[jt]sx?$/.test(n)||s.push(`${n}.ts`,`${n}.tsx`,`${n}.js`,`${n}/index.ts`,`${n}/index.js`);for(let i of s)if(i.startsWith(o+my)&&gR(i)&&yR(i).isFile())return i;return null}function yy(t){return{name:"extension-self-contained-fence",setup(e){e.onResolve({filter:/.*/},r=>{if(r.kind==="entry-point")return null;if(gy(r.path))return{path:r.path,namespace:"extension-sdk"};let n=r.path.startsWith(".")||r.path.startsWith("/");if(n&&t){let s=_R(t,r.resolveDir,r.path);if(s)return{path:s}}return{errors:[{text:`extension ${n?`imports a sibling/local file ('${r.path}')${t?" that does not resolve inside the extension\u2019s own directory":""}`:r.path.startsWith("node:")||kR(r.path)?`imports a Node builtin ('${r.path}')`:`imports an external module ('${r.path}')`} \u2014 sandboxed extensions must be self-contained. The ONLY allowed imports are the SDK factory ('@/sync/hooks' or '@turbobase/extensions') and a relative sibling inside the extension's own directory; inline everything else into the extension file.`}]}}),e.onLoad({filter:/.*/,namespace:"extension-sdk"},()=>({contents:vR,loader:"js"}))}}}function kR(t){let e=t.startsWith("node:")?t.slice(5):t;return xR.has(e.split("/")[0])}function by(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 wy(){try{return(await import("esbuild")).build}catch(t){throw by("esbuild",t)}}async function $R(){try{return(await import("isolated-vm")).default}catch(t){throw by("isolated-vm",t)}}async function Qi(t,e={}){let r=await wy(),n=e.resolveDir?Ji(e.resolveDir):void 0,o;try{o=await r({stdin:{contents:t,loader:"ts",resolveDir:n??process.cwd(),sourcefile:"extension.ts"},bundle:!0,write:!1,format:"iife",globalName:"__tb_extension_module",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[yy(n)]})}catch(s){let a=s.errors?.map(c=>c.text).filter(Boolean).join("; ");throw new Yi(a||`extension bundle failed: ${String(s)}`)}return o.outputFiles?.[0]?.text??""}async function iu(t,e){if(!/(^|\n)\s*(import|export)\s[^;]*?from\s*['"](\.|\/)/.test(t)&&!/\bimport\s*\(\s*['"](\.|\/)/.test(t))return t;let r=await wy(),n=Ji(e),o=yy(n),s={name:"extension-sdk-external",setup(a){a.onResolve({filter:/.*/},c=>c.kind==="entry-point"?null:gy(c.path)?{path:c.path,external:!0}:null)}},i;try{i=await r({stdin:{contents:t,loader:"ts",resolveDir:n,sourcefile:"extension.ts"},bundle:!0,write:!1,format:"esm",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[s,o]})}catch(a){let l=a.errors?.map(u=>u.text).filter(Boolean).join("; ");throw new Yi(l||`extension bundle failed: ${String(a)}`)}return i.outputFiles?.[0]?.text??t}async function as(t,e,r={}){let n=r.timeoutMs??Xi,o=r.memoryLimitMb??bR,s=r.member??"run",i={patches:[],logs:[]},a=await $R(),c=new a.Isolate({memoryLimit:o});try{let l=await c.createContext(),u=l.global,p=new a.Callback(B=>{let W=JSON.parse(String(B));i.rejection||(i.rejection=W)}),w=new a.Callback(B=>{i.patches.push(JSON.parse(String(B)))}),f=new a.Callback(B=>{let W=JSON.parse(String(B));i.logs.push(W)}),h=new a.Callback(B=>{i.result=JSON.parse(String(B))}),b=r.query,$=new a.Reference(async B=>{if(!b)throw new Error("ctx.query is not available in this context");return JSON.stringify(await b(String(B)))});await u.set("__tb_reject",p),await u.set("__tb_patch",w),await u.set("__tb_log",f),await u.set("__tb_result",h),await u.set("__tb_query",$),await u.set("__tb_ctx_json",JSON.stringify(SR(e)));let E=ER(t,s,r.stepIndex??0,!!r.query),z=await(await c.compileScript(E)).run(l,{timeout:n,promise:!0});return s==="when"?{effects:i,whenResult:!!z}:{effects:i}}finally{c.isDisposed||c.dispose()}}function SR(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,materialized:t.materialized??null,process:t.process??null}}function TR(t){return`
47
47
  "use strict";
48
48
  (async () => {
49
49
  const __tb_ctx = JSON.parse(__tb_ctx_json);
@@ -66,7 +66,7 @@ ${o.join(`
66
66
  __tb_result(JSON.stringify(out == null ? null : String(out)));
67
67
  return undefined;
68
68
  })()
69
- `}function _R(t,e,r){return e==="build"?xR(t,r):e==="outstanding"?vR(t):`
69
+ `}function ER(t,e,r,n=!1){return e==="build"?RR(t,r):e==="outstanding"?TR(t):`
70
70
  "use strict";
71
71
  (async () => {
72
72
  const __tb_ctx = JSON.parse(__tb_ctx_json);
@@ -108,6 +108,13 @@ ${o.join(`
108
108
  canonicalStatus(args) {
109
109
  return String((args && args.raw) || '').trim().toLowerCase();
110
110
  },
111
+ ${n?`async query(q) {
112
+ const json = await __tb_query.apply(undefined, [String(q)], {
113
+ arguments: { copy: true },
114
+ result: { promise: true, copy: true },
115
+ });
116
+ return JSON.parse(json);
117
+ },`:""}
111
118
  reject(envelope) { __tb_reject(JSON.stringify(envelope)); },
112
119
  patch(updates) { __tb_patch(JSON.stringify(updates)); },
113
120
  log(level, message, meta) {
@@ -140,7 +147,7 @@ ${o.join(`
140
147
  ${e==="transform"?"__tb_result(JSON.stringify(out == null ? null : out));":""}
141
148
  return ${e==="when"?"out":"undefined"};
142
149
  })()
143
- `}function xR(t,e){return`
150
+ `}function RR(t,e){return`
144
151
  "use strict";
145
152
  (async () => {
146
153
  const __tb_ctx = JSON.parse(__tb_ctx_json);
@@ -182,12 +189,12 @@ ${o.join(`
182
189
  __tb_result(JSON.stringify(out == null ? null : out));
183
190
  return undefined;
184
191
  })()
185
- `}var Ji,pR,hR,fR,Gi,gR,Xi=C(()=>{Ji=200,pR=16,hR=new Set(["@/sync/hooks","@/sync/hooks/index.js","@/sync/conduits","@/sync/conduits/index.js","@/sync/processes","@/sync/processes/index.js","@turbobase/extensions","@turbobase/extensions/hook","@turbobase/extensions/conduit","@turbobase/extensions/process"]);fR=`
192
+ `}var Xi,bR,wR,vR,Yi,xR,ea=C(()=>{Xi=200,bR=16,wR=new Set(["@/sync/hooks","@/sync/hooks/index.js","@/sync/conduits","@/sync/conduits/index.js","@/sync/processes","@/sync/processes/index.js","@turbobase/extensions","@turbobase/extensions/hook","@turbobase/extensions/conduit","@turbobase/extensions/process"]);vR=`
186
193
  export const defineHook = (def) => def;
187
194
  export const defineConduit = (def) => def;
188
195
  export const defineProcess = (def) => def;
189
196
  export default defineHook;
190
- `;Gi=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};gR=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 su}from"node:fs";import{join as kR}from"node:path";function $R(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 SR(t,e,r){let n=e.name??r,o=e.expect??"pass";try{let{effects:s}=await as(t,$R(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 Qi(t,e,r={}){let n=await Yi(t,{resolveDir:r.resolveDir}),o=[];for(let s=0;s<e.length;s+=1)o.push(await SR(n,e[s],`sample[${s}]`));return o}async function cs(t){let e;try{e=await su.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 su.readFile(kR(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 ls(t){return su.readFile(t,"utf8")}var iu=C(()=>{Xi()});function St(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function n0(t){let e=t.recordType;if(!e)throw new Tt("record type is required (e.g. --record=salesOrder)");let r=t.event??"before_save",n=t.template??"require-field",o=t.source,s=o?`
197
+ `;Yi=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};xR=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 au}from"node:fs";import{join as PR}from"node:path";function AR(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 IR(t,e,r){let n=e.name??r,o=e.expect??"pass";try{let{effects:s}=await as(t,AR(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 ta(t,e,r={}){let n=await Qi(t,{resolveDir:r.resolveDir}),o=[];for(let s=0;s<e.length;s+=1)o.push(await IR(n,e[s],`sample[${s}]`));return o}async function cs(t){let e;try{e=await au.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 au.readFile(PR(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 ls(t){return au.readFile(t,"utf8")}var cu=C(()=>{ea()});function St(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function l0(t){let e=t.recordType;if(!e)throw new Tt("record type is required (e.g. --record=salesOrder)");let r=t.event??"before_save",n=t.template??"require-field",o=t.source,s=o?`
191
198
  source: ${JSON.stringify(o)},`:"",i,a;if(n==="blank")i=`
192
199
  run: (ctx) => {
193
200
  // Validate or mutate ctx.payload here. Reject with ctx.reject({...}); mutate
@@ -225,7 +232,7 @@ export default defineHook<Record<string, unknown>>({
225
232
  recordType: ${JSON.stringify(e)},
226
233
  event: ${JSON.stringify(r)},${s}${i}
227
234
  });
228
- `;return{relativePath:`hooks/${e}/${r}.${a}.ts`,content:u}}function o0(t){let e=t.recordType;if(!e)throw new Tt("record type is required (e.g. --record=order)");let r=t.source;if(!r)throw new Tt("--source is required (the origin source, e.g. --source=shopify)");let n=t.to;if(!n)throw new Tt("--to is required (the target source, e.g. --to=netsuite)");if(r===n)throw new Tt(`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??`${St(r)}2${St(n)}:${St(e)}`,c=`/**
235
+ `;return{relativePath:`hooks/${e}/${r}.${a}.ts`,content:u}}function u0(t){let e=t.recordType;if(!e)throw new Tt("record type is required (e.g. --record=order)");let r=t.source;if(!r)throw new Tt("--source is required (the origin source, e.g. --source=shopify)");let n=t.to;if(!n)throw new Tt("--to is required (the target source, e.g. --to=netsuite)");if(r===n)throw new Tt(`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??`${St(r)}2${St(n)}:${St(e)}`,c=`/**
229
236
  * ${t.description??`Bridge ${r} ${e} \u2192 ${n} ${o} (${s}).`}
230
237
  *
231
238
  * Scaffolded by \`turbobase ext new conduit\`. A conduit is a PURE canonical\u2192canonical
@@ -268,7 +275,7 @@ export default defineConduit<Record<string, unknown>>({
268
275
  },
269
276
  idempotencyKey: (ctx) => ${JSON.stringify(`${i}:`)} + ctx.externalId,
270
277
  });
271
- `;return{relativePath:`conduits/${St(r)}-${St(e)}-to-${St(n)}-${St(o)}.ts`,content:c}}function s0(t){let e=t.recordType;if(!e)throw new Tt("record type is required (e.g. --record=purchaseOrder)");let r=t.then,n=t.onFailure??"stop";if(n!=="stop"&&n!=="rollback")throw new Tt(`--on-failure must be stop | rollback (got ${n})`);let o=r?`${St(e)}-then-${St(r)}`:St(e),s=t.id??`custom:process:${o}`,i=t.description??(r?`Raise a ${e}, wait for the source, then raise a ${r}.`:`Raise a ${e}.`),a=r?`
278
+ `;return{relativePath:`conduits/${St(r)}-${St(e)}-to-${St(n)}-${St(o)}.ts`,content:c}}function d0(t){let e=t.recordType;if(!e)throw new Tt("record type is required (e.g. --record=purchaseOrder)");let r=t.then,n=t.onFailure??"stop";if(n!=="stop"&&n!=="rollback")throw new Tt(`--on-failure must be stop | rollback (got ${n})`);let o=r?`${St(e)}-then-${St(r)}`:St(e),s=t.id??`custom:process:${o}`,i=t.description??(r?`Raise a ${e}, wait for the source, then raise a ${r}.`:`Raise a ${e}.`),a=r?`
272
279
  {
273
280
  id: ${JSON.stringify(St(r))},
274
281
  recordType: ${JSON.stringify(r)},
@@ -317,7 +324,7 @@ export default defineProcess({
317
324
  ],
318
325
  onFailure: ${JSON.stringify(n)},
319
326
  });
320
- `;return{relativePath:`processes/${o}.ts`,content:c}}function fr(t,e){let r=i0[t];if(!r)throw new Tt(`unknown extension kind '${t}'. Scaffoldable kinds: ${qy.join(", ")}.`);return r(e)}var qy,Tt,i0,oa=C(()=>{qy=["hook","conduit","process"];Tt=class extends Error{};i0={hook:n0,conduit:o0,process:s0}});var $u,Su=C(()=>{$u=Object.freeze({instance:!0,platform:!0,share:"inherit"})});function sA(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 iA(t){return rw[sA(t)%rw.length]}function aA(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 nw(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function ow(t,e){let[r,n]=iA(t),o=nw(aA(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${nw(e)}">
327
+ `;return{relativePath:`processes/${o}.ts`,content:c}}function fr(t,e){let r=p0[t];if(!r)throw new Tt(`unknown extension kind '${t}'. Scaffoldable kinds: ${Fy.join(", ")}.`);return r(e)}var Fy,Tt,p0,ia=C(()=>{Fy=["hook","conduit","process"];Tt=class extends Error{};p0={hook:l0,conduit:u0,process:d0}});var Tu,Eu=C(()=>{Tu=Object.freeze({instance:!0,platform:!0,share:"inherit"})});function dA(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 pA(t){return sw[dA(t)%sw.length]}function hA(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 iw(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function aw(t,e){let[r,n]=pA(t),o=iw(hA(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${iw(e)}">
321
328
  <defs>
322
329
  <linearGradient id="tile" x1="0" y1="0" x2="1" y2="1">
323
330
  <stop offset="0" stop-color="${r}"/>
@@ -327,9 +334,9 @@ export default defineProcess({
327
334
  <rect width="64" height="64" rx="14" fill="url(#tile)"/>
328
335
  <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>
329
336
  </svg>
330
- `}var rw,sw=C(()=>{rw=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var _w={};Yo(_w,{CN_UTIL:()=>dw,COMPONENTS_JSON:()=>uw,MAIN_TSX:()=>hw,STYLES_CSS:()=>fw,TSCONFIG:()=>lw,TURBOBASE_CLIENT:()=>iw,UI_BADGE:()=>yw,UI_BUTTON:()=>mw,UI_CARD:()=>gw,UI_INPUT:()=>ww,UI_LABEL:()=>vw,UI_TABLE:()=>bw,indexHtml:()=>pw,instanceOriginFromEnv:()=>gA,packageJson:()=>aw,scaffoldAppFiles:()=>bA,starterApp:()=>wA,viteConfig:()=>cw});function uA(t,e){let r=t.trim();if(r.length<=e)return r;let n=r.slice(0,e);return n.replace(/[\s\p{P}\p{S}]+$/u,"")||n}function dA(t){let e={name:uA(t.title,lA)},r=(t.description??"").trim().slice(0,cA);return r&&(e.description=r),e.icon="favicon.svg",e.learnings={...$u},JSON.stringify(e,null,2)+`
331
- `}function aw(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview",pretest:pA},dependencies:{react:"^19.2.0","react-dom":"^19.2.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1","tailwind-merge":"^3.0.0","lucide-react":"^0.469.0","@fontsource/inter":"^5.1.0"},devDependencies:{"@types/react":"^19.2.0","@types/react-dom":"^19.2.0","@vitejs/plugin-react":"^4.3.1",tailwindcss:"^4.0.0","@tailwindcss/vite":"^4.0.0","tw-animate-css":"^1.2.5",typescript:"^5.5.3",vite:"^5.4.0"}},null,2)}
332
- `}function mA(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 gA(t=process.env){let e=(t.TENANT_SLUG??"").trim(),r=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!r))return`https://${e}.${r}`}function cw(t,e={}){let r=mA(e.instanceOrigin);return`import { defineConfig } from 'vite';
337
+ `}var sw,cw=C(()=>{sw=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var $w={};Yo($w,{CN_UTIL:()=>fw,COMPONENTS_JSON:()=>hw,MAIN_TSX:()=>gw,STYLES_CSS:()=>yw,TSCONFIG:()=>pw,TURBOBASE_CLIENT:()=>lw,UI_BADGE:()=>vw,UI_BUTTON:()=>bw,UI_CARD:()=>ww,UI_INPUT:()=>xw,UI_LABEL:()=>kw,UI_TABLE:()=>_w,indexHtml:()=>mw,instanceOriginFromEnv:()=>xA,packageJson:()=>uw,scaffoldAppFiles:()=>$A,starterApp:()=>SA,viteConfig:()=>dw});function gA(t,e){let r=t.trim();if(r.length<=e)return r;let n=r.slice(0,e);return n.replace(/[\s\p{P}\p{S}]+$/u,"")||n}function yA(t){let e={name:gA(t.title,mA)},r=(t.description??"").trim().slice(0,fA);return r&&(e.description=r),e.icon="favicon.svg",e.learnings={...Tu},JSON.stringify(e,null,2)+`
338
+ `}function uw(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview",pretest:bA},dependencies:{react:"^19.2.0","react-dom":"^19.2.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1","tailwind-merge":"^3.0.0","lucide-react":"^0.469.0","@fontsource/inter":"^5.1.0"},devDependencies:{"@types/react":"^19.2.0","@types/react-dom":"^19.2.0","@vitejs/plugin-react":"^4.3.1",tailwindcss:"^4.0.0","@tailwindcss/vite":"^4.0.0","tw-animate-css":"^1.2.5",typescript:"^5.5.3",vite:"^5.4.0"}},null,2)}
339
+ `}function _A(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 xA(t=process.env){let e=(t.TENANT_SLUG??"").trim(),r=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!r))return`https://${e}.${r}`}function dw(t,e={}){let r=_A(e.instanceOrigin);return`import { defineConfig } from 'vite';
333
340
  import { fileURLToPath, URL } from 'node:url';
334
341
  import react from '@vitejs/plugin-react';
335
342
  // Tailwind v4 is a Vite PLUGIN, not a PostCSS pass \u2014 there is no
@@ -348,8 +355,8 @@ import tailwindcss from '@tailwindcss/vite';
348
355
  // you sign in, and the cookies land on localhost:3000. Override the targets
349
356
  // with SUPABASE_URL / TURBOBASE_API_URL without editing this file (Vite reads
350
357
  // them at boot; restart the dev server after changing one).
351
- const TENANT = process.env.SUPABASE_URL || '${r??hA}'; // /rest + the Realtime WS
352
- const API = process.env.TURBOBASE_API_URL || '${r??fA}'; // /v1, /auth, /login, /_app
358
+ const TENANT = process.env.SUPABASE_URL || '${r??wA}'; // /rest + the Realtime WS
359
+ const API = process.env.TURBOBASE_API_URL || '${r??vA}'; // /v1, /auth, /login, /_app
353
360
 
354
361
  // Where this bundle's assets are requested from. \`turbobase apps deploy\` sets
355
362
  // this to /_tb/app-assets/<build-id>/ so the asset URLs name the BUILD, not the
@@ -387,7 +394,7 @@ export default defineConfig({
387
394
  },
388
395
  build: { outDir: 'dist' },
389
396
  });
390
- `}function pw(t){return`<!doctype html>
397
+ `}function mw(t){return`<!doctype html>
391
398
  <html lang="en">
392
399
  <head>
393
400
  <meta charset="UTF-8" />
@@ -400,7 +407,7 @@ export default defineConfig({
400
407
  <script type="module" src="/src/main.tsx"></script>
401
408
  </body>
402
409
  </html>
403
- `}function bA(t){return{"package.json":aw(t.slug),"vite.config.ts":cw(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":yA,"tsconfig.json":lw,"index.html":pw(t.title),"public/turbobase.json":dA(t),"public/favicon.svg":ow(t.slug,t.title),"src/main.tsx":hw,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":iw,"src/styles.css":fw,"components.json":uw,"src/lib/utils.ts":dw,"src/components/ui/button.tsx":mw,"src/components/ui/card.tsx":gw,"src/components/ui/badge.tsx":yw,"src/components/ui/table.tsx":bw,"src/components/ui/input.tsx":ww,"src/components/ui/label.tsx":vw,"README.md":`# ${t.title}
410
+ `}function $A(t){return{"package.json":uw(t.slug),"vite.config.ts":dw(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":kA,"tsconfig.json":pw,"index.html":mw(t.title),"public/turbobase.json":yA(t),"public/favicon.svg":aw(t.slug,t.title),"src/main.tsx":gw,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":lw,"src/styles.css":yw,"components.json":hw,"src/lib/utils.ts":fw,"src/components/ui/button.tsx":bw,"src/components/ui/card.tsx":ww,"src/components/ui/badge.tsx":vw,"src/components/ui/table.tsx":_w,"src/components/ui/input.tsx":xw,"src/components/ui/label.tsx":kw,"README.md":`# ${t.title}
404
411
 
405
412
  \`\`\`sh
406
413
  npm install
@@ -421,7 +428,7 @@ every read comes back "permission denied", which looks like an RLS problem.
421
428
 
422
429
  \`CLAUDE.md\` + \`.mcp.json\` wire Claude Code to this instance. \`.mcp.json\` holds a
423
430
  live access token and is gitignored \u2014 keep it that way.
424
- `}}function wA(t){return`import React from 'react';
431
+ `}}function SA(t){return`import React from 'react';
425
432
  import { Loader2, Trash2 } from 'lucide-react';
426
433
 
427
434
  import { select, write, del } from '@/lib/turbobase';
@@ -646,7 +653,7 @@ export default function App() {
646
653
  </main>
647
654
  );
648
655
  }
649
- `}var cA,lA,iw,ws,pA,hA,fA,yA,lw,uw,dw,hw,fw,mw,gw,yw,bw,ww,vw,xw=C(()=>{sw();Su();cA=200,lA=60;iw=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
656
+ `}var fA,mA,lw,ws,bA,wA,vA,kA,pw,hw,fw,gw,yw,bw,ww,vw,_w,xw,kw,Sw=C(()=>{cw();Eu();fA=200,mA=60;lw=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
650
657
  // Reads go through PostgREST (RLS-scoped); writes go through POST /v1/data/<recordType>.
651
658
  // A cold first paint that fans out many reads should use batch() \u2014 ONE request
652
659
  // that multiplexes them, sidestepping the per-request rate limiter.
@@ -1663,7 +1670,7 @@ export async function selectPage<T = unknown>(
1663
1670
  }
1664
1671
  return { rows, nextCursor };
1665
1672
  }
1666
- `,ws="src/types.ts",pA=`turbobase project types -o ${ws} || node -e "if(require('node:fs').existsSync('${ws}')){console.error('turbobase: could not refresh ${ws} (offline or signed out) - testing against the copy on disk, which may be stale.')}else{console.error('turbobase: ${ws} 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 ${ws}');process.exit(1)}"`;hA="http://localhost:54331",fA="http://localhost:4100";yA=`node_modules/
1673
+ `,ws="src/types.ts",bA=`turbobase project types -o ${ws} || node -e "if(require('node:fs').existsSync('${ws}')){console.error('turbobase: could not refresh ${ws} (offline or signed out) - testing against the copy on disk, which may be stale.')}else{console.error('turbobase: ${ws} 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 ${ws}');process.exit(1)}"`;wA="http://localhost:54331",vA="http://localhost:4100";kA=`node_modules/
1667
1674
  dist/
1668
1675
  build/
1669
1676
 
@@ -1675,9 +1682,9 @@ build/
1675
1682
  !.env.example
1676
1683
 
1677
1684
  .DS_Store
1678
- `,lw=`${JSON.stringify({compilerOptions:{target:"ES2022",lib:["ES2022","DOM","DOM.Iterable"],module:"ESNext",moduleResolution:"bundler",jsx:"react-jsx",strict:!0,skipLibCheck:!0,noEmit:!0,baseUrl:".",paths:{"@/*":["./src/*"]}},include:["src"]},null,2)}
1679
- `,uw=`${JSON.stringify({$schema:"https://ui.shadcn.com/schema.json",style:"new-york",rsc:!1,tsx:!0,tailwind:{config:"",css:"src/styles.css",baseColor:"neutral",cssVariables:!0,prefix:""},aliases:{components:"@/components",utils:"@/lib/utils",ui:"@/components/ui",lib:"@/lib",hooks:"@/hooks"},iconLibrary:"lucide"},null,2)}
1680
- `,dw=`import { clsx, type ClassValue } from 'clsx';
1685
+ `,pw=`${JSON.stringify({compilerOptions:{target:"ES2022",lib:["ES2022","DOM","DOM.Iterable"],module:"ESNext",moduleResolution:"bundler",jsx:"react-jsx",strict:!0,skipLibCheck:!0,noEmit:!0,baseUrl:".",paths:{"@/*":["./src/*"]}},include:["src"]},null,2)}
1686
+ `,hw=`${JSON.stringify({$schema:"https://ui.shadcn.com/schema.json",style:"new-york",rsc:!1,tsx:!0,tailwind:{config:"",css:"src/styles.css",baseColor:"neutral",cssVariables:!0,prefix:""},aliases:{components:"@/components",utils:"@/lib/utils",ui:"@/components/ui",lib:"@/lib",hooks:"@/hooks"},iconLibrary:"lucide"},null,2)}
1687
+ `,fw=`import { clsx, type ClassValue } from 'clsx';
1681
1688
  import { twMerge } from 'tailwind-merge';
1682
1689
 
1683
1690
  /**
@@ -1691,7 +1698,7 @@ import { twMerge } from 'tailwind-merge';
1691
1698
  export function cn(...inputs: ClassValue[]) {
1692
1699
  return twMerge(clsx(inputs));
1693
1700
  }
1694
- `;hw=`import React from 'react';
1701
+ `;gw=`import React from 'react';
1695
1702
  import { createRoot } from 'react-dom/client';
1696
1703
  import App from './App';
1697
1704
  import './styles.css';
@@ -1701,7 +1708,7 @@ createRoot(document.getElementById('root')!).render(
1701
1708
  <App />
1702
1709
  </React.StrictMode>,
1703
1710
  );
1704
- `,fw=`@import 'tailwindcss';
1711
+ `,yw=`@import 'tailwindcss';
1705
1712
  @import 'tw-animate-css';
1706
1713
 
1707
1714
  /* Inter, self-hosted \u2014 the design system's font.
@@ -1789,7 +1796,7 @@ createRoot(document.getElementById('root')!).render(
1789
1796
  transition-duration: 0.01ms !important;
1790
1797
  }
1791
1798
  }
1792
- `,mw=`import * as React from 'react';
1799
+ `,bw=`import * as React from 'react';
1793
1800
  import { cva, type VariantProps } from 'class-variance-authority';
1794
1801
 
1795
1802
  import { cn } from '@/lib/utils';
@@ -1829,7 +1836,7 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
1829
1836
  Button.displayName = 'Button';
1830
1837
 
1831
1838
  export { Button, buttonVariants };
1832
- `,gw=`import * as React from 'react';
1839
+ `,ww=`import * as React from 'react';
1833
1840
 
1834
1841
  import { cn } from '@/lib/utils';
1835
1842
 
@@ -1867,7 +1874,7 @@ const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDi
1867
1874
  CardContent.displayName = 'CardContent';
1868
1875
 
1869
1876
  export { Card, CardHeader, CardTitle, CardDescription, CardContent };
1870
- `,yw=`import * as React from 'react';
1877
+ `,vw=`import * as React from 'react';
1871
1878
  import { cva, type VariantProps } from 'class-variance-authority';
1872
1879
 
1873
1880
  import { cn } from '@/lib/utils';
@@ -1902,7 +1909,7 @@ function Badge({ className, variant, ...props }: BadgeProps) {
1902
1909
  }
1903
1910
 
1904
1911
  export { Badge, badgeVariants };
1905
- `,bw=`import * as React from 'react';
1912
+ `,_w=`import * as React from 'react';
1906
1913
 
1907
1914
  import { cn } from '@/lib/utils';
1908
1915
 
@@ -1961,7 +1968,7 @@ const TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<
1961
1968
  TableCell.displayName = 'TableCell';
1962
1969
 
1963
1970
  export { Table, TableHeader, TableBody, TableRow, TableHead, TableCell };
1964
- `,ww=`import * as React from 'react';
1971
+ `,xw=`import * as React from 'react';
1965
1972
 
1966
1973
  import { cn } from '@/lib/utils';
1967
1974
 
@@ -1981,7 +1988,7 @@ const Input = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLI
1981
1988
  Input.displayName = 'Input';
1982
1989
 
1983
1990
  export { Input };
1984
- `,vw=`import * as React from 'react';
1991
+ `,kw=`import * as React from 'react';
1985
1992
 
1986
1993
  import { cn } from '@/lib/utils';
1987
1994
 
@@ -1998,9 +2005,9 @@ const Label = React.forwardRef<HTMLLabelElement, React.LabelHTMLAttributes<HTMLL
1998
2005
  Label.displayName = 'Label';
1999
2006
 
2000
2007
  export { Label };
2001
- `});var vs=C(()=>{Di()});function O(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 Ct(t){return t&&Object.assign(ya,t),ya}var _A,Or,ya,vo=C(()=>{_A=Object.freeze({status:"aborted"});Or=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},ya={}});var we={};Yo(we,{BIGINT_FORMAT_RANGES:()=>$w,Class:()=>Du,NUMBER_FORMAT_RANGES:()=>Hu,aborted:()=>zn,allowsEval:()=>Bu,assert:()=>TA,assertEqual:()=>xA,assertIs:()=>$A,assertNever:()=>SA,assertNotEqual:()=>kA,assignProp:()=>qu,cached:()=>ks,captureStackTrace:()=>wa,cleanEnum:()=>MA,cleanRegex:()=>Ss,clone:()=>Nt,createTransparentProxy:()=>OA,defineLazy:()=>Ce,esc:()=>Nn,escapeRegex:()=>Gr,extend:()=>zA,finalizeIssue:()=>tr,floatSafeRemainder:()=>Uu,getElementAtPath:()=>EA,getEnumValues:()=>xs,getLengthableOrigin:()=>Ts,getParsedType:()=>IA,getSizableOrigin:()=>Sw,isObject:()=>_o,isPlainObject:()=>xo,issue:()=>Vu,joinValues:()=>ba,jsonStringifyReplacer:()=>Mu,merge:()=>jA,normalizeParams:()=>oe,nullish:()=>$s,numKeys:()=>AA,omit:()=>NA,optionalKeys:()=>Fu,partial:()=>LA,pick:()=>CA,prefixIssues:()=>mr,primitiveTypes:()=>kw,promiseAllObject:()=>RA,propertyKeyTypes:()=>Zu,randomString:()=>PA,required:()=>DA,stringifyPrimitive:()=>va,unwrapMessage:()=>_s});function xA(t){return t}function kA(t){return t}function $A(t){}function SA(t){throw new Error}function TA(t){}function xs(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 ba(t,e="|"){return t.map(r=>va(r)).join(e)}function Mu(t,e){return typeof e=="bigint"?e.toString():e}function ks(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function $s(t){return t==null}function Ss(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Uu(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 qu(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function EA(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function RA(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 PA(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Nn(t){return JSON.stringify(t)}function _o(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function xo(t){if(_o(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(_o(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function AA(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function Gr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Nt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function oe(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 OA(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 va(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Fu(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function CA(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 Nt(t,{...t._zod.def,shape:r,checks:[]})}function NA(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 Nt(t,{...t._zod.def,shape:r,checks:[]})}function zA(t,e){if(!xo(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 qu(this,"shape",n),n},checks:[]};return Nt(t,r)}function jA(t,e){return Nt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return qu(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function LA(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 Nt(e,{...e._zod.def,shape:o,checks:[]})}function DA(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 Nt(e,{...e._zod.def,shape:o,checks:[]})}function zn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function mr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function _s(t){return typeof t=="string"?t:t?.message}function tr(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=_s(t.inst?._zod.def?.error?.(t))??_s(e?.error?.(t))??_s(r.customError?.(t))??_s(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Sw(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Ts(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Vu(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function MA(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var wa,Bu,IA,Zu,kw,Hu,$w,Du,gr=C(()=>{wa=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};Bu=ks(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});IA=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}`)}},Zu=new Set(["string","number","symbol"]),kw=new Set(["string","number","bigint","boolean","symbol","undefined"]);Hu={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]},$w={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Du=class{constructor(...e){}}});function Ku(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 Wu(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 Tw,_a,Es,Gu=C(()=>{vo();gr();Tw=(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,Mu,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},_a=O("$ZodError",Tw),Es=O("$ZodError",Tw,{Parent:Error})});var Ju,Yu,Xu,Qu,ed,jn,td,Ln,rd=C(()=>{vo();Gu();gr();Ju=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 Or;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>tr(c,s,Ct())));throw wa(a,o?.callee),a}return i.value},Yu=Ju(Es),Xu=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=>tr(c,s,Ct())));throw wa(a,o?.callee),a}return i.value},Qu=Xu(Es),ed=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 Or;return s.issues.length?{success:!1,error:new(t??_a)(s.issues.map(i=>tr(i,o,Ct())))}:{success:!0,data:s.value}},jn=ed(Es),td=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=>tr(i,o,Ct())))}:{success:!0,data:s.value}},Ln=td(Es)});function jw(){return new RegExp(qA,"u")}function Vw(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 Kw(t){return new RegExp(`^${Vw(t)}$`)}function Ww(t){let e=Vw({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(`^${Fw}T(?:${n})$`)}var Ew,Rw,Pw,Aw,Iw,Ow,Cw,Nw,nd,zw,qA,Lw,Dw,Mw,Uw,qw,od,Bw,Zw,Fw,Hw,Gw,Jw,Yw,Xw,Qw,ev,tv,ka=C(()=>{Ew=/^[cC][^\s-]{8,}$/,Rw=/^[0-9a-z]+$/,Pw=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Aw=/^[0-9a-vA-V]{20}$/,Iw=/^[A-Za-z0-9]{27}$/,Ow=/^[a-zA-Z0-9_-]{21}$/,Cw=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Nw=/^([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})$/,nd=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)$/,zw=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,qA="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";Lw=/^(?:(?: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])$/,Dw=/^(([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})$/,Mw=/^((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])$/,Uw=/^(([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])$/,qw=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,od=/^[A-Za-z0-9_-]*$/,Bw=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Zw=/^\+(?:[0-9]){6,14}[0-9]$/,Fw="(?:(?:\\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])))",Hw=new RegExp(`^${Fw}$`);Gw=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Jw=/^\d+$/,Yw=/^-?\d+(?:\.\d+)?/i,Xw=/true|false/i,Qw=/null/i,ev=/^[^A-Z]*$/,tv=/^[^a-z]*$/});var ot,rv,sd,id,nv,ov,sv,iv,av,Rs,cv,lv,uv,dv,pv,hv,fv,$a=C(()=>{vo();ka();gr();ot=O("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),rv={number:"number",bigint:"bigint",object:"date"},sd=O("$ZodCheckLessThan",(t,e)=>{ot.init(t,e);let r=rv[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})}}),id=O("$ZodCheckGreaterThan",(t,e)=>{ot.init(t,e);let r=rv[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})}}),nv=O("$ZodCheckMultipleOf",(t,e)=>{ot.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):Uu(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})}}),ov=O("$ZodCheckNumberFormat",(t,e)=>{ot.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Hu[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=Jw)}),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})}}),sv=O("$ZodCheckMaxLength",(t,e)=>{var r;ot.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!$s(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=Ts(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),iv=O("$ZodCheckMinLength",(t,e)=>{var r;ot.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!$s(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=Ts(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),av=O("$ZodCheckLengthEquals",(t,e)=>{var r;ot.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!$s(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=Ts(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})}}),Rs=O("$ZodCheckStringFormat",(t,e)=>{var r,n;ot.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=()=>{})}),cv=O("$ZodCheckRegex",(t,e)=>{Rs.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})}}),lv=O("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=ev),Rs.init(t,e)}),uv=O("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=tv),Rs.init(t,e)}),dv=O("$ZodCheckIncludes",(t,e)=>{ot.init(t,e);let r=Gr(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})}}),pv=O("$ZodCheckStartsWith",(t,e)=>{ot.init(t,e);let r=new RegExp(`^${Gr(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})}}),hv=O("$ZodCheckEndsWith",(t,e)=>{ot.init(t,e);let r=new RegExp(`.*${Gr(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})}}),fv=O("$ZodCheckOverwrite",(t,e)=>{ot.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Sa,ad=C(()=>{Sa=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(`
2008
+ `});var vs=C(()=>{Di()});function O(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 Ct(t){return t&&Object.assign(wa,t),wa}var EA,Or,wa,vo=C(()=>{EA=Object.freeze({status:"aborted"});Or=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},wa={}});var we={};Yo(we,{BIGINT_FORMAT_RANGES:()=>Ew,Class:()=>Uu,NUMBER_FORMAT_RANGES:()=>Ku,aborted:()=>zn,allowsEval:()=>Fu,assert:()=>OA,assertEqual:()=>RA,assertIs:()=>AA,assertNever:()=>IA,assertNotEqual:()=>PA,assignProp:()=>Zu,cached:()=>ks,captureStackTrace:()=>_a,cleanEnum:()=>HA,cleanRegex:()=>Ss,clone:()=>Nt,createTransparentProxy:()=>DA,defineLazy:()=>Ce,esc:()=>Nn,escapeRegex:()=>Gr,extend:()=>qA,finalizeIssue:()=>tr,floatSafeRemainder:()=>Bu,getElementAtPath:()=>CA,getEnumValues:()=>xs,getLengthableOrigin:()=>Ts,getParsedType:()=>LA,getSizableOrigin:()=>Rw,isObject:()=>_o,isPlainObject:()=>xo,issue:()=>Wu,joinValues:()=>va,jsonStringifyReplacer:()=>qu,merge:()=>BA,normalizeParams:()=>oe,nullish:()=>$s,numKeys:()=>jA,omit:()=>UA,optionalKeys:()=>Vu,partial:()=>ZA,pick:()=>MA,prefixIssues:()=>mr,primitiveTypes:()=>Tw,promiseAllObject:()=>NA,propertyKeyTypes:()=>Hu,randomString:()=>zA,required:()=>FA,stringifyPrimitive:()=>xa,unwrapMessage:()=>_s});function RA(t){return t}function PA(t){return t}function AA(t){}function IA(t){throw new Error}function OA(t){}function xs(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 va(t,e="|"){return t.map(r=>xa(r)).join(e)}function qu(t,e){return typeof e=="bigint"?e.toString():e}function ks(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function $s(t){return t==null}function Ss(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Bu(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 Zu(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function CA(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function NA(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 zA(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Nn(t){return JSON.stringify(t)}function _o(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function xo(t){if(_o(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(_o(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function jA(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function Gr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Nt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function oe(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 DA(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 xa(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Vu(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function MA(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 Nt(t,{...t._zod.def,shape:r,checks:[]})}function UA(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 Nt(t,{...t._zod.def,shape:r,checks:[]})}function qA(t,e){if(!xo(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 Zu(this,"shape",n),n},checks:[]};return Nt(t,r)}function BA(t,e){return Nt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Zu(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function ZA(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 Nt(e,{...e._zod.def,shape:o,checks:[]})}function FA(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 Nt(e,{...e._zod.def,shape:o,checks:[]})}function zn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function mr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function _s(t){return typeof t=="string"?t:t?.message}function tr(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=_s(t.inst?._zod.def?.error?.(t))??_s(e?.error?.(t))??_s(r.customError?.(t))??_s(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Rw(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Ts(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Wu(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function HA(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var _a,Fu,LA,Hu,Tw,Ku,Ew,Uu,gr=C(()=>{_a=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};Fu=ks(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});LA=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}`)}},Hu=new Set(["string","number","symbol"]),Tw=new Set(["string","number","bigint","boolean","symbol","undefined"]);Ku={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]},Ew={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Uu=class{constructor(...e){}}});function Gu(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 Ju(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 Pw,ka,Es,Yu=C(()=>{vo();gr();Pw=(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,qu,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},ka=O("$ZodError",Pw),Es=O("$ZodError",Pw,{Parent:Error})});var Xu,Qu,ed,td,rd,jn,nd,Ln,od=C(()=>{vo();Yu();gr();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 Or;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>tr(c,s,Ct())));throw _a(a,o?.callee),a}return i.value},Qu=Xu(Es),ed=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=>tr(c,s,Ct())));throw _a(a,o?.callee),a}return i.value},td=ed(Es),rd=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 Or;return s.issues.length?{success:!1,error:new(t??ka)(s.issues.map(i=>tr(i,o,Ct())))}:{success:!0,data:s.value}},jn=rd(Es),nd=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=>tr(i,o,Ct())))}:{success:!0,data:s.value}},Ln=nd(Es)});function Mw(){return new RegExp(KA,"u")}function Gw(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 Jw(t){return new RegExp(`^${Gw(t)}$`)}function Yw(t){let e=Gw({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(`^${Kw}T(?:${n})$`)}var Aw,Iw,Ow,Cw,Nw,zw,jw,Lw,sd,Dw,KA,Uw,qw,Bw,Zw,Fw,id,Hw,Vw,Kw,Ww,Xw,Qw,ev,tv,rv,nv,ov,Sa=C(()=>{Aw=/^[cC][^\s-]{8,}$/,Iw=/^[0-9a-z]+$/,Ow=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Cw=/^[0-9a-vA-V]{20}$/,Nw=/^[A-Za-z0-9]{27}$/,zw=/^[a-zA-Z0-9_-]{21}$/,jw=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Lw=/^([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})$/,sd=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)$/,Dw=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,KA="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";Uw=/^(?:(?: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])$/,qw=/^(([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})$/,Bw=/^((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])$/,Zw=/^(([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])$/,Fw=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,id=/^[A-Za-z0-9_-]*$/,Hw=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Vw=/^\+(?:[0-9]){6,14}[0-9]$/,Kw="(?:(?:\\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])))",Ww=new RegExp(`^${Kw}$`);Xw=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Qw=/^\d+$/,ev=/^-?\d+(?:\.\d+)?/i,tv=/true|false/i,rv=/null/i,nv=/^[^A-Z]*$/,ov=/^[^a-z]*$/});var ot,sv,ad,cd,iv,av,cv,lv,uv,Rs,dv,pv,hv,fv,mv,gv,yv,Ta=C(()=>{vo();Sa();gr();ot=O("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),sv={number:"number",bigint:"bigint",object:"date"},ad=O("$ZodCheckLessThan",(t,e)=>{ot.init(t,e);let r=sv[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})}}),cd=O("$ZodCheckGreaterThan",(t,e)=>{ot.init(t,e);let r=sv[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})}}),iv=O("$ZodCheckMultipleOf",(t,e)=>{ot.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):Bu(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})}}),av=O("$ZodCheckNumberFormat",(t,e)=>{ot.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Ku[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=Qw)}),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})}}),cv=O("$ZodCheckMaxLength",(t,e)=>{var r;ot.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!$s(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=Ts(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),lv=O("$ZodCheckMinLength",(t,e)=>{var r;ot.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!$s(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=Ts(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),uv=O("$ZodCheckLengthEquals",(t,e)=>{var r;ot.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!$s(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=Ts(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})}}),Rs=O("$ZodCheckStringFormat",(t,e)=>{var r,n;ot.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=()=>{})}),dv=O("$ZodCheckRegex",(t,e)=>{Rs.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})}}),pv=O("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=nv),Rs.init(t,e)}),hv=O("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=ov),Rs.init(t,e)}),fv=O("$ZodCheckIncludes",(t,e)=>{ot.init(t,e);let r=Gr(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})}}),mv=O("$ZodCheckStartsWith",(t,e)=>{ot.init(t,e);let r=new RegExp(`^${Gr(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})}}),gv=O("$ZodCheckEndsWith",(t,e)=>{ot.init(t,e);let r=new RegExp(`.*${Gr(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})}}),yv=O("$ZodCheckOverwrite",(t,e)=>{ot.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Ea,ld=C(()=>{Ea=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
2002
2009
  `).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(`
2003
- `))}}});var gv,cd=C(()=>{gv={major:4,minor:0,patch:0}});function Av(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function BA(t){if(!od.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Av(r)}function ZA(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 yv(t,e,r){t.issues.length&&e.issues.push(...mr(r,t.issues)),e.value[r]=t.value}function Ta(t,e,r){t.issues.length&&e.issues.push(...mr(r,t.issues)),e.value[r]=t.value}function bv(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(...mr(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function wv(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=>tr(s,n,Ct())))}),e}function ld(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(xo(t)&&xo(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=ld(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=ld(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 vv(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),zn(t))return t;let n=ld(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 _v(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function xv(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 kv(t,e,r){return zn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function $v(t){return t.value=Object.freeze(t.value),t}function Sv(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(Vu(o))}}var Ae,Ps,Ne,ud,dd,pd,hd,fd,md,gd,yd,bd,wd,vd,Tv,Ev,Rv,Pv,_d,xd,kd,$d,Sd,Td,Ed,Rd,Ea,Pd,Ad,Id,Od,Cd,Nd,Ra,Pa,zd,jd,Ld,Dd,Md,Ud,qd,Bd,Zd,Fd,Hd,Vd,Kd,Wd,Gd,Iv=C(()=>{$a();vo();ad();rd();ka();gr();cd();gr();Ae=O("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=gv;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=zn(s),l;for(let u of i){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(c)continue;let p=s.issues.length,w=u._zod.check(s);if(w instanceof Promise&&a?.async===!1)throw new Or;if(l||w instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await w,s.issues.length!==p&&(c||(c=zn(s,p)))});else{if(s.issues.length===p)continue;c||(c=zn(s,p))}}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 Or;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=jn(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Ln(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Ps=O("$ZodString",(t,e)=>{Ae.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Gw(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}}),Ne=O("$ZodStringFormat",(t,e)=>{Rs.init(t,e),Ps.init(t,e)}),ud=O("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Nw),Ne.init(t,e)}),dd=O("$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=nd(n))}else e.pattern??(e.pattern=nd());Ne.init(t,e)}),pd=O("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=zw),Ne.init(t,e)}),hd=O("$ZodURL",(t,e)=>{Ne.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:Bw.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})}}}),fd=O("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=jw()),Ne.init(t,e)}),md=O("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Ow),Ne.init(t,e)}),gd=O("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Ew),Ne.init(t,e)}),yd=O("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Rw),Ne.init(t,e)}),bd=O("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Pw),Ne.init(t,e)}),wd=O("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Aw),Ne.init(t,e)}),vd=O("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Iw),Ne.init(t,e)}),Tv=O("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Ww(e)),Ne.init(t,e)}),Ev=O("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Hw),Ne.init(t,e)}),Rv=O("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Kw(e)),Ne.init(t,e)}),Pv=O("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Cw),Ne.init(t,e)}),_d=O("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Lw),Ne.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),xd=O("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Dw),Ne.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})}}}),kd=O("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Mw),Ne.init(t,e)}),$d=O("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Uw),Ne.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})}}});Sd=O("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=qw),Ne.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{Av(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});Td=O("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=od),Ne.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{BA(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Ed=O("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Zw),Ne.init(t,e)});Rd=O("$ZodJWT",(t,e)=>{Ne.init(t,e),t._zod.check=r=>{ZA(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Ea=O("$ZodNumber",(t,e)=>{Ae.init(t,e),t._zod.pattern=t._zod.bag.pattern??Yw,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}}),Pd=O("$ZodNumber",(t,e)=>{ov.init(t,e),Ea.init(t,e)}),Ad=O("$ZodBoolean",(t,e)=>{Ae.init(t,e),t._zod.pattern=Xw,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}}),Id=O("$ZodNull",(t,e)=>{Ae.init(t,e),t._zod.pattern=Qw,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=O("$ZodUnknown",(t,e)=>{Ae.init(t,e),t._zod.parse=r=>r}),Cd=O("$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)});Nd=O("$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=>yv(l,r,i))):yv(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});Ra=O("$ZodObject",(t,e)=>{Ae.init(t,e);let r=ks(()=>{let p=Object.keys(e.shape);for(let f of p)if(!(e.shape[f]instanceof Ae))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let w=Fu(e.shape);return{shape:e.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(w)}});Ce(t._zod,"propValues",()=>{let p=e.shape,w={};for(let f in p){let h=p[f]._zod;if(h.values){w[f]??(w[f]=new Set);for(let b of h.values)w[f].add(b)}}return w});let n=p=>{let w=new Sa(["shape","payload","ctx"]),f=r.value,h=P=>{let z=Nn(P);return`shape[${z}]._zod.run({ value: input[${z}], issues: [] }, ctx)`};w.write("const input = payload.value;");let b=Object.create(null),$=0;for(let P of f.keys)b[P]=`key_${$++}`;w.write("const newResult = {}");for(let P of f.keys)if(f.optionalKeys.has(P)){let z=b[P];w.write(`const ${z} = ${h(P)};`);let B=Nn(P);w.write(`
2010
+ `))}}});var wv,ud=C(()=>{wv={major:4,minor:0,patch:0}});function Cv(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function WA(t){if(!id.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Cv(r)}function GA(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 vv(t,e,r){t.issues.length&&e.issues.push(...mr(r,t.issues)),e.value[r]=t.value}function Ra(t,e,r){t.issues.length&&e.issues.push(...mr(r,t.issues)),e.value[r]=t.value}function _v(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(...mr(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function xv(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=>tr(s,n,Ct())))}),e}function dd(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(xo(t)&&xo(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=dd(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=dd(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 kv(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),zn(t))return t;let n=dd(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 $v(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function Sv(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 Tv(t,e,r){return zn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function Ev(t){return t.value=Object.freeze(t.value),t}function Rv(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(Wu(o))}}var Ae,Ps,Ne,pd,hd,fd,md,gd,yd,bd,wd,vd,_d,xd,Pv,Av,Iv,Ov,kd,$d,Sd,Td,Ed,Rd,Pd,Ad,Pa,Id,Od,Cd,Nd,zd,jd,Aa,Ia,Ld,Dd,Md,Ud,qd,Bd,Zd,Fd,Hd,Vd,Kd,Wd,Gd,Jd,Yd,Nv=C(()=>{Ta();vo();ld();od();Sa();gr();ud();gr();Ae=O("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=wv;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=zn(s),l;for(let u of i){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(c)continue;let p=s.issues.length,w=u._zod.check(s);if(w instanceof Promise&&a?.async===!1)throw new Or;if(l||w instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await w,s.issues.length!==p&&(c||(c=zn(s,p)))});else{if(s.issues.length===p)continue;c||(c=zn(s,p))}}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 Or;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=jn(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Ln(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Ps=O("$ZodString",(t,e)=>{Ae.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Xw(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}}),Ne=O("$ZodStringFormat",(t,e)=>{Rs.init(t,e),Ps.init(t,e)}),pd=O("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Lw),Ne.init(t,e)}),hd=O("$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=sd(n))}else e.pattern??(e.pattern=sd());Ne.init(t,e)}),fd=O("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Dw),Ne.init(t,e)}),md=O("$ZodURL",(t,e)=>{Ne.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:Hw.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})}}}),gd=O("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Mw()),Ne.init(t,e)}),yd=O("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=zw),Ne.init(t,e)}),bd=O("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Aw),Ne.init(t,e)}),wd=O("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Iw),Ne.init(t,e)}),vd=O("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Ow),Ne.init(t,e)}),_d=O("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Cw),Ne.init(t,e)}),xd=O("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Nw),Ne.init(t,e)}),Pv=O("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Yw(e)),Ne.init(t,e)}),Av=O("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Ww),Ne.init(t,e)}),Iv=O("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Jw(e)),Ne.init(t,e)}),Ov=O("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=jw),Ne.init(t,e)}),kd=O("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Uw),Ne.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),$d=O("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=qw),Ne.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})}}}),Sd=O("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Bw),Ne.init(t,e)}),Td=O("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Zw),Ne.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})}}});Ed=O("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Fw),Ne.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{Cv(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});Rd=O("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=id),Ne.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{WA(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Pd=O("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Vw),Ne.init(t,e)});Ad=O("$ZodJWT",(t,e)=>{Ne.init(t,e),t._zod.check=r=>{GA(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Pa=O("$ZodNumber",(t,e)=>{Ae.init(t,e),t._zod.pattern=t._zod.bag.pattern??ev,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}}),Id=O("$ZodNumber",(t,e)=>{av.init(t,e),Pa.init(t,e)}),Od=O("$ZodBoolean",(t,e)=>{Ae.init(t,e),t._zod.pattern=tv,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}}),Cd=O("$ZodNull",(t,e)=>{Ae.init(t,e),t._zod.pattern=rv,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}}),Nd=O("$ZodUnknown",(t,e)=>{Ae.init(t,e),t._zod.parse=r=>r}),zd=O("$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)});jd=O("$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=>vv(l,r,i))):vv(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});Aa=O("$ZodObject",(t,e)=>{Ae.init(t,e);let r=ks(()=>{let p=Object.keys(e.shape);for(let f of p)if(!(e.shape[f]instanceof Ae))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let w=Vu(e.shape);return{shape:e.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(w)}});Ce(t._zod,"propValues",()=>{let p=e.shape,w={};for(let f in p){let h=p[f]._zod;if(h.values){w[f]??(w[f]=new Set);for(let b of h.values)w[f].add(b)}}return w});let n=p=>{let w=new Ea(["shape","payload","ctx"]),f=r.value,h=P=>{let z=Nn(P);return`shape[${z}]._zod.run({ value: input[${z}], issues: [] }, ctx)`};w.write("const input = payload.value;");let b=Object.create(null),$=0;for(let P of f.keys)b[P]=`key_${$++}`;w.write("const newResult = {}");for(let P of f.keys)if(f.optionalKeys.has(P)){let z=b[P];w.write(`const ${z} = ${h(P)};`);let B=Nn(P);w.write(`
2004
2011
  if (${z}.issues.length) {
2005
2012
  if (input[${B}] === undefined) {
2006
2013
  if (${B} in input) {
@@ -2023,53 +2030,53 @@ export { Label };
2023
2030
  if (${z}.issues.length) payload.issues = payload.issues.concat(${z}.issues.map(iss => ({
2024
2031
  ...iss,
2025
2032
  path: iss.path ? [${Nn(P)}, ...iss.path] : [${Nn(P)}]
2026
- })));`),w.write(`newResult[${Nn(P)}] = ${z}.value`)}w.write("payload.value = newResult;"),w.write("return payload;");let E=w.compile();return(P,z)=>E(p,P,z)},o,s=_o,i=!ya.jitless,c=i&&Bu.value,l=e.catchall,u;t._zod.parse=(p,w)=>{u??(u=r.value);let f=p.value;if(!s(f))return p.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),p;let h=[];if(i&&c&&w?.async===!1&&w.jitless!==!0)o||(o=n(e.shape)),p=o(p,w);else{p.value={};let z=u.shape;for(let B of u.keys){let W=z[B],Ve=W._zod.run({value:f[B],issues:[]},w),Ye=W._zod.optin==="optional"&&W._zod.optout==="optional";Ve instanceof Promise?h.push(Ve.then(Gt=>Ye?bv(Gt,p,B,f):Ta(Gt,p,B))):Ye?bv(Ve,p,B,f):Ta(Ve,p,B)}}if(!l)return h.length?Promise.all(h).then(()=>p):p;let b=[],$=u.keySet,E=l._zod,P=E.def.type;for(let z of Object.keys(f)){if($.has(z))continue;if(P==="never"){b.push(z);continue}let B=E.run({value:f[z],issues:[]},w);B instanceof Promise?h.push(B.then(W=>Ta(W,p,z))):Ta(B,p,z)}return b.length&&p.issues.push({code:"unrecognized_keys",keys:b,input:f,inst:t}),h.length?Promise.all(h).then(()=>p):p}});Pa=O("$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=>Ss(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=>wv(i,r,t,n)):wv(s,r,t,n)}}),zd=O("$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=ks(()=>{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(!_o(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)}}),jd=O("$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])=>vv(r,c,l)):vv(r,s,i)}});Ld=O("$ZodRecord",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!xo(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(...mr(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...mr(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=>tr(l,n,Ct())),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(...mr(i,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...mr(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Dd=O("$ZodEnum",(t,e)=>{Ae.init(t,e);let r=xs(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Zu.has(typeof n)).map(n=>typeof n=="string"?Gr(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}}),Md=O("$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"?Gr(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}}),Ud=O("$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 Or;return r.value=o,r}}),qd=O("$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(`^(${Ss(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)}),Bd=O("$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(`^(${Ss(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)}),Zd=O("$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=>_v(s,e)):_v(o,e)}});Fd=O("$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))}),Hd=O("$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=>xv(s,t)):xv(o,t)}});Vd=O("$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=>tr(i,n,Ct()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>tr(s,n,Ct()))},input:r.value}),r.issues=[]),r)}}),Kd=O("$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=>kv(s,e,n)):kv(o,e,n)}});Wd=O("$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($v):$v(o)}});Gd=O("$ZodCustom",(t,e)=>{ot.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=>Sv(s,r,n,t));Sv(o,r,n,t)}})});function Ov(){return{localeError:HA()}}var FA,HA,Cv=C(()=>{gr();FA=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},HA=()=>{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 ${FA(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${va(n.values[0])}`:`Invalid option: expected one of ${ba(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":""}: ${ba(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 Aa=C(()=>{});function Nv(){return new As}var As,Jr,Yd=C(()=>{As=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)}};Jr=Nv()});function Xd(t,e){return new t({type:"string",...oe(e)})}function Qd(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...oe(e)})}function Ia(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...oe(e)})}function ep(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...oe(e)})}function tp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...oe(e)})}function rp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...oe(e)})}function np(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...oe(e)})}function op(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...oe(e)})}function sp(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...oe(e)})}function ip(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...oe(e)})}function ap(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...oe(e)})}function cp(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...oe(e)})}function lp(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...oe(e)})}function up(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...oe(e)})}function dp(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...oe(e)})}function pp(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...oe(e)})}function hp(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...oe(e)})}function fp(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...oe(e)})}function mp(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...oe(e)})}function gp(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...oe(e)})}function yp(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...oe(e)})}function bp(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...oe(e)})}function wp(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...oe(e)})}function zv(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...oe(e)})}function jv(t,e){return new t({type:"string",format:"date",check:"string_format",...oe(e)})}function Lv(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...oe(e)})}function Dv(t,e){return new t({type:"string",format:"duration",check:"string_format",...oe(e)})}function vp(t,e){return new t({type:"number",checks:[],...oe(e)})}function _p(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...oe(e)})}function xp(t,e){return new t({type:"boolean",...oe(e)})}function kp(t,e){return new t({type:"null",...oe(e)})}function $p(t){return new t({type:"unknown"})}function Sp(t,e){return new t({type:"never",...oe(e)})}function Oa(t,e){return new sd({check:"less_than",...oe(e),value:t,inclusive:!1})}function Is(t,e){return new sd({check:"less_than",...oe(e),value:t,inclusive:!0})}function Ca(t,e){return new id({check:"greater_than",...oe(e),value:t,inclusive:!1})}function Os(t,e){return new id({check:"greater_than",...oe(e),value:t,inclusive:!0})}function Na(t,e){return new nv({check:"multiple_of",...oe(e),value:t})}function za(t,e){return new sv({check:"max_length",...oe(e),maximum:t})}function ko(t,e){return new iv({check:"min_length",...oe(e),minimum:t})}function ja(t,e){return new av({check:"length_equals",...oe(e),length:t})}function Tp(t,e){return new cv({check:"string_format",format:"regex",...oe(e),pattern:t})}function Ep(t){return new lv({check:"string_format",format:"lowercase",...oe(t)})}function Rp(t){return new uv({check:"string_format",format:"uppercase",...oe(t)})}function Pp(t,e){return new dv({check:"string_format",format:"includes",...oe(e),includes:t})}function Ap(t,e){return new pv({check:"string_format",format:"starts_with",...oe(e),prefix:t})}function Ip(t,e){return new hv({check:"string_format",format:"ends_with",...oe(e),suffix:t})}function Dn(t){return new fv({check:"overwrite",tx:t})}function Op(t){return Dn(e=>e.normalize(t))}function Cp(){return Dn(t=>t.trim())}function Np(){return Dn(t=>t.toLowerCase())}function zp(){return Dn(t=>t.toUpperCase())}function Mv(t,e,r){return new t({type:"array",element:e,...oe(r)})}function jp(t,e,r){let n=oe(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,...oe(r)})}var Uv=C(()=>{$a();gr()});var qv=C(()=>{});function Dp(t,e){if(t instanceof As){let n=new La(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 La(e);return r.process(t),r.emit(t,e)}function Xe(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 Xe(o.element,r);case"object":{for(let s in o.shape)if(Xe(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(Xe(s,r))return!0;return!1}case"intersection":return Xe(o.left,r)||Xe(o.right,r);case"tuple":{for(let s of o.items)if(Xe(s,r))return!0;return!!(o.rest&&Xe(o.rest,r))}case"record":return Xe(o.keyType,r)||Xe(o.valueType,r);case"map":return Xe(o.keyType,r)||Xe(o.valueType,r);case"set":return Xe(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Xe(o.innerType,r);case"lazy":return Xe(o.getter(),r);case"default":return Xe(o.innerType,r);case"prefault":return Xe(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Xe(o.in,r)||Xe(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var La,Bv=C(()=>{Yd();gr();La=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Jr,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 p={...r,schemaPath:[...r.schemaPath,e],path:r.path},w=e._zod.parent;if(w)a.ref=w,this.process(w,p),this.seen.get(w).isParent=!0;else{let f=a.schema;switch(o.type){case"string":{let h=f;h.type="string";let{minimum:b,maximum:$,format:E,patterns:P,contentEncoding:z}=e._zod.bag;if(typeof b=="number"&&(h.minLength=b),typeof $=="number"&&(h.maxLength=$),E&&(h.format=s[E]??E,h.format===""&&delete h.format),z&&(h.contentEncoding=z),P&&P.size>0){let B=[...P];B.length===1?h.pattern=B[0].source:B.length>1&&(a.schema.allOf=[...B.map(W=>({...this.target==="draft-7"?{type:"string"}:{},pattern:W.source}))])}break}case"number":{let h=f,{minimum:b,maximum:$,format:E,multipleOf:P,exclusiveMaximum:z,exclusiveMinimum:B}=e._zod.bag;typeof E=="string"&&E.includes("int")?h.type="integer":h.type="number",typeof B=="number"&&(h.exclusiveMinimum=B),typeof b=="number"&&(h.minimum=b,typeof B=="number"&&(B>=b?delete h.minimum:delete h.exclusiveMinimum)),typeof z=="number"&&(h.exclusiveMaximum=z),typeof $=="number"&&(h.maximum=$,typeof z=="number"&&(z<=$?delete h.maximum:delete h.exclusiveMaximum)),typeof P=="number"&&(h.multipleOf=P);break}case"boolean":{let h=f;h.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":{f.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":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let h=f,{minimum:b,maximum:$}=e._zod.bag;typeof b=="number"&&(h.minItems=b),typeof $=="number"&&(h.maxItems=$),h.type="array",h.items=this.process(o.element,{...p,path:[...p.path,"items"]});break}case"object":{let h=f;h.type="object",h.properties={};let b=o.shape;for(let P in b)h.properties[P]=this.process(b[P],{...p,path:[...p.path,"properties",P]});let $=new Set(Object.keys(b)),E=new Set([...$].filter(P=>{let z=o.shape[P]._zod;return this.io==="input"?z.optin===void 0:z.optout===void 0}));E.size>0&&(h.required=Array.from(E)),o.catchall?._zod.def.type==="never"?h.additionalProperties=!1:o.catchall?o.catchall&&(h.additionalProperties=this.process(o.catchall,{...p,path:[...p.path,"additionalProperties"]})):this.io==="output"&&(h.additionalProperties=!1);break}case"union":{let h=f;h.anyOf=o.options.map((b,$)=>this.process(b,{...p,path:[...p.path,"anyOf",$]}));break}case"intersection":{let h=f,b=this.process(o.left,{...p,path:[...p.path,"allOf",0]}),$=this.process(o.right,{...p,path:[...p.path,"allOf",1]}),E=z=>"allOf"in z&&Object.keys(z).length===1,P=[...E(b)?b.allOf:[b],...E($)?$.allOf:[$]];h.allOf=P;break}case"tuple":{let h=f;h.type="array";let b=o.items.map((P,z)=>this.process(P,{...p,path:[...p.path,"prefixItems",z]}));if(this.target==="draft-2020-12"?h.prefixItems=b:h.items=b,o.rest){let P=this.process(o.rest,{...p,path:[...p.path,"items"]});this.target==="draft-2020-12"?h.items=P:h.additionalItems=P}o.rest&&(h.items=this.process(o.rest,{...p,path:[...p.path,"items"]}));let{minimum:$,maximum:E}=e._zod.bag;typeof $=="number"&&(h.minItems=$),typeof E=="number"&&(h.maxItems=E);break}case"record":{let h=f;h.type="object",h.propertyNames=this.process(o.keyType,{...p,path:[...p.path,"propertyNames"]}),h.additionalProperties=this.process(o.valueType,{...p,path:[...p.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 h=f,b=xs(o.entries);b.every($=>typeof $=="number")&&(h.type="number"),b.every($=>typeof $=="string")&&(h.type="string"),h.enum=b;break}case"literal":{let h=f,b=[];for(let $ of o.values)if($===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof $=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");b.push(Number($))}else b.push($);if(b.length!==0)if(b.length===1){let $=b[0];h.type=$===null?"null":typeof $,h.const=$}else b.every($=>typeof $=="number")&&(h.type="number"),b.every($=>typeof $=="string")&&(h.type="string"),b.every($=>typeof $=="boolean")&&(h.type="string"),b.every($=>$===null)&&(h.type="null"),h.enum=b;break}case"file":{let h=f,b={type:"string",format:"binary",contentEncoding:"binary"},{minimum:$,maximum:E,mime:P}=e._zod.bag;$!==void 0&&(b.minLength=$),E!==void 0&&(b.maxLength=E),P?P.length===1?(b.contentMediaType=P[0],Object.assign(h,b)):h.anyOf=P.map(z=>({...b,contentMediaType:z})):Object.assign(h,b);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let h=this.process(o.innerType,p);f.anyOf=[h,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,p),a.ref=o.innerType;break}case"success":{let h=f;h.type="boolean";break}case"default":{this.process(o.innerType,p),a.ref=o.innerType,f.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,p),a.ref=o.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,p),a.ref=o.innerType;let h;try{h=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=h;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let h=f,b=e._zod.pattern;if(!b)throw new Error("Pattern not found in template literal");h.type="string",h.pattern=b.source;break}case"pipe":{let h=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(h,p),a.ref=h;break}case"readonly":{this.process(o.innerType,p),a.ref=o.innerType,f.readOnly=!0;break}case"promise":{this.process(o.innerType,p),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,p),a.ref=o.innerType;break}case"lazy":{let h=e._zod.innerType;this.process(h,p),a.ref=h;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"&&Xe(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 p=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let b=n.external.registry.get(u[0])?.id,$=n.external.uri??(P=>P);if(b)return{ref:$(b)};let E=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=E,{defId:E,ref:`${$("__shared")}#/${p}/${E}`}}if(u[1]===o)return{ref:"#"};let f=`#/${p}/`,h=u[1].schema.id??`__schema${this.counter++}`;return{defId:h,ref:f+h}},i=u=>{if(u[1].schema.$ref)return;let p=u[1],{ref:w,defId:f}=s(u);p.def={...p.schema},f&&(p.defId=f);let h=p.schema;for(let b in h)delete h[b];h.$ref=w};if(n.cycles==="throw")for(let u of this.seen.entries()){let p=u[1];if(p.cycle)throw new Error(`Cycle detected: #/${p.cycle?.join("/")}/<root>
2033
+ })));`),w.write(`newResult[${Nn(P)}] = ${z}.value`)}w.write("payload.value = newResult;"),w.write("return payload;");let E=w.compile();return(P,z)=>E(p,P,z)},o,s=_o,i=!wa.jitless,c=i&&Fu.value,l=e.catchall,u;t._zod.parse=(p,w)=>{u??(u=r.value);let f=p.value;if(!s(f))return p.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),p;let h=[];if(i&&c&&w?.async===!1&&w.jitless!==!0)o||(o=n(e.shape)),p=o(p,w);else{p.value={};let z=u.shape;for(let B of u.keys){let W=z[B],Ve=W._zod.run({value:f[B],issues:[]},w),Ye=W._zod.optin==="optional"&&W._zod.optout==="optional";Ve instanceof Promise?h.push(Ve.then(Gt=>Ye?_v(Gt,p,B,f):Ra(Gt,p,B))):Ye?_v(Ve,p,B,f):Ra(Ve,p,B)}}if(!l)return h.length?Promise.all(h).then(()=>p):p;let b=[],$=u.keySet,E=l._zod,P=E.def.type;for(let z of Object.keys(f)){if($.has(z))continue;if(P==="never"){b.push(z);continue}let B=E.run({value:f[z],issues:[]},w);B instanceof Promise?h.push(B.then(W=>Ra(W,p,z))):Ra(B,p,z)}return b.length&&p.issues.push({code:"unrecognized_keys",keys:b,input:f,inst:t}),h.length?Promise.all(h).then(()=>p):p}});Ia=O("$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=>Ss(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=>xv(i,r,t,n)):xv(s,r,t,n)}}),Ld=O("$ZodDiscriminatedUnion",(t,e)=>{Ia.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=ks(()=>{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(!_o(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)}}),Dd=O("$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])=>kv(r,c,l)):kv(r,s,i)}});Md=O("$ZodRecord",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!xo(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(...mr(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...mr(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=>tr(l,n,Ct())),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(...mr(i,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...mr(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Ud=O("$ZodEnum",(t,e)=>{Ae.init(t,e);let r=xs(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Hu.has(typeof n)).map(n=>typeof n=="string"?Gr(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}}),qd=O("$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"?Gr(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}}),Bd=O("$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 Or;return r.value=o,r}}),Zd=O("$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(`^(${Ss(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)}),Fd=O("$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(`^(${Ss(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)}),Hd=O("$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=>$v(s,e)):$v(o,e)}});Vd=O("$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))}),Kd=O("$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=>Sv(s,t)):Sv(o,t)}});Wd=O("$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=>tr(i,n,Ct()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>tr(s,n,Ct()))},input:r.value}),r.issues=[]),r)}}),Gd=O("$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=>Tv(s,e,n)):Tv(o,e,n)}});Jd=O("$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(Ev):Ev(o)}});Yd=O("$ZodCustom",(t,e)=>{ot.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=>Rv(s,r,n,t));Rv(o,r,n,t)}})});function zv(){return{localeError:YA()}}var JA,YA,jv=C(()=>{gr();JA=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},YA=()=>{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 ${JA(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${xa(n.values[0])}`:`Invalid option: expected one of ${va(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":""}: ${va(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 Oa=C(()=>{});function Lv(){return new As}var As,Jr,Qd=C(()=>{As=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)}};Jr=Lv()});function ep(t,e){return new t({type:"string",...oe(e)})}function tp(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...oe(e)})}function Ca(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...oe(e)})}function rp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...oe(e)})}function np(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...oe(e)})}function op(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...oe(e)})}function sp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...oe(e)})}function ip(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...oe(e)})}function ap(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...oe(e)})}function cp(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...oe(e)})}function lp(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...oe(e)})}function up(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...oe(e)})}function dp(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...oe(e)})}function pp(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...oe(e)})}function hp(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...oe(e)})}function fp(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...oe(e)})}function mp(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...oe(e)})}function gp(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...oe(e)})}function yp(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...oe(e)})}function bp(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...oe(e)})}function wp(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...oe(e)})}function vp(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...oe(e)})}function _p(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...oe(e)})}function Dv(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...oe(e)})}function Mv(t,e){return new t({type:"string",format:"date",check:"string_format",...oe(e)})}function Uv(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...oe(e)})}function qv(t,e){return new t({type:"string",format:"duration",check:"string_format",...oe(e)})}function xp(t,e){return new t({type:"number",checks:[],...oe(e)})}function kp(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...oe(e)})}function $p(t,e){return new t({type:"boolean",...oe(e)})}function Sp(t,e){return new t({type:"null",...oe(e)})}function Tp(t){return new t({type:"unknown"})}function Ep(t,e){return new t({type:"never",...oe(e)})}function Na(t,e){return new ad({check:"less_than",...oe(e),value:t,inclusive:!1})}function Is(t,e){return new ad({check:"less_than",...oe(e),value:t,inclusive:!0})}function za(t,e){return new cd({check:"greater_than",...oe(e),value:t,inclusive:!1})}function Os(t,e){return new cd({check:"greater_than",...oe(e),value:t,inclusive:!0})}function ja(t,e){return new iv({check:"multiple_of",...oe(e),value:t})}function La(t,e){return new cv({check:"max_length",...oe(e),maximum:t})}function ko(t,e){return new lv({check:"min_length",...oe(e),minimum:t})}function Da(t,e){return new uv({check:"length_equals",...oe(e),length:t})}function Rp(t,e){return new dv({check:"string_format",format:"regex",...oe(e),pattern:t})}function Pp(t){return new pv({check:"string_format",format:"lowercase",...oe(t)})}function Ap(t){return new hv({check:"string_format",format:"uppercase",...oe(t)})}function Ip(t,e){return new fv({check:"string_format",format:"includes",...oe(e),includes:t})}function Op(t,e){return new mv({check:"string_format",format:"starts_with",...oe(e),prefix:t})}function Cp(t,e){return new gv({check:"string_format",format:"ends_with",...oe(e),suffix:t})}function Dn(t){return new yv({check:"overwrite",tx:t})}function Np(t){return Dn(e=>e.normalize(t))}function zp(){return Dn(t=>t.trim())}function jp(){return Dn(t=>t.toLowerCase())}function Lp(){return Dn(t=>t.toUpperCase())}function Bv(t,e,r){return new t({type:"array",element:e,...oe(r)})}function Dp(t,e,r){let n=oe(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Mp(t,e,r){return new t({type:"custom",check:"custom",fn:e,...oe(r)})}var Zv=C(()=>{Ta();gr()});var Fv=C(()=>{});function Up(t,e){if(t instanceof As){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 Xe(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 Xe(o.element,r);case"object":{for(let s in o.shape)if(Xe(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(Xe(s,r))return!0;return!1}case"intersection":return Xe(o.left,r)||Xe(o.right,r);case"tuple":{for(let s of o.items)if(Xe(s,r))return!0;return!!(o.rest&&Xe(o.rest,r))}case"record":return Xe(o.keyType,r)||Xe(o.valueType,r);case"map":return Xe(o.keyType,r)||Xe(o.valueType,r);case"set":return Xe(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Xe(o.innerType,r);case"lazy":return Xe(o.getter(),r);case"default":return Xe(o.innerType,r);case"prefault":return Xe(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Xe(o.in,r)||Xe(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var Ma,Hv=C(()=>{Qd();gr();Ma=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Jr,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 p={...r,schemaPath:[...r.schemaPath,e],path:r.path},w=e._zod.parent;if(w)a.ref=w,this.process(w,p),this.seen.get(w).isParent=!0;else{let f=a.schema;switch(o.type){case"string":{let h=f;h.type="string";let{minimum:b,maximum:$,format:E,patterns:P,contentEncoding:z}=e._zod.bag;if(typeof b=="number"&&(h.minLength=b),typeof $=="number"&&(h.maxLength=$),E&&(h.format=s[E]??E,h.format===""&&delete h.format),z&&(h.contentEncoding=z),P&&P.size>0){let B=[...P];B.length===1?h.pattern=B[0].source:B.length>1&&(a.schema.allOf=[...B.map(W=>({...this.target==="draft-7"?{type:"string"}:{},pattern:W.source}))])}break}case"number":{let h=f,{minimum:b,maximum:$,format:E,multipleOf:P,exclusiveMaximum:z,exclusiveMinimum:B}=e._zod.bag;typeof E=="string"&&E.includes("int")?h.type="integer":h.type="number",typeof B=="number"&&(h.exclusiveMinimum=B),typeof b=="number"&&(h.minimum=b,typeof B=="number"&&(B>=b?delete h.minimum:delete h.exclusiveMinimum)),typeof z=="number"&&(h.exclusiveMaximum=z),typeof $=="number"&&(h.maximum=$,typeof z=="number"&&(z<=$?delete h.maximum:delete h.exclusiveMaximum)),typeof P=="number"&&(h.multipleOf=P);break}case"boolean":{let h=f;h.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":{f.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":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let h=f,{minimum:b,maximum:$}=e._zod.bag;typeof b=="number"&&(h.minItems=b),typeof $=="number"&&(h.maxItems=$),h.type="array",h.items=this.process(o.element,{...p,path:[...p.path,"items"]});break}case"object":{let h=f;h.type="object",h.properties={};let b=o.shape;for(let P in b)h.properties[P]=this.process(b[P],{...p,path:[...p.path,"properties",P]});let $=new Set(Object.keys(b)),E=new Set([...$].filter(P=>{let z=o.shape[P]._zod;return this.io==="input"?z.optin===void 0:z.optout===void 0}));E.size>0&&(h.required=Array.from(E)),o.catchall?._zod.def.type==="never"?h.additionalProperties=!1:o.catchall?o.catchall&&(h.additionalProperties=this.process(o.catchall,{...p,path:[...p.path,"additionalProperties"]})):this.io==="output"&&(h.additionalProperties=!1);break}case"union":{let h=f;h.anyOf=o.options.map((b,$)=>this.process(b,{...p,path:[...p.path,"anyOf",$]}));break}case"intersection":{let h=f,b=this.process(o.left,{...p,path:[...p.path,"allOf",0]}),$=this.process(o.right,{...p,path:[...p.path,"allOf",1]}),E=z=>"allOf"in z&&Object.keys(z).length===1,P=[...E(b)?b.allOf:[b],...E($)?$.allOf:[$]];h.allOf=P;break}case"tuple":{let h=f;h.type="array";let b=o.items.map((P,z)=>this.process(P,{...p,path:[...p.path,"prefixItems",z]}));if(this.target==="draft-2020-12"?h.prefixItems=b:h.items=b,o.rest){let P=this.process(o.rest,{...p,path:[...p.path,"items"]});this.target==="draft-2020-12"?h.items=P:h.additionalItems=P}o.rest&&(h.items=this.process(o.rest,{...p,path:[...p.path,"items"]}));let{minimum:$,maximum:E}=e._zod.bag;typeof $=="number"&&(h.minItems=$),typeof E=="number"&&(h.maxItems=E);break}case"record":{let h=f;h.type="object",h.propertyNames=this.process(o.keyType,{...p,path:[...p.path,"propertyNames"]}),h.additionalProperties=this.process(o.valueType,{...p,path:[...p.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 h=f,b=xs(o.entries);b.every($=>typeof $=="number")&&(h.type="number"),b.every($=>typeof $=="string")&&(h.type="string"),h.enum=b;break}case"literal":{let h=f,b=[];for(let $ of o.values)if($===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof $=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");b.push(Number($))}else b.push($);if(b.length!==0)if(b.length===1){let $=b[0];h.type=$===null?"null":typeof $,h.const=$}else b.every($=>typeof $=="number")&&(h.type="number"),b.every($=>typeof $=="string")&&(h.type="string"),b.every($=>typeof $=="boolean")&&(h.type="string"),b.every($=>$===null)&&(h.type="null"),h.enum=b;break}case"file":{let h=f,b={type:"string",format:"binary",contentEncoding:"binary"},{minimum:$,maximum:E,mime:P}=e._zod.bag;$!==void 0&&(b.minLength=$),E!==void 0&&(b.maxLength=E),P?P.length===1?(b.contentMediaType=P[0],Object.assign(h,b)):h.anyOf=P.map(z=>({...b,contentMediaType:z})):Object.assign(h,b);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let h=this.process(o.innerType,p);f.anyOf=[h,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,p),a.ref=o.innerType;break}case"success":{let h=f;h.type="boolean";break}case"default":{this.process(o.innerType,p),a.ref=o.innerType,f.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,p),a.ref=o.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,p),a.ref=o.innerType;let h;try{h=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=h;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let h=f,b=e._zod.pattern;if(!b)throw new Error("Pattern not found in template literal");h.type="string",h.pattern=b.source;break}case"pipe":{let h=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(h,p),a.ref=h;break}case"readonly":{this.process(o.innerType,p),a.ref=o.innerType,f.readOnly=!0;break}case"promise":{this.process(o.innerType,p),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,p),a.ref=o.innerType;break}case"lazy":{let h=e._zod.innerType;this.process(h,p),a.ref=h;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"&&Xe(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 p=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let b=n.external.registry.get(u[0])?.id,$=n.external.uri??(P=>P);if(b)return{ref:$(b)};let E=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=E,{defId:E,ref:`${$("__shared")}#/${p}/${E}`}}if(u[1]===o)return{ref:"#"};let f=`#/${p}/`,h=u[1].schema.id??`__schema${this.counter++}`;return{defId:h,ref:f+h}},i=u=>{if(u[1].schema.$ref)return;let p=u[1],{ref:w,defId:f}=s(u);p.def={...p.schema},f&&(p.defId=f);let h=p.schema;for(let b in h)delete h[b];h.$ref=w};if(n.cycles==="throw")for(let u of this.seen.entries()){let p=u[1];if(p.cycle)throw new Error(`Cycle detected: #/${p.cycle?.join("/")}/<root>
2027
2034
 
2028
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let u of this.seen.entries()){let p=u[1];if(e===u[0]){i(u);continue}if(n.external){let f=n.external.registry.get(u[0])?.id;if(e!==u[0]&&f){i(u);continue}}if(this.metadataRegistry.get(u[0])?.id){i(u);continue}if(p.cycle){i(u);continue}if(p.count>1&&n.reused==="ref"){i(u);continue}}let a=(u,p)=>{let w=this.seen.get(u),f=w.def??w.schema,h={...f};if(w.ref===null)return;let b=w.ref;if(w.ref=null,b){a(b,p);let $=this.seen.get(b).schema;$.$ref&&p.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push($)):(Object.assign(f,$),Object.assign(f,h))}w.isParent||this.override({zodSchema:u,jsonSchema:f,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 p=u[1];p.def&&p.defId&&(l[p.defId]=p.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 Zv=C(()=>{});var gt=C(()=>{vo();rd();Gu();Iv();$a();cd();gr();ka();Aa();Yd();ad();qv();Uv();Bv();Zv()});var Mp=C(()=>{gt()});function Up(t,e){let r={type:"object",get shape(){return we.assignProp(this,"shape",{...t}),this.shape},...we.normalizeParams(e)};return new EI(r)}var TI,EI,Fv=C(()=>{gt();gt();Mp();TI=O("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");Ae.init(t,e),t.def=e,t.parse=(r,n)=>Yu(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>jn(t,r,n),t.parseAsync=async(r,n)=>Qu(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Ln(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)=>Nt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),EI=O("ZodMiniObject",(t,e)=>{Ra.init(t,e),TI.init(t,e),we.defineLazy(t,"shape",()=>e.shape)})});var Hv=C(()=>{});var Vv=C(()=>{});var Kv=C(()=>{});var Wv=C(()=>{gt();Mp();Fv();Hv();gt();Aa();Vv();Kv()});var Gv=C(()=>{Wv()});var qp=C(()=>{Gv()});function yr(t){return!!t._zod}function Un(t){let e=Object.values(t);if(e.length===0)return Up({});let r=e.every(yr),n=e.every(o=>!yr(o));if(r)return Up(t);if(n)return zl(t);throw new Error("Mixed Zod versions detected in object shape.")}function Yr(t,e){return yr(t)?jn(t,e):t.safeParse(e)}async function Da(t,e){return yr(t)?await Ln(t,e):await t.safeParseAsync(e)}function Xr(t){if(!t)return;let e;if(yr(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function $o(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 Un(t)}}if(yr(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 AI(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function Ma(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 ${AI(e.path)}`:e.message).join(`
2029
- `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function Yv(t){return t.description}function Xv(t){if(yr(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function So(t){if(yr(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 Cs=C(()=>{vs();qp()});var Bp=C(()=>{gt()});var Ns={};Yo(Ns,{ZodISODate:()=>e_,ZodISODateTime:()=>Qv,ZodISODuration:()=>r_,ZodISOTime:()=>t_,date:()=>Fp,datetime:()=>Zp,duration:()=>Vp,time:()=>Hp});function Zp(t){return zv(Qv,t)}function Fp(t){return jv(e_,t)}function Hp(t){return Lv(t_,t)}function Vp(t){return Dv(r_,t)}var Qv,e_,t_,r_,Kp=C(()=>{gt();Wp();Qv=O("ZodISODateTime",(t,e)=>{Tv.init(t,e),Ue.init(t,e)});e_=O("ZodISODate",(t,e)=>{Ev.init(t,e),Ue.init(t,e)});t_=O("ZodISOTime",(t,e)=>{Rv.init(t,e),Ue.init(t,e)});r_=O("ZodISODuration",(t,e)=>{Pv.init(t,e),Ue.init(t,e)})});var n_,a4,zs,Gp=C(()=>{gt();gt();n_=(t,e)=>{_a.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Wu(t,r)},flatten:{value:r=>Ku(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},a4=O("ZodError",n_),zs=O("ZodError",n_,{Parent:Error})});var o_,s_,i_,a_,Jp=C(()=>{gt();Gp();o_=Ju(zs),s_=Xu(zs),i_=ed(zs),a_=td(zs)});function I(t){return Xd(DI,t)}function Re(t){return vp(p_,t)}function l_(t){return _p(rO,t)}function rt(t){return xp(nO,t)}function h_(t){return kp(oO,t)}function qe(){return $p(sO)}function aO(t){return Sp(iO,t)}function _e(t,e){return Mv(cO,t,e)}function K(t,e){let r={type:"object",get shape(){return we.assignProp(this,"shape",{...t}),this.shape},...we.normalizeParams(e)};return new f_(r)}function yt(t,e){return new f_({type:"object",get shape(){return we.assignProp(this,"shape",{...t}),this.shape},catchall:qe(),...we.normalizeParams(e)})}function je(t,e){return new m_({type:"union",options:t,...we.normalizeParams(e)})}function Qp(t,e,r){return new lO({type:"union",options:e,discriminator:t,...we.normalizeParams(r)})}function qa(t,e){return new uO({type:"intersection",left:t,right:e})}function ze(t,e,r){return new dO({type:"record",keyType:t,valueType:e,...we.normalizeParams(r)})}function Et(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Yp({type:"enum",entries:r,...we.normalizeParams(e)})}function Y(t,e){return new pO({type:"literal",values:Array.isArray(t)?t:[t],...we.normalizeParams(e)})}function g_(t){return new hO({type:"transform",transform:t})}function Be(t){return new y_({type:"optional",innerType:t})}function u_(t){return new fO({type:"nullable",innerType:t})}function gO(t,e){return new mO({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function bO(t,e){return new yO({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function wO(t,e){return new b_({type:"nonoptional",innerType:t,...we.normalizeParams(e)})}function _O(t,e){return new vO({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function Xp(t,e){return new xO({type:"pipe",in:t,out:e})}function $O(t){return new kO({type:"readonly",innerType:t})}function SO(t){let e=new ot({check:"custom"});return e._zod.check=t,e}function v_(t,e){return jp(w_,t??(()=>!0),e)}function TO(t,e={}){return Lp(w_,t,e)}function EO(t){let e=SO(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(we.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(we.issue(o))}},t(r.value,r)));return e}function eh(t,e){return Xp(g_(t),e)}var Fe,d_,DI,Ue,MI,c_,Ua,UI,qI,BI,ZI,FI,HI,VI,KI,WI,GI,JI,YI,XI,QI,eO,tO,p_,rO,nO,oO,sO,iO,cO,f_,m_,lO,uO,dO,Yp,pO,hO,y_,fO,mO,yO,b_,vO,xO,kO,w_,Wp=C(()=>{gt();gt();Bp();Kp();Jp();Fe=O("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)=>Nt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>o_(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>i_(t,r,n),t.parseAsync=async(r,n)=>s_(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>a_(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(TO(r,n)),t.superRefine=r=>t.check(EO(r)),t.overwrite=r=>t.check(Dn(r)),t.optional=()=>Be(t),t.nullable=()=>u_(t),t.nullish=()=>Be(u_(t)),t.nonoptional=r=>wO(t,r),t.array=()=>_e(t),t.or=r=>je([t,r]),t.and=r=>qa(t,r),t.transform=r=>Xp(t,g_(r)),t.default=r=>gO(t,r),t.prefault=r=>bO(t,r),t.catch=r=>_O(t,r),t.pipe=r=>Xp(t,r),t.readonly=()=>$O(t),t.describe=r=>{let n=t.clone();return Jr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Jr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Jr.get(t);let n=t.clone();return Jr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),d_=O("_ZodString",(t,e)=>{Ps.init(t,e),Fe.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Tp(...n)),t.includes=(...n)=>t.check(Pp(...n)),t.startsWith=(...n)=>t.check(Ap(...n)),t.endsWith=(...n)=>t.check(Ip(...n)),t.min=(...n)=>t.check(ko(...n)),t.max=(...n)=>t.check(za(...n)),t.length=(...n)=>t.check(ja(...n)),t.nonempty=(...n)=>t.check(ko(1,...n)),t.lowercase=n=>t.check(Ep(n)),t.uppercase=n=>t.check(Rp(n)),t.trim=()=>t.check(Cp()),t.normalize=(...n)=>t.check(Op(...n)),t.toLowerCase=()=>t.check(Np()),t.toUpperCase=()=>t.check(zp())}),DI=O("ZodString",(t,e)=>{Ps.init(t,e),d_.init(t,e),t.email=r=>t.check(Qd(MI,r)),t.url=r=>t.check(op(UI,r)),t.jwt=r=>t.check(wp(tO,r)),t.emoji=r=>t.check(sp(qI,r)),t.guid=r=>t.check(Ia(c_,r)),t.uuid=r=>t.check(ep(Ua,r)),t.uuidv4=r=>t.check(tp(Ua,r)),t.uuidv6=r=>t.check(rp(Ua,r)),t.uuidv7=r=>t.check(np(Ua,r)),t.nanoid=r=>t.check(ip(BI,r)),t.guid=r=>t.check(Ia(c_,r)),t.cuid=r=>t.check(ap(ZI,r)),t.cuid2=r=>t.check(cp(FI,r)),t.ulid=r=>t.check(lp(HI,r)),t.base64=r=>t.check(gp(XI,r)),t.base64url=r=>t.check(yp(QI,r)),t.xid=r=>t.check(up(VI,r)),t.ksuid=r=>t.check(dp(KI,r)),t.ipv4=r=>t.check(pp(WI,r)),t.ipv6=r=>t.check(hp(GI,r)),t.cidrv4=r=>t.check(fp(JI,r)),t.cidrv6=r=>t.check(mp(YI,r)),t.e164=r=>t.check(bp(eO,r)),t.datetime=r=>t.check(Zp(r)),t.date=r=>t.check(Fp(r)),t.time=r=>t.check(Hp(r)),t.duration=r=>t.check(Vp(r))});Ue=O("ZodStringFormat",(t,e)=>{Ne.init(t,e),d_.init(t,e)}),MI=O("ZodEmail",(t,e)=>{pd.init(t,e),Ue.init(t,e)}),c_=O("ZodGUID",(t,e)=>{ud.init(t,e),Ue.init(t,e)}),Ua=O("ZodUUID",(t,e)=>{dd.init(t,e),Ue.init(t,e)}),UI=O("ZodURL",(t,e)=>{hd.init(t,e),Ue.init(t,e)}),qI=O("ZodEmoji",(t,e)=>{fd.init(t,e),Ue.init(t,e)}),BI=O("ZodNanoID",(t,e)=>{md.init(t,e),Ue.init(t,e)}),ZI=O("ZodCUID",(t,e)=>{gd.init(t,e),Ue.init(t,e)}),FI=O("ZodCUID2",(t,e)=>{yd.init(t,e),Ue.init(t,e)}),HI=O("ZodULID",(t,e)=>{bd.init(t,e),Ue.init(t,e)}),VI=O("ZodXID",(t,e)=>{wd.init(t,e),Ue.init(t,e)}),KI=O("ZodKSUID",(t,e)=>{vd.init(t,e),Ue.init(t,e)}),WI=O("ZodIPv4",(t,e)=>{_d.init(t,e),Ue.init(t,e)}),GI=O("ZodIPv6",(t,e)=>{xd.init(t,e),Ue.init(t,e)}),JI=O("ZodCIDRv4",(t,e)=>{kd.init(t,e),Ue.init(t,e)}),YI=O("ZodCIDRv6",(t,e)=>{$d.init(t,e),Ue.init(t,e)}),XI=O("ZodBase64",(t,e)=>{Sd.init(t,e),Ue.init(t,e)}),QI=O("ZodBase64URL",(t,e)=>{Td.init(t,e),Ue.init(t,e)}),eO=O("ZodE164",(t,e)=>{Ed.init(t,e),Ue.init(t,e)}),tO=O("ZodJWT",(t,e)=>{Rd.init(t,e),Ue.init(t,e)}),p_=O("ZodNumber",(t,e)=>{Ea.init(t,e),Fe.init(t,e),t.gt=(n,o)=>t.check(Ca(n,o)),t.gte=(n,o)=>t.check(Os(n,o)),t.min=(n,o)=>t.check(Os(n,o)),t.lt=(n,o)=>t.check(Oa(n,o)),t.lte=(n,o)=>t.check(Is(n,o)),t.max=(n,o)=>t.check(Is(n,o)),t.int=n=>t.check(l_(n)),t.safe=n=>t.check(l_(n)),t.positive=n=>t.check(Ca(0,n)),t.nonnegative=n=>t.check(Os(0,n)),t.negative=n=>t.check(Oa(0,n)),t.nonpositive=n=>t.check(Is(0,n)),t.multipleOf=(n,o)=>t.check(Na(n,o)),t.step=(n,o)=>t.check(Na(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});rO=O("ZodNumberFormat",(t,e)=>{Pd.init(t,e),p_.init(t,e)});nO=O("ZodBoolean",(t,e)=>{Ad.init(t,e),Fe.init(t,e)});oO=O("ZodNull",(t,e)=>{Id.init(t,e),Fe.init(t,e)});sO=O("ZodUnknown",(t,e)=>{Od.init(t,e),Fe.init(t,e)});iO=O("ZodNever",(t,e)=>{Cd.init(t,e),Fe.init(t,e)});cO=O("ZodArray",(t,e)=>{Nd.init(t,e),Fe.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(ko(r,n)),t.nonempty=r=>t.check(ko(1,r)),t.max=(r,n)=>t.check(za(r,n)),t.length=(r,n)=>t.check(ja(r,n)),t.unwrap=()=>t.element});f_=O("ZodObject",(t,e)=>{Ra.init(t,e),Fe.init(t,e),we.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Et(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:qe()}),t.loose=()=>t.clone({...t._zod.def,catchall:qe()}),t.strict=()=>t.clone({...t._zod.def,catchall:aO()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>we.extend(t,r),t.merge=r=>we.merge(t,r),t.pick=r=>we.pick(t,r),t.omit=r=>we.omit(t,r),t.partial=(...r)=>we.partial(y_,t,r[0]),t.required=(...r)=>we.required(b_,t,r[0])});m_=O("ZodUnion",(t,e)=>{Pa.init(t,e),Fe.init(t,e),t.options=e.options});lO=O("ZodDiscriminatedUnion",(t,e)=>{m_.init(t,e),zd.init(t,e)});uO=O("ZodIntersection",(t,e)=>{jd.init(t,e),Fe.init(t,e)});dO=O("ZodRecord",(t,e)=>{Ld.init(t,e),Fe.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});Yp=O("ZodEnum",(t,e)=>{Dd.init(t,e),Fe.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Yp({...e,checks:[],...we.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Yp({...e,checks:[],...we.normalizeParams(o),entries:s})}});pO=O("ZodLiteral",(t,e)=>{Md.init(t,e),Fe.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});hO=O("ZodTransform",(t,e)=>{Ud.init(t,e),Fe.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(we.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(we.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});y_=O("ZodOptional",(t,e)=>{qd.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});fO=O("ZodNullable",(t,e)=>{Bd.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});mO=O("ZodDefault",(t,e)=>{Zd.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});yO=O("ZodPrefault",(t,e)=>{Fd.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});b_=O("ZodNonOptional",(t,e)=>{Hd.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});vO=O("ZodCatch",(t,e)=>{Vd.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});xO=O("ZodPipe",(t,e)=>{Kd.init(t,e),Fe.init(t,e),t.in=e.in,t.out=e.out});kO=O("ZodReadonly",(t,e)=>{Wd.init(t,e),Fe.init(t,e)});w_=O("ZodCustom",(t,e)=>{Gd.init(t,e),Fe.init(t,e)})});var __=C(()=>{});var x_=C(()=>{});var k_=C(()=>{gt();Wp();Bp();Gp();Jp();__();gt();Cv();Aa();Kp();x_();Ct(Ov())});var $_=C(()=>{k_()});var S_=C(()=>{$_()});function B_(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Z_(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var rh,T_,Qr,Za,Qe,E_,R_,k4,AO,IO,nh,zt,js,P_,st,Bt,Zt,it,Fa,A_,oh,I_,O_,sh,Ls,te,ih,C_,N_,$4,Ha,OO,Va,CO,Ds,To,z_,NO,zO,jO,LO,DO,MO,ah,UO,qO,ch,Ka,BO,ZO,Wa,FO,Ms,Us,HO,qs,Eo,VO,Bs,Ga,Ja,Ya,S4,Xa,Qa,ec,j_,L_,D_,lh,M_,Zs,Ro,U_,KO,tc,WO,rc,GO,uh,JO,nc,YO,XO,QO,eC,tC,rC,nC,oC,sC,iC,oc,aC,cC,sc,dh,ph,hh,lC,uC,dC,fh,pC,hC,fC,mC,gC,q_,ic,yC,ac,T4,bC,Po,wC,E4,Fs,vC,mh,_C,xC,kC,$C,SC,TC,EC,Ba,RC,PC,AC,Hs,gh,IC,OC,CC,NC,zC,jC,LC,DC,MC,UC,qC,BC,ZC,FC,HC,VC,KC,WC,Ao,GC,JC,YC,cc,XC,QC,eN,yh,tN,R4,P4,A4,I4,O4,C4,J,th,Io=C(()=>{S_();rh="2025-11-25",T_=[rh,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Qr="io.modelcontextprotocol/related-task",Za="2.0",Qe=v_(t=>t!==null&&(typeof t=="object"||typeof t=="function")),E_=je([I(),Re().int()]),R_=I(),k4=yt({ttl:Re().optional(),pollInterval:Re().optional()}),AO=K({ttl:Re().optional()}),IO=K({taskId:I()}),nh=yt({progressToken:E_.optional(),[Qr]:IO.optional()}),zt=K({_meta:nh.optional()}),js=zt.extend({task:AO.optional()}),P_=t=>js.safeParse(t).success,st=K({method:I(),params:zt.loose().optional()}),Bt=K({_meta:nh.optional()}),Zt=K({method:I(),params:Bt.loose().optional()}),it=yt({_meta:nh.optional()}),Fa=je([I(),Re().int()]),A_=K({jsonrpc:Y(Za),id:Fa,...st.shape}).strict(),oh=t=>A_.safeParse(t).success,I_=K({jsonrpc:Y(Za),...Zt.shape}).strict(),O_=t=>I_.safeParse(t).success,sh=K({jsonrpc:Y(Za),id:Fa,result:it}).strict(),Ls=t=>sh.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"})(te||(te={}));ih=K({jsonrpc:Y(Za),id:Fa.optional(),error:K({code:Re().int(),message:I(),data:qe().optional()})}).strict(),C_=t=>ih.safeParse(t).success,N_=je([A_,I_,sh,ih]),$4=je([sh,ih]),Ha=it.strict(),OO=Bt.extend({requestId:Fa.optional(),reason:I().optional()}),Va=Zt.extend({method:Y("notifications/cancelled"),params:OO}),CO=K({src:I(),mimeType:I().optional(),sizes:_e(I()).optional(),theme:Et(["light","dark"]).optional()}),Ds=K({icons:_e(CO).optional()}),To=K({name:I(),title:I().optional()}),z_=To.extend({...To.shape,...Ds.shape,version:I(),websiteUrl:I().optional(),description:I().optional()}),NO=qa(K({applyDefaults:rt().optional()}),ze(I(),qe())),zO=eh(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,qa(K({form:NO.optional(),url:Qe.optional()}),ze(I(),qe()).optional())),jO=yt({list:Qe.optional(),cancel:Qe.optional(),requests:yt({sampling:yt({createMessage:Qe.optional()}).optional(),elicitation:yt({create:Qe.optional()}).optional()}).optional()}),LO=yt({list:Qe.optional(),cancel:Qe.optional(),requests:yt({tools:yt({call:Qe.optional()}).optional()}).optional()}),DO=K({experimental:ze(I(),Qe).optional(),sampling:K({context:Qe.optional(),tools:Qe.optional()}).optional(),elicitation:zO.optional(),roots:K({listChanged:rt().optional()}).optional(),tasks:jO.optional(),extensions:ze(I(),Qe).optional()}),MO=zt.extend({protocolVersion:I(),capabilities:DO,clientInfo:z_}),ah=st.extend({method:Y("initialize"),params:MO}),UO=K({experimental:ze(I(),Qe).optional(),logging:Qe.optional(),completions:Qe.optional(),prompts:K({listChanged:rt().optional()}).optional(),resources:K({subscribe:rt().optional(),listChanged:rt().optional()}).optional(),tools:K({listChanged:rt().optional()}).optional(),tasks:LO.optional(),extensions:ze(I(),Qe).optional()}),qO=it.extend({protocolVersion:I(),capabilities:UO,serverInfo:z_,instructions:I().optional()}),ch=Zt.extend({method:Y("notifications/initialized"),params:Bt.optional()}),Ka=st.extend({method:Y("ping"),params:zt.optional()}),BO=K({progress:Re(),total:Be(Re()),message:Be(I())}),ZO=K({...Bt.shape,...BO.shape,progressToken:E_}),Wa=Zt.extend({method:Y("notifications/progress"),params:ZO}),FO=zt.extend({cursor:R_.optional()}),Ms=st.extend({params:FO.optional()}),Us=it.extend({nextCursor:R_.optional()}),HO=Et(["working","input_required","completed","failed","cancelled"]),qs=K({taskId:I(),status:HO,ttl:je([Re(),h_()]),createdAt:I(),lastUpdatedAt:I(),pollInterval:Be(Re()),statusMessage:Be(I())}),Eo=it.extend({task:qs}),VO=Bt.merge(qs),Bs=Zt.extend({method:Y("notifications/tasks/status"),params:VO}),Ga=st.extend({method:Y("tasks/get"),params:zt.extend({taskId:I()})}),Ja=it.merge(qs),Ya=st.extend({method:Y("tasks/result"),params:zt.extend({taskId:I()})}),S4=it.loose(),Xa=Ms.extend({method:Y("tasks/list")}),Qa=Us.extend({tasks:_e(qs)}),ec=st.extend({method:Y("tasks/cancel"),params:zt.extend({taskId:I()})}),j_=it.merge(qs),L_=K({uri:I(),mimeType:Be(I()),_meta:ze(I(),qe()).optional()}),D_=L_.extend({text:I()}),lh=I().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),M_=L_.extend({blob:lh}),Zs=Et(["user","assistant"]),Ro=K({audience:_e(Zs).optional(),priority:Re().min(0).max(1).optional(),lastModified:Ns.datetime({offset:!0}).optional()}),U_=K({...To.shape,...Ds.shape,uri:I(),description:Be(I()),mimeType:Be(I()),size:Be(Re()),annotations:Ro.optional(),_meta:Be(yt({}))}),KO=K({...To.shape,...Ds.shape,uriTemplate:I(),description:Be(I()),mimeType:Be(I()),annotations:Ro.optional(),_meta:Be(yt({}))}),tc=Ms.extend({method:Y("resources/list")}),WO=Us.extend({resources:_e(U_)}),rc=Ms.extend({method:Y("resources/templates/list")}),GO=Us.extend({resourceTemplates:_e(KO)}),uh=zt.extend({uri:I()}),JO=uh,nc=st.extend({method:Y("resources/read"),params:JO}),YO=it.extend({contents:_e(je([D_,M_]))}),XO=Zt.extend({method:Y("notifications/resources/list_changed"),params:Bt.optional()}),QO=uh,eC=st.extend({method:Y("resources/subscribe"),params:QO}),tC=uh,rC=st.extend({method:Y("resources/unsubscribe"),params:tC}),nC=Bt.extend({uri:I()}),oC=Zt.extend({method:Y("notifications/resources/updated"),params:nC}),sC=K({name:I(),description:Be(I()),required:Be(rt())}),iC=K({...To.shape,...Ds.shape,description:Be(I()),arguments:Be(_e(sC)),_meta:Be(yt({}))}),oc=Ms.extend({method:Y("prompts/list")}),aC=Us.extend({prompts:_e(iC)}),cC=zt.extend({name:I(),arguments:ze(I(),I()).optional()}),sc=st.extend({method:Y("prompts/get"),params:cC}),dh=K({type:Y("text"),text:I(),annotations:Ro.optional(),_meta:ze(I(),qe()).optional()}),ph=K({type:Y("image"),data:lh,mimeType:I(),annotations:Ro.optional(),_meta:ze(I(),qe()).optional()}),hh=K({type:Y("audio"),data:lh,mimeType:I(),annotations:Ro.optional(),_meta:ze(I(),qe()).optional()}),lC=K({type:Y("tool_use"),name:I(),id:I(),input:ze(I(),qe()),_meta:ze(I(),qe()).optional()}),uC=K({type:Y("resource"),resource:je([D_,M_]),annotations:Ro.optional(),_meta:ze(I(),qe()).optional()}),dC=U_.extend({type:Y("resource_link")}),fh=je([dh,ph,hh,dC,uC]),pC=K({role:Zs,content:fh}),hC=it.extend({description:I().optional(),messages:_e(pC)}),fC=Zt.extend({method:Y("notifications/prompts/list_changed"),params:Bt.optional()}),mC=K({title:I().optional(),readOnlyHint:rt().optional(),destructiveHint:rt().optional(),idempotentHint:rt().optional(),openWorldHint:rt().optional()}),gC=K({taskSupport:Et(["required","optional","forbidden"]).optional()}),q_=K({...To.shape,...Ds.shape,description:I().optional(),inputSchema:K({type:Y("object"),properties:ze(I(),Qe).optional(),required:_e(I()).optional()}).catchall(qe()),outputSchema:K({type:Y("object"),properties:ze(I(),Qe).optional(),required:_e(I()).optional()}).catchall(qe()).optional(),annotations:mC.optional(),execution:gC.optional(),_meta:ze(I(),qe()).optional()}),ic=Ms.extend({method:Y("tools/list")}),yC=Us.extend({tools:_e(q_)}),ac=it.extend({content:_e(fh).default([]),structuredContent:ze(I(),qe()).optional(),isError:rt().optional()}),T4=ac.or(it.extend({toolResult:qe()})),bC=js.extend({name:I(),arguments:ze(I(),qe()).optional()}),Po=st.extend({method:Y("tools/call"),params:bC}),wC=Zt.extend({method:Y("notifications/tools/list_changed"),params:Bt.optional()}),E4=K({autoRefresh:rt().default(!0),debounceMs:Re().int().nonnegative().default(300)}),Fs=Et(["debug","info","notice","warning","error","critical","alert","emergency"]),vC=zt.extend({level:Fs}),mh=st.extend({method:Y("logging/setLevel"),params:vC}),_C=Bt.extend({level:Fs,logger:I().optional(),data:qe()}),xC=Zt.extend({method:Y("notifications/message"),params:_C}),kC=K({name:I().optional()}),$C=K({hints:_e(kC).optional(),costPriority:Re().min(0).max(1).optional(),speedPriority:Re().min(0).max(1).optional(),intelligencePriority:Re().min(0).max(1).optional()}),SC=K({mode:Et(["auto","required","none"]).optional()}),TC=K({type:Y("tool_result"),toolUseId:I().describe("The unique identifier for the corresponding tool call."),content:_e(fh).default([]),structuredContent:K({}).loose().optional(),isError:rt().optional(),_meta:ze(I(),qe()).optional()}),EC=Qp("type",[dh,ph,hh]),Ba=Qp("type",[dh,ph,hh,lC,TC]),RC=K({role:Zs,content:je([Ba,_e(Ba)]),_meta:ze(I(),qe()).optional()}),PC=js.extend({messages:_e(RC),modelPreferences:$C.optional(),systemPrompt:I().optional(),includeContext:Et(["none","thisServer","allServers"]).optional(),temperature:Re().optional(),maxTokens:Re().int(),stopSequences:_e(I()).optional(),metadata:Qe.optional(),tools:_e(q_).optional(),toolChoice:SC.optional()}),AC=st.extend({method:Y("sampling/createMessage"),params:PC}),Hs=it.extend({model:I(),stopReason:Be(Et(["endTurn","stopSequence","maxTokens"]).or(I())),role:Zs,content:EC}),gh=it.extend({model:I(),stopReason:Be(Et(["endTurn","stopSequence","maxTokens","toolUse"]).or(I())),role:Zs,content:je([Ba,_e(Ba)])}),IC=K({type:Y("boolean"),title:I().optional(),description:I().optional(),default:rt().optional()}),OC=K({type:Y("string"),title:I().optional(),description:I().optional(),minLength:Re().optional(),maxLength:Re().optional(),format:Et(["email","uri","date","date-time"]).optional(),default:I().optional()}),CC=K({type:Et(["number","integer"]),title:I().optional(),description:I().optional(),minimum:Re().optional(),maximum:Re().optional(),default:Re().optional()}),NC=K({type:Y("string"),title:I().optional(),description:I().optional(),enum:_e(I()),default:I().optional()}),zC=K({type:Y("string"),title:I().optional(),description:I().optional(),oneOf:_e(K({const:I(),title:I()})),default:I().optional()}),jC=K({type:Y("string"),title:I().optional(),description:I().optional(),enum:_e(I()),enumNames:_e(I()).optional(),default:I().optional()}),LC=je([NC,zC]),DC=K({type:Y("array"),title:I().optional(),description:I().optional(),minItems:Re().optional(),maxItems:Re().optional(),items:K({type:Y("string"),enum:_e(I())}),default:_e(I()).optional()}),MC=K({type:Y("array"),title:I().optional(),description:I().optional(),minItems:Re().optional(),maxItems:Re().optional(),items:K({anyOf:_e(K({const:I(),title:I()}))}),default:_e(I()).optional()}),UC=je([DC,MC]),qC=je([jC,LC,UC]),BC=je([qC,IC,OC,CC]),ZC=js.extend({mode:Y("form").optional(),message:I(),requestedSchema:K({type:Y("object"),properties:ze(I(),BC),required:_e(I()).optional()})}),FC=js.extend({mode:Y("url"),message:I(),elicitationId:I(),url:I().url()}),HC=je([ZC,FC]),VC=st.extend({method:Y("elicitation/create"),params:HC}),KC=Bt.extend({elicitationId:I()}),WC=Zt.extend({method:Y("notifications/elicitation/complete"),params:KC}),Ao=it.extend({action:Et(["accept","decline","cancel"]),content:eh(t=>t===null?void 0:t,ze(I(),je([I(),Re(),rt(),_e(I())])).optional())}),GC=K({type:Y("ref/resource"),uri:I()}),JC=K({type:Y("ref/prompt"),name:I()}),YC=zt.extend({ref:je([JC,GC]),argument:K({name:I(),value:I()}),context:K({arguments:ze(I(),I()).optional()}).optional()}),cc=st.extend({method:Y("completion/complete"),params:YC});XC=it.extend({completion:yt({values:_e(I()).max(100),total:Be(Re().int()),hasMore:Be(rt())})}),QC=K({uri:I().startsWith("file://"),name:I().optional(),_meta:ze(I(),qe()).optional()}),eN=st.extend({method:Y("roots/list"),params:zt.optional()}),yh=it.extend({roots:_e(QC)}),tN=Zt.extend({method:Y("notifications/roots/list_changed"),params:Bt.optional()}),R4=je([Ka,ah,cc,mh,sc,oc,tc,rc,nc,eC,rC,Po,ic,Ga,Ya,Xa,ec]),P4=je([Va,Wa,ch,tN,Bs]),A4=je([Ha,Hs,gh,Ao,yh,Ja,Qa,Eo]),I4=je([Ka,AC,VC,eN,Ga,Ya,Xa,ec]),O4=je([Va,Wa,xC,oC,XO,wC,fC,Bs,WC]),C4=je([Ha,qO,XC,hC,aC,WO,GO,YO,ac,yC,Ja,Qa,Eo]),J=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===te.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new th(o.elicitations,r)}return new t(e,r,n)}},th=class extends J{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(te.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function en(t){return t==="completed"||t==="failed"||t==="cancelled"}var F_=C(()=>{});var V_,H_,K_,lc=C(()=>{V_=Symbol("Let zodToJsonSchema decide on which parser to use"),H_={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"},K_=t=>typeof t=="string"?{...H_,name:t}:{...H_,...t}});var W_,bh=C(()=>{lc();W_=t=>{let e=K_(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 wh(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function xe(t,e,r,n,o){t[e]=r,wh(t,e,n,o)}var tn=C(()=>{});var uc,dc=C(()=>{uc=(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 Ze(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?uc(e,t.currentPath):e.join("/")}}var Ft=C(()=>{dc()});function G_(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==U.ZodAny&&(r.items=ie(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&xe(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&xe(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(xe(r,"minItems",t.exactLength.value,t.exactLength.message,e),xe(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var vh=C(()=>{vs();tn();Je()});function J_(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?xe(r,"minimum",n.value,n.message,e):xe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),xe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?xe(r,"maximum",n.value,n.message,e):xe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),xe(r,"maximum",n.value,n.message,e));break;case"multipleOf":xe(r,"multipleOf",n.value,n.message,e);break}return r}var _h=C(()=>{tn()});function Y_(){return{type:"boolean"}}var xh=C(()=>{});function pc(t,e){return ie(t.type._def,e)}var hc=C(()=>{Je()});var X_,kh=C(()=>{Je();X_=(t,e)=>ie(t.innerType._def,e)});function $h(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>$h(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 rN(t,e)}}var rN,Sh=C(()=>{tn();rN=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":xe(r,"minimum",n.value,n.message,e);break;case"max":xe(r,"maximum",n.value,n.message,e);break}return r}});function Q_(t,e){return{...ie(t.innerType._def,e),default:t.defaultValue()}}var Th=C(()=>{Je()});function ex(t,e){return e.effectStrategy==="input"?ie(t.schema._def,e):Ze(e)}var Eh=C(()=>{Je();Ft()});function tx(t){return{type:"string",enum:Array.from(t.values)}}var Rh=C(()=>{});function rx(t,e){let r=[ie(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),ie(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(nN(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 nN,Ph=C(()=>{Je();nN=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function nx(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 Ah=C(()=>{});function fc(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":xe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":xe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":nr(r,"email",n.message,e);break;case"format:idn-email":nr(r,"idn-email",n.message,e);break;case"pattern:zod":bt(r,rr.email,n.message,e);break}break;case"url":nr(r,"uri",n.message,e);break;case"uuid":nr(r,"uuid",n.message,e);break;case"regex":bt(r,n.regex,n.message,e);break;case"cuid":bt(r,rr.cuid,n.message,e);break;case"cuid2":bt(r,rr.cuid2,n.message,e);break;case"startsWith":bt(r,RegExp(`^${Oh(n.value,e)}`),n.message,e);break;case"endsWith":bt(r,RegExp(`${Oh(n.value,e)}$`),n.message,e);break;case"datetime":nr(r,"date-time",n.message,e);break;case"date":nr(r,"date",n.message,e);break;case"time":nr(r,"time",n.message,e);break;case"duration":nr(r,"duration",n.message,e);break;case"length":xe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),xe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{bt(r,RegExp(Oh(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&nr(r,"ipv4",n.message,e),n.version!=="v4"&&nr(r,"ipv6",n.message,e);break}case"base64url":bt(r,rr.base64url,n.message,e);break;case"jwt":bt(r,rr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&bt(r,rr.ipv4Cidr,n.message,e),n.version!=="v4"&&bt(r,rr.ipv6Cidr,n.message,e);break}case"emoji":bt(r,rr.emoji(),n.message,e);break;case"ulid":{bt(r,rr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{nr(r,"binary",n.message,e);break}case"contentEncoding:base64":{xe(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{bt(r,rr.base64,n.message,e);break}}break}case"nanoid":bt(r,rr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Oh(t,e){return e.patternStrategy==="escape"?sN(t):t}function sN(t){let e="";for(let r=0;r<t.length;r++)oN.has(t[r])||(e+="\\"),e+=t[r];return e}function nr(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):xe(t,"format",e,r,n)}function 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:ox(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):xe(t,"pattern",ox(e,n),r,n)}function ox(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
2035
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let u of this.seen.entries()){let p=u[1];if(e===u[0]){i(u);continue}if(n.external){let f=n.external.registry.get(u[0])?.id;if(e!==u[0]&&f){i(u);continue}}if(this.metadataRegistry.get(u[0])?.id){i(u);continue}if(p.cycle){i(u);continue}if(p.count>1&&n.reused==="ref"){i(u);continue}}let a=(u,p)=>{let w=this.seen.get(u),f=w.def??w.schema,h={...f};if(w.ref===null)return;let b=w.ref;if(w.ref=null,b){a(b,p);let $=this.seen.get(b).schema;$.$ref&&p.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push($)):(Object.assign(f,$),Object.assign(f,h))}w.isParent||this.override({zodSchema:u,jsonSchema:f,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 p=u[1];p.def&&p.defId&&(l[p.defId]=p.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 Vv=C(()=>{});var gt=C(()=>{vo();od();Yu();Nv();Ta();ud();gr();Sa();Oa();Qd();ld();Fv();Zv();Hv();Vv()});var qp=C(()=>{gt()});function Bp(t,e){let r={type:"object",get shape(){return we.assignProp(this,"shape",{...t}),this.shape},...we.normalizeParams(e)};return new CI(r)}var OI,CI,Kv=C(()=>{gt();gt();qp();OI=O("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");Ae.init(t,e),t.def=e,t.parse=(r,n)=>Qu(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>jn(t,r,n),t.parseAsync=async(r,n)=>td(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Ln(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)=>Nt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),CI=O("ZodMiniObject",(t,e)=>{Aa.init(t,e),OI.init(t,e),we.defineLazy(t,"shape",()=>e.shape)})});var Wv=C(()=>{});var Gv=C(()=>{});var Jv=C(()=>{});var Yv=C(()=>{gt();qp();Kv();Wv();gt();Oa();Gv();Jv()});var Xv=C(()=>{Yv()});var Zp=C(()=>{Xv()});function yr(t){return!!t._zod}function Un(t){let e=Object.values(t);if(e.length===0)return Bp({});let r=e.every(yr),n=e.every(o=>!yr(o));if(r)return Bp(t);if(n)return Ll(t);throw new Error("Mixed Zod versions detected in object shape.")}function Yr(t,e){return yr(t)?jn(t,e):t.safeParse(e)}async function Ua(t,e){return yr(t)?await Ln(t,e):await t.safeParseAsync(e)}function Xr(t){if(!t)return;let e;if(yr(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function $o(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 Un(t)}}if(yr(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 jI(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function qa(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 ${jI(e.path)}`:e.message).join(`
2036
+ `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function e_(t){return t.description}function t_(t){if(yr(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function So(t){if(yr(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 Cs=C(()=>{vs();Zp()});var Fp=C(()=>{gt()});var Ns={};Yo(Ns,{ZodISODate:()=>n_,ZodISODateTime:()=>r_,ZodISODuration:()=>s_,ZodISOTime:()=>o_,date:()=>Vp,datetime:()=>Hp,duration:()=>Wp,time:()=>Kp});function Hp(t){return Dv(r_,t)}function Vp(t){return Mv(n_,t)}function Kp(t){return Uv(o_,t)}function Wp(t){return qv(s_,t)}var r_,n_,o_,s_,Gp=C(()=>{gt();Jp();r_=O("ZodISODateTime",(t,e)=>{Pv.init(t,e),Ue.init(t,e)});n_=O("ZodISODate",(t,e)=>{Av.init(t,e),Ue.init(t,e)});o_=O("ZodISOTime",(t,e)=>{Iv.init(t,e),Ue.init(t,e)});s_=O("ZodISODuration",(t,e)=>{Ov.init(t,e),Ue.init(t,e)})});var i_,h4,zs,Yp=C(()=>{gt();gt();i_=(t,e)=>{ka.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Ju(t,r)},flatten:{value:r=>Gu(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},h4=O("ZodError",i_),zs=O("ZodError",i_,{Parent:Error})});var a_,c_,l_,u_,Xp=C(()=>{gt();Yp();a_=Xu(zs),c_=ed(zs),l_=rd(zs),u_=nd(zs)});function I(t){return ep(FI,t)}function Re(t){return xp(m_,t)}function p_(t){return kp(cO,t)}function rt(t){return $p(lO,t)}function g_(t){return Sp(uO,t)}function qe(){return Tp(dO)}function hO(t){return Ep(pO,t)}function _e(t,e){return Bv(fO,t,e)}function K(t,e){let r={type:"object",get shape(){return we.assignProp(this,"shape",{...t}),this.shape},...we.normalizeParams(e)};return new y_(r)}function yt(t,e){return new y_({type:"object",get shape(){return we.assignProp(this,"shape",{...t}),this.shape},catchall:qe(),...we.normalizeParams(e)})}function je(t,e){return new b_({type:"union",options:t,...we.normalizeParams(e)})}function th(t,e,r){return new mO({type:"union",options:e,discriminator:t,...we.normalizeParams(r)})}function Za(t,e){return new gO({type:"intersection",left:t,right:e})}function ze(t,e,r){return new yO({type:"record",keyType:t,valueType:e,...we.normalizeParams(r)})}function Et(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Qp({type:"enum",entries:r,...we.normalizeParams(e)})}function Y(t,e){return new bO({type:"literal",values:Array.isArray(t)?t:[t],...we.normalizeParams(e)})}function w_(t){return new wO({type:"transform",transform:t})}function Be(t){return new v_({type:"optional",innerType:t})}function h_(t){return new vO({type:"nullable",innerType:t})}function xO(t,e){return new _O({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function $O(t,e){return new kO({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function SO(t,e){return new __({type:"nonoptional",innerType:t,...we.normalizeParams(e)})}function EO(t,e){return new TO({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function eh(t,e){return new RO({type:"pipe",in:t,out:e})}function AO(t){return new PO({type:"readonly",innerType:t})}function IO(t){let e=new ot({check:"custom"});return e._zod.check=t,e}function k_(t,e){return Dp(x_,t??(()=>!0),e)}function OO(t,e={}){return Mp(x_,t,e)}function CO(t){let e=IO(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(we.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(we.issue(o))}},t(r.value,r)));return e}function rh(t,e){return eh(w_(t),e)}var Fe,f_,FI,Ue,HI,d_,Ba,VI,KI,WI,GI,JI,YI,XI,QI,eO,tO,rO,nO,oO,sO,iO,aO,m_,cO,lO,uO,dO,pO,fO,y_,b_,mO,gO,yO,Qp,bO,wO,v_,vO,_O,kO,__,TO,RO,PO,x_,Jp=C(()=>{gt();gt();Fp();Gp();Xp();Fe=O("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)=>Nt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>a_(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>l_(t,r,n),t.parseAsync=async(r,n)=>c_(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>u_(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(OO(r,n)),t.superRefine=r=>t.check(CO(r)),t.overwrite=r=>t.check(Dn(r)),t.optional=()=>Be(t),t.nullable=()=>h_(t),t.nullish=()=>Be(h_(t)),t.nonoptional=r=>SO(t,r),t.array=()=>_e(t),t.or=r=>je([t,r]),t.and=r=>Za(t,r),t.transform=r=>eh(t,w_(r)),t.default=r=>xO(t,r),t.prefault=r=>$O(t,r),t.catch=r=>EO(t,r),t.pipe=r=>eh(t,r),t.readonly=()=>AO(t),t.describe=r=>{let n=t.clone();return Jr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Jr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Jr.get(t);let n=t.clone();return Jr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),f_=O("_ZodString",(t,e)=>{Ps.init(t,e),Fe.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Rp(...n)),t.includes=(...n)=>t.check(Ip(...n)),t.startsWith=(...n)=>t.check(Op(...n)),t.endsWith=(...n)=>t.check(Cp(...n)),t.min=(...n)=>t.check(ko(...n)),t.max=(...n)=>t.check(La(...n)),t.length=(...n)=>t.check(Da(...n)),t.nonempty=(...n)=>t.check(ko(1,...n)),t.lowercase=n=>t.check(Pp(n)),t.uppercase=n=>t.check(Ap(n)),t.trim=()=>t.check(zp()),t.normalize=(...n)=>t.check(Np(...n)),t.toLowerCase=()=>t.check(jp()),t.toUpperCase=()=>t.check(Lp())}),FI=O("ZodString",(t,e)=>{Ps.init(t,e),f_.init(t,e),t.email=r=>t.check(tp(HI,r)),t.url=r=>t.check(ip(VI,r)),t.jwt=r=>t.check(_p(aO,r)),t.emoji=r=>t.check(ap(KI,r)),t.guid=r=>t.check(Ca(d_,r)),t.uuid=r=>t.check(rp(Ba,r)),t.uuidv4=r=>t.check(np(Ba,r)),t.uuidv6=r=>t.check(op(Ba,r)),t.uuidv7=r=>t.check(sp(Ba,r)),t.nanoid=r=>t.check(cp(WI,r)),t.guid=r=>t.check(Ca(d_,r)),t.cuid=r=>t.check(lp(GI,r)),t.cuid2=r=>t.check(up(JI,r)),t.ulid=r=>t.check(dp(YI,r)),t.base64=r=>t.check(bp(oO,r)),t.base64url=r=>t.check(wp(sO,r)),t.xid=r=>t.check(pp(XI,r)),t.ksuid=r=>t.check(hp(QI,r)),t.ipv4=r=>t.check(fp(eO,r)),t.ipv6=r=>t.check(mp(tO,r)),t.cidrv4=r=>t.check(gp(rO,r)),t.cidrv6=r=>t.check(yp(nO,r)),t.e164=r=>t.check(vp(iO,r)),t.datetime=r=>t.check(Hp(r)),t.date=r=>t.check(Vp(r)),t.time=r=>t.check(Kp(r)),t.duration=r=>t.check(Wp(r))});Ue=O("ZodStringFormat",(t,e)=>{Ne.init(t,e),f_.init(t,e)}),HI=O("ZodEmail",(t,e)=>{fd.init(t,e),Ue.init(t,e)}),d_=O("ZodGUID",(t,e)=>{pd.init(t,e),Ue.init(t,e)}),Ba=O("ZodUUID",(t,e)=>{hd.init(t,e),Ue.init(t,e)}),VI=O("ZodURL",(t,e)=>{md.init(t,e),Ue.init(t,e)}),KI=O("ZodEmoji",(t,e)=>{gd.init(t,e),Ue.init(t,e)}),WI=O("ZodNanoID",(t,e)=>{yd.init(t,e),Ue.init(t,e)}),GI=O("ZodCUID",(t,e)=>{bd.init(t,e),Ue.init(t,e)}),JI=O("ZodCUID2",(t,e)=>{wd.init(t,e),Ue.init(t,e)}),YI=O("ZodULID",(t,e)=>{vd.init(t,e),Ue.init(t,e)}),XI=O("ZodXID",(t,e)=>{_d.init(t,e),Ue.init(t,e)}),QI=O("ZodKSUID",(t,e)=>{xd.init(t,e),Ue.init(t,e)}),eO=O("ZodIPv4",(t,e)=>{kd.init(t,e),Ue.init(t,e)}),tO=O("ZodIPv6",(t,e)=>{$d.init(t,e),Ue.init(t,e)}),rO=O("ZodCIDRv4",(t,e)=>{Sd.init(t,e),Ue.init(t,e)}),nO=O("ZodCIDRv6",(t,e)=>{Td.init(t,e),Ue.init(t,e)}),oO=O("ZodBase64",(t,e)=>{Ed.init(t,e),Ue.init(t,e)}),sO=O("ZodBase64URL",(t,e)=>{Rd.init(t,e),Ue.init(t,e)}),iO=O("ZodE164",(t,e)=>{Pd.init(t,e),Ue.init(t,e)}),aO=O("ZodJWT",(t,e)=>{Ad.init(t,e),Ue.init(t,e)}),m_=O("ZodNumber",(t,e)=>{Pa.init(t,e),Fe.init(t,e),t.gt=(n,o)=>t.check(za(n,o)),t.gte=(n,o)=>t.check(Os(n,o)),t.min=(n,o)=>t.check(Os(n,o)),t.lt=(n,o)=>t.check(Na(n,o)),t.lte=(n,o)=>t.check(Is(n,o)),t.max=(n,o)=>t.check(Is(n,o)),t.int=n=>t.check(p_(n)),t.safe=n=>t.check(p_(n)),t.positive=n=>t.check(za(0,n)),t.nonnegative=n=>t.check(Os(0,n)),t.negative=n=>t.check(Na(0,n)),t.nonpositive=n=>t.check(Is(0,n)),t.multipleOf=(n,o)=>t.check(ja(n,o)),t.step=(n,o)=>t.check(ja(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});cO=O("ZodNumberFormat",(t,e)=>{Id.init(t,e),m_.init(t,e)});lO=O("ZodBoolean",(t,e)=>{Od.init(t,e),Fe.init(t,e)});uO=O("ZodNull",(t,e)=>{Cd.init(t,e),Fe.init(t,e)});dO=O("ZodUnknown",(t,e)=>{Nd.init(t,e),Fe.init(t,e)});pO=O("ZodNever",(t,e)=>{zd.init(t,e),Fe.init(t,e)});fO=O("ZodArray",(t,e)=>{jd.init(t,e),Fe.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(ko(r,n)),t.nonempty=r=>t.check(ko(1,r)),t.max=(r,n)=>t.check(La(r,n)),t.length=(r,n)=>t.check(Da(r,n)),t.unwrap=()=>t.element});y_=O("ZodObject",(t,e)=>{Aa.init(t,e),Fe.init(t,e),we.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Et(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:qe()}),t.loose=()=>t.clone({...t._zod.def,catchall:qe()}),t.strict=()=>t.clone({...t._zod.def,catchall:hO()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>we.extend(t,r),t.merge=r=>we.merge(t,r),t.pick=r=>we.pick(t,r),t.omit=r=>we.omit(t,r),t.partial=(...r)=>we.partial(v_,t,r[0]),t.required=(...r)=>we.required(__,t,r[0])});b_=O("ZodUnion",(t,e)=>{Ia.init(t,e),Fe.init(t,e),t.options=e.options});mO=O("ZodDiscriminatedUnion",(t,e)=>{b_.init(t,e),Ld.init(t,e)});gO=O("ZodIntersection",(t,e)=>{Dd.init(t,e),Fe.init(t,e)});yO=O("ZodRecord",(t,e)=>{Md.init(t,e),Fe.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});Qp=O("ZodEnum",(t,e)=>{Ud.init(t,e),Fe.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Qp({...e,checks:[],...we.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Qp({...e,checks:[],...we.normalizeParams(o),entries:s})}});bO=O("ZodLiteral",(t,e)=>{qd.init(t,e),Fe.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});wO=O("ZodTransform",(t,e)=>{Bd.init(t,e),Fe.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(we.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(we.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});v_=O("ZodOptional",(t,e)=>{Zd.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});vO=O("ZodNullable",(t,e)=>{Fd.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});_O=O("ZodDefault",(t,e)=>{Hd.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});kO=O("ZodPrefault",(t,e)=>{Vd.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});__=O("ZodNonOptional",(t,e)=>{Kd.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});TO=O("ZodCatch",(t,e)=>{Wd.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});RO=O("ZodPipe",(t,e)=>{Gd.init(t,e),Fe.init(t,e),t.in=e.in,t.out=e.out});PO=O("ZodReadonly",(t,e)=>{Jd.init(t,e),Fe.init(t,e)});x_=O("ZodCustom",(t,e)=>{Yd.init(t,e),Fe.init(t,e)})});var $_=C(()=>{});var S_=C(()=>{});var T_=C(()=>{gt();Jp();Fp();Yp();Xp();$_();gt();jv();Oa();Gp();S_();Ct(zv())});var E_=C(()=>{T_()});var R_=C(()=>{E_()});function H_(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function V_(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var oh,P_,Qr,Ha,Qe,A_,I_,P4,jO,LO,sh,zt,js,O_,st,Bt,Zt,it,Va,C_,ih,N_,z_,ah,Ls,te,ch,j_,L_,A4,Ka,DO,Wa,MO,Ds,To,D_,UO,qO,BO,ZO,FO,HO,lh,VO,KO,uh,Ga,WO,GO,Ja,JO,Ms,Us,YO,qs,Eo,XO,Bs,Ya,Xa,Qa,I4,ec,tc,rc,M_,U_,q_,dh,B_,Zs,Ro,Z_,QO,nc,eC,oc,tC,ph,rC,sc,nC,oC,sC,iC,aC,cC,lC,uC,dC,pC,ic,hC,fC,ac,hh,fh,mh,mC,gC,yC,gh,bC,wC,vC,_C,xC,F_,cc,kC,lc,O4,$C,Po,SC,C4,Fs,TC,yh,EC,RC,PC,AC,IC,OC,CC,Fa,NC,zC,jC,Hs,bh,LC,DC,MC,UC,qC,BC,ZC,FC,HC,VC,KC,WC,GC,JC,YC,XC,QC,eN,Ao,tN,rN,nN,uc,oN,sN,iN,wh,aN,N4,z4,j4,L4,D4,M4,J,nh,Io=C(()=>{R_();oh="2025-11-25",P_=[oh,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Qr="io.modelcontextprotocol/related-task",Ha="2.0",Qe=k_(t=>t!==null&&(typeof t=="object"||typeof t=="function")),A_=je([I(),Re().int()]),I_=I(),P4=yt({ttl:Re().optional(),pollInterval:Re().optional()}),jO=K({ttl:Re().optional()}),LO=K({taskId:I()}),sh=yt({progressToken:A_.optional(),[Qr]:LO.optional()}),zt=K({_meta:sh.optional()}),js=zt.extend({task:jO.optional()}),O_=t=>js.safeParse(t).success,st=K({method:I(),params:zt.loose().optional()}),Bt=K({_meta:sh.optional()}),Zt=K({method:I(),params:Bt.loose().optional()}),it=yt({_meta:sh.optional()}),Va=je([I(),Re().int()]),C_=K({jsonrpc:Y(Ha),id:Va,...st.shape}).strict(),ih=t=>C_.safeParse(t).success,N_=K({jsonrpc:Y(Ha),...Zt.shape}).strict(),z_=t=>N_.safeParse(t).success,ah=K({jsonrpc:Y(Ha),id:Va,result:it}).strict(),Ls=t=>ah.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"})(te||(te={}));ch=K({jsonrpc:Y(Ha),id:Va.optional(),error:K({code:Re().int(),message:I(),data:qe().optional()})}).strict(),j_=t=>ch.safeParse(t).success,L_=je([C_,N_,ah,ch]),A4=je([ah,ch]),Ka=it.strict(),DO=Bt.extend({requestId:Va.optional(),reason:I().optional()}),Wa=Zt.extend({method:Y("notifications/cancelled"),params:DO}),MO=K({src:I(),mimeType:I().optional(),sizes:_e(I()).optional(),theme:Et(["light","dark"]).optional()}),Ds=K({icons:_e(MO).optional()}),To=K({name:I(),title:I().optional()}),D_=To.extend({...To.shape,...Ds.shape,version:I(),websiteUrl:I().optional(),description:I().optional()}),UO=Za(K({applyDefaults:rt().optional()}),ze(I(),qe())),qO=rh(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Za(K({form:UO.optional(),url:Qe.optional()}),ze(I(),qe()).optional())),BO=yt({list:Qe.optional(),cancel:Qe.optional(),requests:yt({sampling:yt({createMessage:Qe.optional()}).optional(),elicitation:yt({create:Qe.optional()}).optional()}).optional()}),ZO=yt({list:Qe.optional(),cancel:Qe.optional(),requests:yt({tools:yt({call:Qe.optional()}).optional()}).optional()}),FO=K({experimental:ze(I(),Qe).optional(),sampling:K({context:Qe.optional(),tools:Qe.optional()}).optional(),elicitation:qO.optional(),roots:K({listChanged:rt().optional()}).optional(),tasks:BO.optional(),extensions:ze(I(),Qe).optional()}),HO=zt.extend({protocolVersion:I(),capabilities:FO,clientInfo:D_}),lh=st.extend({method:Y("initialize"),params:HO}),VO=K({experimental:ze(I(),Qe).optional(),logging:Qe.optional(),completions:Qe.optional(),prompts:K({listChanged:rt().optional()}).optional(),resources:K({subscribe:rt().optional(),listChanged:rt().optional()}).optional(),tools:K({listChanged:rt().optional()}).optional(),tasks:ZO.optional(),extensions:ze(I(),Qe).optional()}),KO=it.extend({protocolVersion:I(),capabilities:VO,serverInfo:D_,instructions:I().optional()}),uh=Zt.extend({method:Y("notifications/initialized"),params:Bt.optional()}),Ga=st.extend({method:Y("ping"),params:zt.optional()}),WO=K({progress:Re(),total:Be(Re()),message:Be(I())}),GO=K({...Bt.shape,...WO.shape,progressToken:A_}),Ja=Zt.extend({method:Y("notifications/progress"),params:GO}),JO=zt.extend({cursor:I_.optional()}),Ms=st.extend({params:JO.optional()}),Us=it.extend({nextCursor:I_.optional()}),YO=Et(["working","input_required","completed","failed","cancelled"]),qs=K({taskId:I(),status:YO,ttl:je([Re(),g_()]),createdAt:I(),lastUpdatedAt:I(),pollInterval:Be(Re()),statusMessage:Be(I())}),Eo=it.extend({task:qs}),XO=Bt.merge(qs),Bs=Zt.extend({method:Y("notifications/tasks/status"),params:XO}),Ya=st.extend({method:Y("tasks/get"),params:zt.extend({taskId:I()})}),Xa=it.merge(qs),Qa=st.extend({method:Y("tasks/result"),params:zt.extend({taskId:I()})}),I4=it.loose(),ec=Ms.extend({method:Y("tasks/list")}),tc=Us.extend({tasks:_e(qs)}),rc=st.extend({method:Y("tasks/cancel"),params:zt.extend({taskId:I()})}),M_=it.merge(qs),U_=K({uri:I(),mimeType:Be(I()),_meta:ze(I(),qe()).optional()}),q_=U_.extend({text:I()}),dh=I().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),B_=U_.extend({blob:dh}),Zs=Et(["user","assistant"]),Ro=K({audience:_e(Zs).optional(),priority:Re().min(0).max(1).optional(),lastModified:Ns.datetime({offset:!0}).optional()}),Z_=K({...To.shape,...Ds.shape,uri:I(),description:Be(I()),mimeType:Be(I()),size:Be(Re()),annotations:Ro.optional(),_meta:Be(yt({}))}),QO=K({...To.shape,...Ds.shape,uriTemplate:I(),description:Be(I()),mimeType:Be(I()),annotations:Ro.optional(),_meta:Be(yt({}))}),nc=Ms.extend({method:Y("resources/list")}),eC=Us.extend({resources:_e(Z_)}),oc=Ms.extend({method:Y("resources/templates/list")}),tC=Us.extend({resourceTemplates:_e(QO)}),ph=zt.extend({uri:I()}),rC=ph,sc=st.extend({method:Y("resources/read"),params:rC}),nC=it.extend({contents:_e(je([q_,B_]))}),oC=Zt.extend({method:Y("notifications/resources/list_changed"),params:Bt.optional()}),sC=ph,iC=st.extend({method:Y("resources/subscribe"),params:sC}),aC=ph,cC=st.extend({method:Y("resources/unsubscribe"),params:aC}),lC=Bt.extend({uri:I()}),uC=Zt.extend({method:Y("notifications/resources/updated"),params:lC}),dC=K({name:I(),description:Be(I()),required:Be(rt())}),pC=K({...To.shape,...Ds.shape,description:Be(I()),arguments:Be(_e(dC)),_meta:Be(yt({}))}),ic=Ms.extend({method:Y("prompts/list")}),hC=Us.extend({prompts:_e(pC)}),fC=zt.extend({name:I(),arguments:ze(I(),I()).optional()}),ac=st.extend({method:Y("prompts/get"),params:fC}),hh=K({type:Y("text"),text:I(),annotations:Ro.optional(),_meta:ze(I(),qe()).optional()}),fh=K({type:Y("image"),data:dh,mimeType:I(),annotations:Ro.optional(),_meta:ze(I(),qe()).optional()}),mh=K({type:Y("audio"),data:dh,mimeType:I(),annotations:Ro.optional(),_meta:ze(I(),qe()).optional()}),mC=K({type:Y("tool_use"),name:I(),id:I(),input:ze(I(),qe()),_meta:ze(I(),qe()).optional()}),gC=K({type:Y("resource"),resource:je([q_,B_]),annotations:Ro.optional(),_meta:ze(I(),qe()).optional()}),yC=Z_.extend({type:Y("resource_link")}),gh=je([hh,fh,mh,yC,gC]),bC=K({role:Zs,content:gh}),wC=it.extend({description:I().optional(),messages:_e(bC)}),vC=Zt.extend({method:Y("notifications/prompts/list_changed"),params:Bt.optional()}),_C=K({title:I().optional(),readOnlyHint:rt().optional(),destructiveHint:rt().optional(),idempotentHint:rt().optional(),openWorldHint:rt().optional()}),xC=K({taskSupport:Et(["required","optional","forbidden"]).optional()}),F_=K({...To.shape,...Ds.shape,description:I().optional(),inputSchema:K({type:Y("object"),properties:ze(I(),Qe).optional(),required:_e(I()).optional()}).catchall(qe()),outputSchema:K({type:Y("object"),properties:ze(I(),Qe).optional(),required:_e(I()).optional()}).catchall(qe()).optional(),annotations:_C.optional(),execution:xC.optional(),_meta:ze(I(),qe()).optional()}),cc=Ms.extend({method:Y("tools/list")}),kC=Us.extend({tools:_e(F_)}),lc=it.extend({content:_e(gh).default([]),structuredContent:ze(I(),qe()).optional(),isError:rt().optional()}),O4=lc.or(it.extend({toolResult:qe()})),$C=js.extend({name:I(),arguments:ze(I(),qe()).optional()}),Po=st.extend({method:Y("tools/call"),params:$C}),SC=Zt.extend({method:Y("notifications/tools/list_changed"),params:Bt.optional()}),C4=K({autoRefresh:rt().default(!0),debounceMs:Re().int().nonnegative().default(300)}),Fs=Et(["debug","info","notice","warning","error","critical","alert","emergency"]),TC=zt.extend({level:Fs}),yh=st.extend({method:Y("logging/setLevel"),params:TC}),EC=Bt.extend({level:Fs,logger:I().optional(),data:qe()}),RC=Zt.extend({method:Y("notifications/message"),params:EC}),PC=K({name:I().optional()}),AC=K({hints:_e(PC).optional(),costPriority:Re().min(0).max(1).optional(),speedPriority:Re().min(0).max(1).optional(),intelligencePriority:Re().min(0).max(1).optional()}),IC=K({mode:Et(["auto","required","none"]).optional()}),OC=K({type:Y("tool_result"),toolUseId:I().describe("The unique identifier for the corresponding tool call."),content:_e(gh).default([]),structuredContent:K({}).loose().optional(),isError:rt().optional(),_meta:ze(I(),qe()).optional()}),CC=th("type",[hh,fh,mh]),Fa=th("type",[hh,fh,mh,mC,OC]),NC=K({role:Zs,content:je([Fa,_e(Fa)]),_meta:ze(I(),qe()).optional()}),zC=js.extend({messages:_e(NC),modelPreferences:AC.optional(),systemPrompt:I().optional(),includeContext:Et(["none","thisServer","allServers"]).optional(),temperature:Re().optional(),maxTokens:Re().int(),stopSequences:_e(I()).optional(),metadata:Qe.optional(),tools:_e(F_).optional(),toolChoice:IC.optional()}),jC=st.extend({method:Y("sampling/createMessage"),params:zC}),Hs=it.extend({model:I(),stopReason:Be(Et(["endTurn","stopSequence","maxTokens"]).or(I())),role:Zs,content:CC}),bh=it.extend({model:I(),stopReason:Be(Et(["endTurn","stopSequence","maxTokens","toolUse"]).or(I())),role:Zs,content:je([Fa,_e(Fa)])}),LC=K({type:Y("boolean"),title:I().optional(),description:I().optional(),default:rt().optional()}),DC=K({type:Y("string"),title:I().optional(),description:I().optional(),minLength:Re().optional(),maxLength:Re().optional(),format:Et(["email","uri","date","date-time"]).optional(),default:I().optional()}),MC=K({type:Et(["number","integer"]),title:I().optional(),description:I().optional(),minimum:Re().optional(),maximum:Re().optional(),default:Re().optional()}),UC=K({type:Y("string"),title:I().optional(),description:I().optional(),enum:_e(I()),default:I().optional()}),qC=K({type:Y("string"),title:I().optional(),description:I().optional(),oneOf:_e(K({const:I(),title:I()})),default:I().optional()}),BC=K({type:Y("string"),title:I().optional(),description:I().optional(),enum:_e(I()),enumNames:_e(I()).optional(),default:I().optional()}),ZC=je([UC,qC]),FC=K({type:Y("array"),title:I().optional(),description:I().optional(),minItems:Re().optional(),maxItems:Re().optional(),items:K({type:Y("string"),enum:_e(I())}),default:_e(I()).optional()}),HC=K({type:Y("array"),title:I().optional(),description:I().optional(),minItems:Re().optional(),maxItems:Re().optional(),items:K({anyOf:_e(K({const:I(),title:I()}))}),default:_e(I()).optional()}),VC=je([FC,HC]),KC=je([BC,ZC,VC]),WC=je([KC,LC,DC,MC]),GC=js.extend({mode:Y("form").optional(),message:I(),requestedSchema:K({type:Y("object"),properties:ze(I(),WC),required:_e(I()).optional()})}),JC=js.extend({mode:Y("url"),message:I(),elicitationId:I(),url:I().url()}),YC=je([GC,JC]),XC=st.extend({method:Y("elicitation/create"),params:YC}),QC=Bt.extend({elicitationId:I()}),eN=Zt.extend({method:Y("notifications/elicitation/complete"),params:QC}),Ao=it.extend({action:Et(["accept","decline","cancel"]),content:rh(t=>t===null?void 0:t,ze(I(),je([I(),Re(),rt(),_e(I())])).optional())}),tN=K({type:Y("ref/resource"),uri:I()}),rN=K({type:Y("ref/prompt"),name:I()}),nN=zt.extend({ref:je([rN,tN]),argument:K({name:I(),value:I()}),context:K({arguments:ze(I(),I()).optional()}).optional()}),uc=st.extend({method:Y("completion/complete"),params:nN});oN=it.extend({completion:yt({values:_e(I()).max(100),total:Be(Re().int()),hasMore:Be(rt())})}),sN=K({uri:I().startsWith("file://"),name:I().optional(),_meta:ze(I(),qe()).optional()}),iN=st.extend({method:Y("roots/list"),params:zt.optional()}),wh=it.extend({roots:_e(sN)}),aN=Zt.extend({method:Y("notifications/roots/list_changed"),params:Bt.optional()}),N4=je([Ga,lh,uc,yh,ac,ic,nc,oc,sc,iC,cC,Po,cc,Ya,Qa,ec,rc]),z4=je([Wa,Ja,uh,aN,Bs]),j4=je([Ka,Hs,bh,Ao,wh,Xa,tc,Eo]),L4=je([Ga,jC,XC,iN,Ya,Qa,ec,rc]),D4=je([Wa,Ja,RC,uC,oC,SC,vC,Bs,eN]),M4=je([Ka,KO,oN,wC,hC,eC,tC,nC,lc,kC,Xa,tc,Eo]),J=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===te.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new nh(o.elicitations,r)}return new t(e,r,n)}},nh=class extends J{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(te.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function en(t){return t==="completed"||t==="failed"||t==="cancelled"}var K_=C(()=>{});var G_,W_,J_,dc=C(()=>{G_=Symbol("Let zodToJsonSchema decide on which parser to use"),W_={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"},J_=t=>typeof t=="string"?{...W_,name:t}:{...W_,...t}});var Y_,vh=C(()=>{dc();Y_=t=>{let e=J_(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 _h(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function xe(t,e,r,n,o){t[e]=r,_h(t,e,n,o)}var tn=C(()=>{});var pc,hc=C(()=>{pc=(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 Ze(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?pc(e,t.currentPath):e.join("/")}}var Ft=C(()=>{hc()});function X_(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==U.ZodAny&&(r.items=ie(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&xe(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&xe(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(xe(r,"minItems",t.exactLength.value,t.exactLength.message,e),xe(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var xh=C(()=>{vs();tn();Je()});function Q_(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?xe(r,"minimum",n.value,n.message,e):xe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),xe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?xe(r,"maximum",n.value,n.message,e):xe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),xe(r,"maximum",n.value,n.message,e));break;case"multipleOf":xe(r,"multipleOf",n.value,n.message,e);break}return r}var kh=C(()=>{tn()});function ex(){return{type:"boolean"}}var $h=C(()=>{});function fc(t,e){return ie(t.type._def,e)}var mc=C(()=>{Je()});var tx,Sh=C(()=>{Je();tx=(t,e)=>ie(t.innerType._def,e)});function Th(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Th(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 cN(t,e)}}var cN,Eh=C(()=>{tn();cN=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":xe(r,"minimum",n.value,n.message,e);break;case"max":xe(r,"maximum",n.value,n.message,e);break}return r}});function rx(t,e){return{...ie(t.innerType._def,e),default:t.defaultValue()}}var Rh=C(()=>{Je()});function nx(t,e){return e.effectStrategy==="input"?ie(t.schema._def,e):Ze(e)}var Ph=C(()=>{Je();Ft()});function ox(t){return{type:"string",enum:Array.from(t.values)}}var Ah=C(()=>{});function sx(t,e){let r=[ie(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),ie(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(lN(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 lN,Ih=C(()=>{Je();lN=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function ix(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 Oh=C(()=>{});function gc(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":xe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":xe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":nr(r,"email",n.message,e);break;case"format:idn-email":nr(r,"idn-email",n.message,e);break;case"pattern:zod":bt(r,rr.email,n.message,e);break}break;case"url":nr(r,"uri",n.message,e);break;case"uuid":nr(r,"uuid",n.message,e);break;case"regex":bt(r,n.regex,n.message,e);break;case"cuid":bt(r,rr.cuid,n.message,e);break;case"cuid2":bt(r,rr.cuid2,n.message,e);break;case"startsWith":bt(r,RegExp(`^${Nh(n.value,e)}`),n.message,e);break;case"endsWith":bt(r,RegExp(`${Nh(n.value,e)}$`),n.message,e);break;case"datetime":nr(r,"date-time",n.message,e);break;case"date":nr(r,"date",n.message,e);break;case"time":nr(r,"time",n.message,e);break;case"duration":nr(r,"duration",n.message,e);break;case"length":xe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),xe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{bt(r,RegExp(Nh(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&nr(r,"ipv4",n.message,e),n.version!=="v4"&&nr(r,"ipv6",n.message,e);break}case"base64url":bt(r,rr.base64url,n.message,e);break;case"jwt":bt(r,rr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&bt(r,rr.ipv4Cidr,n.message,e),n.version!=="v4"&&bt(r,rr.ipv6Cidr,n.message,e);break}case"emoji":bt(r,rr.emoji(),n.message,e);break;case"ulid":{bt(r,rr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{nr(r,"binary",n.message,e);break}case"contentEncoding:base64":{xe(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{bt(r,rr.base64,n.message,e);break}}break}case"nanoid":bt(r,rr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Nh(t,e){return e.patternStrategy==="escape"?dN(t):t}function dN(t){let e="";for(let r=0;r<t.length;r++)uN.has(t[r])||(e+="\\"),e+=t[r];return e}function nr(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):xe(t,"format",e,r,n)}function 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:ax(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):xe(t,"pattern",ax(e,n),r,n)}function ax(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
2030
2037
  ]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
2031
2038
  ]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
2032
2039
  `:`[${n[c]}\r
2033
- ]`;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 Ih,rr,oN,mc=C(()=>{tn();rr={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:()=>(Ih===void 0&&(Ih=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ih),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-_]*$/};oN=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function gc(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===U.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:ie(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Ze(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:ie(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===U.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=fc(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===U.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===U.ZodBranded&&t.keyType._def.type._def.typeName===U.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=pc(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var yc=C(()=>{vs();Je();mc();hc();Ft()});function sx(t,e){if(e.mapStrategy==="record")return gc(t,e);let r=ie(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ze(e),n=ie(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ze(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var Ch=C(()=>{Je();yc();Ft()});function ix(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 Nh=C(()=>{});function ax(t){return t.target==="openAi"?void 0:{not:Ze({...t,currentPath:[...t.currentPath,"not"]})}}var zh=C(()=>{Ft()});function cx(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var jh=C(()=>{});function ux(t,e){if(e.target==="openApi3")return lx(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Vs&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Vs[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 lx(t,e)}var Vs,lx,bc=C(()=>{Je();Vs={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};lx=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>ie(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 dx(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:Vs[t.innerType._def.typeName],nullable:!0}:{type:[Vs[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=ie(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=ie(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var Lh=C(()=>{Je();bc()});function px(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",wh(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?xe(r,"minimum",n.value,n.message,e):xe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),xe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?xe(r,"maximum",n.value,n.message,e):xe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),xe(r,"maximum",n.value,n.message,e));break;case"multipleOf":xe(r,"multipleOf",n.value,n.message,e);break}return r}var Dh=C(()=>{tn()});function hx(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=aN(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=ie(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=iN(t,e);return i!==void 0&&(n.additionalProperties=i),n}function iN(t,e){if(t.catchall._def.typeName!=="ZodNever")return ie(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 aN(t){try{return t.isOptional()}catch{return!0}}var Mh=C(()=>{Je()});var fx,Uh=C(()=>{Je();Ft();fx=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return ie(t.innerType._def,e);let r=ie(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ze(e)},r]}:Ze(e)}});var mx,qh=C(()=>{Je();mx=(t,e)=>{if(e.pipeStrategy==="input")return ie(t.in._def,e);if(e.pipeStrategy==="output")return ie(t.out._def,e);let r=ie(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=ie(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function gx(t,e){return ie(t.type._def,e)}var Bh=C(()=>{Je()});function yx(t,e){let n={type:"array",uniqueItems:!0,items:ie(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&xe(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&xe(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var Zh=C(()=>{tn();Je()});function bx(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>ie(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:ie(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>ie(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var Fh=C(()=>{Je()});function wx(t){return{not:Ze(t)}}var Hh=C(()=>{Ft()});function vx(t){return Ze(t)}var Vh=C(()=>{Ft()});var _x,Kh=C(()=>{Je();_x=(t,e)=>ie(t.innerType._def,e)});var xx,Wh=C(()=>{vs();Ft();vh();_h();xh();hc();kh();Sh();Th();Eh();Rh();Ph();Ah();Ch();Nh();zh();jh();Lh();Dh();Mh();Uh();qh();Bh();yc();Zh();mc();Fh();Hh();bc();Vh();Kh();xx=(t,e,r)=>{switch(e){case U.ZodString:return fc(t,r);case U.ZodNumber:return px(t,r);case U.ZodObject:return hx(t,r);case U.ZodBigInt:return J_(t,r);case U.ZodBoolean:return Y_();case U.ZodDate:return $h(t,r);case U.ZodUndefined:return wx(r);case U.ZodNull:return cx(r);case U.ZodArray:return G_(t,r);case U.ZodUnion:case U.ZodDiscriminatedUnion:return ux(t,r);case U.ZodIntersection:return rx(t,r);case U.ZodTuple:return bx(t,r);case U.ZodRecord:return gc(t,r);case U.ZodLiteral:return nx(t,r);case U.ZodEnum:return tx(t);case U.ZodNativeEnum:return ix(t);case U.ZodNullable:return dx(t,r);case U.ZodOptional:return fx(t,r);case U.ZodMap:return sx(t,r);case U.ZodSet:return yx(t,r);case U.ZodLazy:return()=>t.getter()._def;case U.ZodPromise:return gx(t,r);case U.ZodNaN:case U.ZodNever:return ax(r);case U.ZodEffects:return ex(t,r);case U.ZodAny:return Ze(r);case U.ZodUnknown:return vx(r);case U.ZodDefault:return Q_(t,r);case U.ZodBranded:return pc(t,r);case U.ZodReadonly:return _x(t,r);case U.ZodCatch:return X_(t,r);case U.ZodPipeline:return mx(t,r);case U.ZodFunction:case U.ZodVoid:case U.ZodSymbol:return;default:return(n=>{})(e)}}});function ie(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=cN(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=xx(t,t.typeName,e),i=typeof s=="function"?ie(s(),e):s;if(i&&lN(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var cN,lN,Je=C(()=>{lc();Wh();dc();Ft();cN=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:uc(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`),Ze(e)):e.$refStrategy==="seen"?Ze(e):void 0}},lN=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var kx=C(()=>{});var Gh,Jh=C(()=>{Je();bh();Ft();Gh=(t,e)=>{let r=W_(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:ie(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??Ze(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=ie(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Ze(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 $x=C(()=>{lc();bh();tn();dc();Je();kx();Ft();vh();_h();xh();hc();kh();Sh();Th();Eh();Rh();Ph();Ah();Ch();Nh();zh();jh();Lh();Dh();Mh();Uh();qh();Bh();Kh();yc();Zh();mc();Fh();Hh();bc();Vh();Wh();Jh();Jh()});function uN(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Yh(t,e){return yr(t)?Dp(t,{target:uN(e?.target),io:e?.pipeStrategy??"input"}):Gh(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Xh(t){let r=Xr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=So(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Qh(t,e){let r=Yr(t,e);if(!r.success)throw r.error;return r.data}var ef=C(()=>{qp();Cs();$x()});function Sx(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Tx(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];Sx(i)&&Sx(s)?r[o]={...i,...s}:r[o]=s}return r}var dN,wc,Ex=C(()=>{Cs();Io();F_();ef();dN=6e4,wc=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Va,r=>{this._oncancel(r)}),this.setNotificationHandler(Wa,r=>{this._onprogress(r)}),this.setRequestHandler(Ka,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ga,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new J(te.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Ya,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 p=c,w=new J(p.error.code,p.error.message,p.error.data);u(w)}else{let p=a.type==="response"?"Response":"Error";this._onerror(new Error(`${p} 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 J(te.InvalidParams,`Task not found: ${s}`);if(!en(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(en(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Qr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Xa,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 J(te.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(ec,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new J(te.InvalidParams,`Task not found: ${r.params.taskId}`);if(en(o.status))throw new J(te.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 J(te.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof J?o:new J(te.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),J.fromError(te.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),Ls(s)||C_(s)?this._onresponse(s):oh(s)?this._onrequest(s,i):O_(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=J.fromError(te.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?.[Qr]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:te.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):o?.send(u).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=P_(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 p={relatedRequestId:e.id};s&&(p.relatedTask={taskId:s}),await this.notification(u,p)},sendRequest:async(u,p,w)=>{if(i.signal.aborted)throw new J(te.ConnectionClosed,"Request was cancelled");let f={...w,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let h=f.relatedTask?.taskId??s;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(u,p,f)},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 p={result:u,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)},async u=>{if(i.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:te.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)}).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),Ls(e))n(e);else{let i=new J(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(Ls(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),Ls(e))o(e);else{let i=J.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 J?i:new J(te.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Eo,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new J(te.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},en(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new J(te.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new J(te.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 J?i:new J(te.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 p=P=>{u(P)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(P){p(P);return}n?.signal?.throwIfAborted();let w=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:w};n?.onprogress&&(this._progressHandlers.set(w,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:w}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Qr]:c}});let h=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(B=>this._onerror(new Error(`Failed to send cancellation: ${B}`)));let z=P instanceof J?P:new J(te.RequestTimeout,String(P));u(z)};this._responseHandlers.set(w,P=>{if(!n?.signal?.aborted){if(P instanceof Error)return u(P);try{let z=Yr(r,P.result);z.success?l(z.data):u(z.error)}catch(z){u(z)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let b=n?.timeout??dN,$=()=>h(J.fromError(te.RequestTimeout,"Request timed out",{timeout:b}));this._setupTimeout(w,b,n?.maxTotalTimeout,$,n?.resetTimeoutOnProgress??!1);let E=c?.taskId;if(E){let P=z=>{let B=this._responseHandlers.get(w);B?B(z):this._onerror(new Error(`Response handler missing for side-channeled request ${w}`))};this._requestResolvers.set(w,P),this._enqueueTaskMessage(E,{type:"request",message:f,timestamp:Date.now()}).catch(z=>{this._cleanupTimeout(w),u(z)})}else this._transport.send(f,{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},Ja,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},Qa,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},j_,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||{},[Qr]: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||{},[Qr]: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||{},[Qr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Xh(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Qh(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=Xh(e);this._notificationHandlers.set(n,o=>{let s=Qh(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"&&oh(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new J(te.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 J(te.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new J(te.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 J(te.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=Bs.parse({method:"notifications/tasks/status",params:a});await this.notification(c),en(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 J(te.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(en(a.status))throw new J(te.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=Bs.parse({method:"notifications/tasks/status",params:c});await this.notification(l),en(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var Gs=Z(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.regexpCode=Ee.getEsmExportName=Ee.getProperty=Ee.safeStringify=Ee.stringify=Ee.strConcat=Ee.addCodeArg=Ee.str=Ee._=Ee.nil=Ee._Code=Ee.Name=Ee.IDENTIFIER=Ee._CodeOrName=void 0;var Ks=class{};Ee._CodeOrName=Ks;Ee.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var qn=class extends Ks{constructor(e){if(super(),!Ee.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};Ee.Name=qn;var Ht=class extends Ks{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 qn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Ee._Code=Ht;Ee.nil=new Ht("");function Rx(t,...e){let r=[t[0]],n=0;for(;n<e.length;)rf(r,e[n]),r.push(t[++n]);return new Ht(r)}Ee._=Rx;var tf=new Ht("+");function Px(t,...e){let r=[Ws(t[0])],n=0;for(;n<e.length;)r.push(tf),rf(r,e[n]),r.push(tf,Ws(t[++n]));return pN(r),new Ht(r)}Ee.str=Px;function rf(t,e){e instanceof Ht?t.push(...e._items):e instanceof qn?t.push(e):t.push(mN(e))}Ee.addCodeArg=rf;function pN(t){let e=1;for(;e<t.length-1;){if(t[e]===tf){let r=hN(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function hN(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof qn||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 qn))return`"${t}${e.slice(1)}`}function fN(t,e){return e.emptyStr()?t:t.emptyStr()?e:Px`${t}${e}`}Ee.strConcat=fN;function mN(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Ws(Array.isArray(t)?t.join(","):t)}function gN(t){return new Ht(Ws(t))}Ee.stringify=gN;function Ws(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Ee.safeStringify=Ws;function yN(t){return typeof t=="string"&&Ee.IDENTIFIER.test(t)?new Ht(`.${t}`):Rx`[${t}]`}Ee.getProperty=yN;function bN(t){if(typeof t=="string"&&Ee.IDENTIFIER.test(t))return new Ht(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Ee.getEsmExportName=bN;function wN(t){return new Ht(t.toString())}Ee.regexpCode=wN});var sf=Z(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.ValueScope=Pt.ValueScopeName=Pt.Scope=Pt.varKinds=Pt.UsedValueState=void 0;var Rt=Gs(),nf=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},vc;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(vc||(Pt.UsedValueState=vc={}));Pt.varKinds={const:new Rt.Name("const"),let:new Rt.Name("let"),var:new Rt.Name("var")};var _c=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Rt.Name?e:this.name(e)}name(e){return new Rt.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}}};Pt.Scope=_c;var xc=class extends Rt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Rt._)`.${new Rt.Name(r)}[${n}]`}};Pt.ValueScopeName=xc;var vN=(0,Rt._)`\n`,of=class extends _c{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?vN:Rt.nil}}get(){return this._scope}name(e){return new xc(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,Rt._)`${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=Rt.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,vc.Started);let u=r(l);if(u){let p=this.opts.es5?Pt.varKinds.var:Pt.varKinds.const;s=(0,Rt._)`${s}${p} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))s=(0,Rt._)`${s}${u}${this.opts._n}`;else throw new nf(l);c.set(l,vc.Completed)})}return s}};Pt.ValueScope=of});var he=Z(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.or=fe.and=fe.not=fe.CodeGen=fe.operators=fe.varKinds=fe.ValueScopeName=fe.ValueScope=fe.Scope=fe.Name=fe.regexpCode=fe.stringify=fe.getProperty=fe.nil=fe.strConcat=fe.str=fe._=void 0;var ke=Gs(),or=sf(),rn=Gs();Object.defineProperty(fe,"_",{enumerable:!0,get:function(){return rn._}});Object.defineProperty(fe,"str",{enumerable:!0,get:function(){return rn.str}});Object.defineProperty(fe,"strConcat",{enumerable:!0,get:function(){return rn.strConcat}});Object.defineProperty(fe,"nil",{enumerable:!0,get:function(){return rn.nil}});Object.defineProperty(fe,"getProperty",{enumerable:!0,get:function(){return rn.getProperty}});Object.defineProperty(fe,"stringify",{enumerable:!0,get:function(){return rn.stringify}});Object.defineProperty(fe,"regexpCode",{enumerable:!0,get:function(){return rn.regexpCode}});Object.defineProperty(fe,"Name",{enumerable:!0,get:function(){return rn.Name}});var Tc=sf();Object.defineProperty(fe,"Scope",{enumerable:!0,get:function(){return Tc.Scope}});Object.defineProperty(fe,"ValueScope",{enumerable:!0,get:function(){return Tc.ValueScope}});Object.defineProperty(fe,"ValueScopeName",{enumerable:!0,get:function(){return Tc.ValueScopeName}});Object.defineProperty(fe,"varKinds",{enumerable:!0,get:function(){return Tc.varKinds}});fe.operators={GT:new ke._Code(">"),GTE:new ke._Code(">="),LT:new ke._Code("<"),LTE:new ke._Code("<="),EQ:new ke._Code("==="),NEQ:new ke._Code("!=="),NOT:new ke._Code("!"),OR:new ke._Code("||"),AND:new ke._Code("&&"),ADD:new ke._Code("+")};var Cr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},af=class extends Cr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?or.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=Co(this.rhs,e,r)),this}get names(){return this.rhs instanceof ke._CodeOrName?this.rhs.names:{}}},kc=class extends Cr{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof ke.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Co(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ke.Name?{}:{...this.lhs.names};return Sc(e,this.rhs)}},cf=class extends kc{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},lf=class extends Cr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},uf=class extends Cr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},df=class extends Cr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},pf=class extends Cr{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=Co(this.code,e,r),this}get names(){return this.code instanceof ke._CodeOrName?this.code.names:{}}},Js=class extends Cr{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)||(_N(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Fn(e,r.names),{})}},Nr=class extends Js{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},hf=class extends Js{},Oo=class extends Nr{};Oo.kind="else";var Bn=class t extends Nr{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 Oo(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Ax(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=Co(this.condition,e,r),this}get names(){let e=super.names;return Sc(e,this.condition),this.else&&Fn(e,this.else.names),e}};Bn.kind="if";var Zn=class extends Nr{};Zn.kind="for";var ff=class extends Zn{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=Co(this.iteration,e,r),this}get names(){return Fn(super.names,this.iteration.names)}},mf=class extends Zn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?or.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=Sc(super.names,this.from);return Sc(e,this.to)}},$c=class extends Zn{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=Co(this.iterable,e,r),this}get names(){return Fn(super.names,this.iterable.names)}},Ys=class extends Nr{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)}};Ys.kind="func";var Xs=class extends Js{render(e){return"return "+super.render(e)}};Xs.kind="return";var gf=class extends Nr{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&&Fn(e,this.catch.names),this.finally&&Fn(e,this.finally.names),e}},Qs=class extends Nr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Qs.kind="catch";var ei=class extends Nr{render(e){return"finally"+super.render(e)}};ei.kind="finally";var yf=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
2034
- `:""},this._extScope=e,this._scope=new or.Scope({parent:e}),this._nodes=[new hf]}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 af(e,s,n)),s}const(e,r,n){return this._def(or.varKinds.const,e,r,n)}let(e,r,n){return this._def(or.varKinds.let,e,r,n)}var(e,r,n){return this._def(or.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new kc(e,r,n))}add(e,r){return this._leafNode(new cf(e,fe.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ke.nil&&this._leafNode(new pf(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,ke.addCodeArg)(r,o));return r.push("}"),new ke._Code(r)}if(e,r,n){if(this._blockNode(new Bn(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 Bn(e))}else(){return this._elseNode(new Oo)}endIf(){return this._endBlockNode(Bn,Oo)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new ff(e),r)}forRange(e,r,n,o,s=this.opts.es5?or.varKinds.var:or.varKinds.let){let i=this._scope.toName(e);return this._for(new mf(s,i,r,n),()=>o(i))}forOf(e,r,n,o=or.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof ke.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ke._)`${i}.length`,a=>{this.var(s,(0,ke._)`${i}[${a}]`),n(s)})}return this._for(new $c("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?or.varKinds.var:or.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ke._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new $c("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Zn)}label(e){return this._leafNode(new lf(e))}break(e){return this._leafNode(new uf(e))}return(e){let r=new Xs;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Xs)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new gf;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Qs(s),r(s)}return n&&(this._currNode=o.finally=new ei,this.code(n)),this._endBlockNode(Qs,ei)}throw(e){return this._leafNode(new df(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=ke.nil,n,o){return this._blockNode(new Ys(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Ys)}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 Bn))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=yf;function Fn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Sc(t,e){return e instanceof ke._CodeOrName?Fn(t,e.names):t}function Co(t,e,r){if(t instanceof ke.Name)return n(t);if(!o(t))return t;return new ke._Code(t._items.reduce((s,i)=>(i instanceof ke.Name&&(i=n(i)),i instanceof ke._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof ke._Code&&s._items.some(i=>i instanceof ke.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function _N(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Ax(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ke._)`!${bf(t)}`}fe.not=Ax;var xN=Ix(fe.operators.AND);function kN(...t){return t.reduce(xN)}fe.and=kN;var $N=Ix(fe.operators.OR);function SN(...t){return t.reduce($N)}fe.or=SN;function Ix(t){return(e,r)=>e===ke.nil?r:r===ke.nil?e:(0,ke._)`${bf(e)} ${t} ${bf(r)}`}function bf(t){return t instanceof ke.Name?t:(0,ke._)`(${t})`}});var Se=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=he(),TN=Gs();function EN(t){let e={};for(let r of t)e[r]=!0;return e}me.toHash=EN;function RN(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Nx(t,e),!zx(e,t.self.RULES.all))}me.alwaysValidSchema=RN;function Nx(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]||Dx(t,`unknown keyword: "${s}"`)}me.checkUnknownRules=Nx;function zx(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}me.schemaHasRules=zx;function PN(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=PN;function AN({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=AN;function IN(t){return jx(decodeURIComponent(t))}me.unescapeFragment=IN;function ON(t){return encodeURIComponent(vf(t))}me.escapeFragment=ON;function vf(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}me.escapeJsonPointer=vf;function jx(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}me.unescapeJsonPointer=jx;function CN(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}me.eachItem=CN;function Ox({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:Ox({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} || {}`),_f(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Lx}),items:Ox({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 Lx(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Oe._)`{}`);return e!==void 0&&_f(t,r,e),r}me.evaluatedPropsToName=Lx;function _f(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Oe._)`${e}${(0,Oe.getProperty)(n)}`,!0))}me.setEvaluated=_f;var Cx={};function NN(t,e){return t.scopeValue("func",{ref:e,code:Cx[e.code]||(Cx[e.code]=new TN._Code(e.code))})}me.useFunc=NN;var wf;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(wf||(me.Type=wf={}));function zN(t,e,r){if(t instanceof Oe.Name){let n=e===wf.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():"/"+vf(t)}me.getErrorPath=zN;function Dx(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=Dx});var zr=Z(xf=>{"use strict";Object.defineProperty(xf,"__esModule",{value:!0});var dt=he(),jN={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")};xf.default=jN});var ti=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 Te=he(),Ec=Se(),wt=zr();pt.keywordError={message:({keyword:t})=>(0,Te.str)`must pass "${t}" keyword validation`};pt.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,Te.str)`"${t}" keyword must be ${e} ($data)`:(0,Te.str)`"${t}" keyword is invalid ($data)`};function LN(t,e=pt.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=qx(t,e,r);n??(i||a)?Mx(s,c):Ux(o,(0,Te._)`[${c}]`)}pt.reportError=LN;function DN(t,e=pt.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=qx(t,e,r);Mx(o,a),s||i||Ux(n,wt.default.vErrors)}pt.reportExtraError=DN;function MN(t,e){t.assign(wt.default.errors,e),t.if((0,Te._)`${wt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,Te._)`${wt.default.vErrors}.length`,e),()=>t.assign(wt.default.vErrors,null)))}pt.resetErrorsCount=MN;function UN({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,Te._)`${wt.default.vErrors}[${a}]`),t.if((0,Te._)`${i}.instancePath === undefined`,()=>t.assign((0,Te._)`${i}.instancePath`,(0,Te.strConcat)(wt.default.instancePath,s.errorPath))),t.assign((0,Te._)`${i}.schemaPath`,(0,Te.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,Te._)`${i}.schema`,r),t.assign((0,Te._)`${i}.data`,n))})}pt.extendErrors=UN;function Mx(t,e){let r=t.const("err",e);t.if((0,Te._)`${wt.default.vErrors} === null`,()=>t.assign(wt.default.vErrors,(0,Te._)`[${r}]`),(0,Te._)`${wt.default.vErrors}.push(${r})`),t.code((0,Te._)`${wt.default.errors}++`)}function Ux(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,Te._)`new ${t.ValidationError}(${e})`):(r.assign((0,Te._)`${n}.errors`,e),r.return(!1))}var Hn={keyword:new Te.Name("keyword"),schemaPath:new Te.Name("schemaPath"),params:new Te.Name("params"),propertyName:new Te.Name("propertyName"),message:new Te.Name("message"),schema:new Te.Name("schema"),parentSchema:new Te.Name("parentSchema")};function qx(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,Te._)`{}`:qN(t,e,r)}function qN(t,e,r={}){let{gen:n,it:o}=t,s=[BN(o,r),ZN(t,r)];return FN(t,e,s),n.object(...s)}function BN({errorPath:t},{instancePath:e}){let r=e?(0,Te.str)`${t}${(0,Ec.getErrorPath)(e,Ec.Type.Str)}`:t;return[wt.default.instancePath,(0,Te.strConcat)(wt.default.instancePath,r)]}function ZN({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,Te.str)`${e}/${t}`;return r&&(o=(0,Te.str)`${o}${(0,Ec.getErrorPath)(r,Ec.Type.Str)}`),[Hn.schemaPath,o]}function FN(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:p}=a;n.push([Hn.keyword,o],[Hn.params,typeof e=="function"?e(t):e||(0,Te._)`{}`]),c.messages&&n.push([Hn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Hn.schema,i],[Hn.parentSchema,(0,Te._)`${u}${p}`],[wt.default.data,s]),l&&n.push([Hn.propertyName,l])}});var Zx=Z(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});No.boolOrEmptySchema=No.topBoolOrEmptySchema=void 0;var HN=ti(),VN=he(),KN=zr(),WN={message:"boolean schema is false"};function GN(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Bx(t,!1):typeof r=="object"&&r.$async===!0?e.return(KN.default.data):(e.assign((0,VN._)`${n}.errors`,null),e.return(!0))}No.topBoolOrEmptySchema=GN;function JN(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Bx(t)):r.var(e,!0)}No.boolOrEmptySchema=JN;function Bx(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,HN.reportError)(o,WN,void 0,e)}});var kf=Z(zo=>{"use strict";Object.defineProperty(zo,"__esModule",{value:!0});zo.getRules=zo.isJSONType=void 0;var YN=["string","number","integer","boolean","null","object","array"],XN=new Set(YN);function QN(t){return typeof t=="string"&&XN.has(t)}zo.isJSONType=QN;function ez(){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:{}}}zo.getRules=ez});var $f=Z(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});nn.shouldUseRule=nn.shouldUseGroup=nn.schemaHasRulesForType=void 0;function tz({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Fx(t,n)}nn.schemaHasRulesForType=tz;function Fx(t,e){return e.rules.some(r=>Hx(t,r))}nn.shouldUseGroup=Fx;function Hx(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))}nn.shouldUseRule=Hx});var ri=Z(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.reportTypeError=ht.checkDataTypes=ht.checkDataType=ht.coerceAndCheckDataType=ht.getJSONTypes=ht.getSchemaTypes=ht.DataType=void 0;var rz=kf(),nz=$f(),oz=ti(),de=he(),Vx=Se(),jo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(jo||(ht.DataType=jo={}));function sz(t){let e=Kx(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}ht.getSchemaTypes=sz;function Kx(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(rz.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ht.getJSONTypes=Kx;function iz(t,e){let{gen:r,data:n,opts:o}=t,s=az(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,nz.schemaHasRulesForType)(t,e[0]));if(i){let a=Tf(e,n,o.strictNumbers,jo.Wrong);r.if(a,()=>{s.length?cz(t,e,s):Ef(t)})}return i}ht.coerceAndCheckDataType=iz;var Wx=new Set(["string","number","integer","boolean","null"]);function az(t,e){return e?t.filter(r=>Wx.has(r)||e==="array"&&r==="array"):[]}function cz(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,de._)`typeof ${o}`),a=n.let("coerced",(0,de._)`undefined`);s.coerceTypes==="array"&&n.if((0,de._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,de._)`${o}[0]`).assign(i,(0,de._)`typeof ${o}`).if(Tf(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,de._)`${a} !== undefined`);for(let l of r)(Wx.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),Ef(t),n.endIf(),n.if((0,de._)`${a} !== undefined`,()=>{n.assign(o,a),lz(t,a)});function c(l){switch(l){case"string":n.elseIf((0,de._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,de._)`"" + ${o}`).elseIf((0,de._)`${o} === null`).assign(a,(0,de._)`""`);return;case"number":n.elseIf((0,de._)`${i} == "boolean" || ${o} === null
2040
+ ]`;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 Ch,rr,uN,yc=C(()=>{tn();rr={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:()=>(Ch===void 0&&(Ch=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ch),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-_]*$/};uN=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function bc(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===U.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:ie(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Ze(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:ie(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===U.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=gc(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===U.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===U.ZodBranded&&t.keyType._def.type._def.typeName===U.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=fc(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var wc=C(()=>{vs();Je();yc();mc();Ft()});function cx(t,e){if(e.mapStrategy==="record")return bc(t,e);let r=ie(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ze(e),n=ie(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ze(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var zh=C(()=>{Je();wc();Ft()});function lx(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 jh=C(()=>{});function ux(t){return t.target==="openAi"?void 0:{not:Ze({...t,currentPath:[...t.currentPath,"not"]})}}var Lh=C(()=>{Ft()});function dx(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Dh=C(()=>{});function hx(t,e){if(e.target==="openApi3")return px(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Vs&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Vs[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 px(t,e)}var Vs,px,vc=C(()=>{Je();Vs={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};px=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>ie(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 fx(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:Vs[t.innerType._def.typeName],nullable:!0}:{type:[Vs[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=ie(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=ie(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var Mh=C(()=>{Je();vc()});function mx(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",_h(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?xe(r,"minimum",n.value,n.message,e):xe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),xe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?xe(r,"maximum",n.value,n.message,e):xe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),xe(r,"maximum",n.value,n.message,e));break;case"multipleOf":xe(r,"multipleOf",n.value,n.message,e);break}return r}var Uh=C(()=>{tn()});function gx(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=hN(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=ie(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=pN(t,e);return i!==void 0&&(n.additionalProperties=i),n}function pN(t,e){if(t.catchall._def.typeName!=="ZodNever")return ie(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 hN(t){try{return t.isOptional()}catch{return!0}}var qh=C(()=>{Je()});var yx,Bh=C(()=>{Je();Ft();yx=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return ie(t.innerType._def,e);let r=ie(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ze(e)},r]}:Ze(e)}});var bx,Zh=C(()=>{Je();bx=(t,e)=>{if(e.pipeStrategy==="input")return ie(t.in._def,e);if(e.pipeStrategy==="output")return ie(t.out._def,e);let r=ie(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=ie(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function wx(t,e){return ie(t.type._def,e)}var Fh=C(()=>{Je()});function vx(t,e){let n={type:"array",uniqueItems:!0,items:ie(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&xe(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&xe(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var Hh=C(()=>{tn();Je()});function _x(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>ie(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:ie(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>ie(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var Vh=C(()=>{Je()});function xx(t){return{not:Ze(t)}}var Kh=C(()=>{Ft()});function kx(t){return Ze(t)}var Wh=C(()=>{Ft()});var $x,Gh=C(()=>{Je();$x=(t,e)=>ie(t.innerType._def,e)});var Sx,Jh=C(()=>{vs();Ft();xh();kh();$h();mc();Sh();Eh();Rh();Ph();Ah();Ih();Oh();zh();jh();Lh();Dh();Mh();Uh();qh();Bh();Zh();Fh();wc();Hh();yc();Vh();Kh();vc();Wh();Gh();Sx=(t,e,r)=>{switch(e){case U.ZodString:return gc(t,r);case U.ZodNumber:return mx(t,r);case U.ZodObject:return gx(t,r);case U.ZodBigInt:return Q_(t,r);case U.ZodBoolean:return ex();case U.ZodDate:return Th(t,r);case U.ZodUndefined:return xx(r);case U.ZodNull:return dx(r);case U.ZodArray:return X_(t,r);case U.ZodUnion:case U.ZodDiscriminatedUnion:return hx(t,r);case U.ZodIntersection:return sx(t,r);case U.ZodTuple:return _x(t,r);case U.ZodRecord:return bc(t,r);case U.ZodLiteral:return ix(t,r);case U.ZodEnum:return ox(t);case U.ZodNativeEnum:return lx(t);case U.ZodNullable:return fx(t,r);case U.ZodOptional:return yx(t,r);case U.ZodMap:return cx(t,r);case U.ZodSet:return vx(t,r);case U.ZodLazy:return()=>t.getter()._def;case U.ZodPromise:return wx(t,r);case U.ZodNaN:case U.ZodNever:return ux(r);case U.ZodEffects:return nx(t,r);case U.ZodAny:return Ze(r);case U.ZodUnknown:return kx(r);case U.ZodDefault:return rx(t,r);case U.ZodBranded:return fc(t,r);case U.ZodReadonly:return $x(t,r);case U.ZodCatch:return tx(t,r);case U.ZodPipeline:return bx(t,r);case U.ZodFunction:case U.ZodVoid:case U.ZodSymbol:return;default:return(n=>{})(e)}}});function ie(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==G_)return a}if(n&&!r){let a=fN(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=Sx(t,t.typeName,e),i=typeof s=="function"?ie(s(),e):s;if(i&&mN(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var fN,mN,Je=C(()=>{dc();Jh();hc();Ft();fN=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:pc(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`),Ze(e)):e.$refStrategy==="seen"?Ze(e):void 0}},mN=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var Tx=C(()=>{});var Yh,Xh=C(()=>{Je();vh();Ft();Yh=(t,e)=>{let r=Y_(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:ie(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??Ze(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=ie(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Ze(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 Ex=C(()=>{dc();vh();tn();hc();Je();Tx();Ft();xh();kh();$h();mc();Sh();Eh();Rh();Ph();Ah();Ih();Oh();zh();jh();Lh();Dh();Mh();Uh();qh();Bh();Zh();Fh();Gh();wc();Hh();yc();Vh();Kh();vc();Wh();Jh();Xh();Xh()});function gN(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Qh(t,e){return yr(t)?Up(t,{target:gN(e?.target),io:e?.pipeStrategy??"input"}):Yh(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function ef(t){let r=Xr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=So(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function tf(t,e){let r=Yr(t,e);if(!r.success)throw r.error;return r.data}var rf=C(()=>{Zp();Cs();Ex()});function Rx(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Px(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];Rx(i)&&Rx(s)?r[o]={...i,...s}:r[o]=s}return r}var yN,_c,Ax=C(()=>{Cs();Io();K_();rf();yN=6e4,_c=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(Wa,r=>{this._oncancel(r)}),this.setNotificationHandler(Ja,r=>{this._onprogress(r)}),this.setRequestHandler(Ga,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ya,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new J(te.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Qa,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 p=c,w=new J(p.error.code,p.error.message,p.error.data);u(w)}else{let p=a.type==="response"?"Response":"Error";this._onerror(new Error(`${p} 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 J(te.InvalidParams,`Task not found: ${s}`);if(!en(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(en(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Qr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(ec,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 J(te.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(rc,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new J(te.InvalidParams,`Task not found: ${r.params.taskId}`);if(en(o.status))throw new J(te.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 J(te.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof J?o:new J(te.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),J.fromError(te.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),Ls(s)||j_(s)?this._onresponse(s):ih(s)?this._onrequest(s,i):z_(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=J.fromError(te.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?.[Qr]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:te.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):o?.send(u).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=O_(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 p={relatedRequestId:e.id};s&&(p.relatedTask={taskId:s}),await this.notification(u,p)},sendRequest:async(u,p,w)=>{if(i.signal.aborted)throw new J(te.ConnectionClosed,"Request was cancelled");let f={...w,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let h=f.relatedTask?.taskId??s;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(u,p,f)},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 p={result:u,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)},async u=>{if(i.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:te.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)}).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),Ls(e))n(e);else{let i=new J(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(Ls(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),Ls(e))o(e);else{let i=J.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 J?i:new J(te.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Eo,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new J(te.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},en(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new J(te.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new J(te.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 J?i:new J(te.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 p=P=>{u(P)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(P){p(P);return}n?.signal?.throwIfAborted();let w=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:w};n?.onprogress&&(this._progressHandlers.set(w,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:w}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Qr]:c}});let h=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(B=>this._onerror(new Error(`Failed to send cancellation: ${B}`)));let z=P instanceof J?P:new J(te.RequestTimeout,String(P));u(z)};this._responseHandlers.set(w,P=>{if(!n?.signal?.aborted){if(P instanceof Error)return u(P);try{let z=Yr(r,P.result);z.success?l(z.data):u(z.error)}catch(z){u(z)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let b=n?.timeout??yN,$=()=>h(J.fromError(te.RequestTimeout,"Request timed out",{timeout:b}));this._setupTimeout(w,b,n?.maxTotalTimeout,$,n?.resetTimeoutOnProgress??!1);let E=c?.taskId;if(E){let P=z=>{let B=this._responseHandlers.get(w);B?B(z):this._onerror(new Error(`Response handler missing for side-channeled request ${w}`))};this._requestResolvers.set(w,P),this._enqueueTaskMessage(E,{type:"request",message:f,timestamp:Date.now()}).catch(z=>{this._cleanupTimeout(w),u(z)})}else this._transport.send(f,{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},Xa,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},tc,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},M_,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||{},[Qr]: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||{},[Qr]: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||{},[Qr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=ef(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=ef(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"&&ih(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new J(te.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 J(te.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new J(te.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 J(te.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=Bs.parse({method:"notifications/tasks/status",params:a});await this.notification(c),en(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 J(te.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(en(a.status))throw new J(te.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=Bs.parse({method:"notifications/tasks/status",params:c});await this.notification(l),en(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var Gs=Z(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.regexpCode=Ee.getEsmExportName=Ee.getProperty=Ee.safeStringify=Ee.stringify=Ee.strConcat=Ee.addCodeArg=Ee.str=Ee._=Ee.nil=Ee._Code=Ee.Name=Ee.IDENTIFIER=Ee._CodeOrName=void 0;var Ks=class{};Ee._CodeOrName=Ks;Ee.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var qn=class extends Ks{constructor(e){if(super(),!Ee.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};Ee.Name=qn;var Ht=class extends Ks{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 qn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Ee._Code=Ht;Ee.nil=new Ht("");function Ix(t,...e){let r=[t[0]],n=0;for(;n<e.length;)of(r,e[n]),r.push(t[++n]);return new Ht(r)}Ee._=Ix;var nf=new Ht("+");function Ox(t,...e){let r=[Ws(t[0])],n=0;for(;n<e.length;)r.push(nf),of(r,e[n]),r.push(nf,Ws(t[++n]));return bN(r),new Ht(r)}Ee.str=Ox;function of(t,e){e instanceof Ht?t.push(...e._items):e instanceof qn?t.push(e):t.push(_N(e))}Ee.addCodeArg=of;function bN(t){let e=1;for(;e<t.length-1;){if(t[e]===nf){let r=wN(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function wN(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof qn||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 qn))return`"${t}${e.slice(1)}`}function vN(t,e){return e.emptyStr()?t:t.emptyStr()?e:Ox`${t}${e}`}Ee.strConcat=vN;function _N(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Ws(Array.isArray(t)?t.join(","):t)}function xN(t){return new Ht(Ws(t))}Ee.stringify=xN;function Ws(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Ee.safeStringify=Ws;function kN(t){return typeof t=="string"&&Ee.IDENTIFIER.test(t)?new Ht(`.${t}`):Ix`[${t}]`}Ee.getProperty=kN;function $N(t){if(typeof t=="string"&&Ee.IDENTIFIER.test(t))return new Ht(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Ee.getEsmExportName=$N;function SN(t){return new Ht(t.toString())}Ee.regexpCode=SN});var cf=Z(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.ValueScope=Pt.ValueScopeName=Pt.Scope=Pt.varKinds=Pt.UsedValueState=void 0;var Rt=Gs(),sf=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},xc;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(xc||(Pt.UsedValueState=xc={}));Pt.varKinds={const:new Rt.Name("const"),let:new Rt.Name("let"),var:new Rt.Name("var")};var kc=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Rt.Name?e:this.name(e)}name(e){return new Rt.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}}};Pt.Scope=kc;var $c=class extends Rt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Rt._)`.${new Rt.Name(r)}[${n}]`}};Pt.ValueScopeName=$c;var TN=(0,Rt._)`\n`,af=class extends kc{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?TN:Rt.nil}}get(){return this._scope}name(e){return new $c(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,Rt._)`${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=Rt.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,xc.Started);let u=r(l);if(u){let p=this.opts.es5?Pt.varKinds.var:Pt.varKinds.const;s=(0,Rt._)`${s}${p} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))s=(0,Rt._)`${s}${u}${this.opts._n}`;else throw new sf(l);c.set(l,xc.Completed)})}return s}};Pt.ValueScope=af});var he=Z(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.or=fe.and=fe.not=fe.CodeGen=fe.operators=fe.varKinds=fe.ValueScopeName=fe.ValueScope=fe.Scope=fe.Name=fe.regexpCode=fe.stringify=fe.getProperty=fe.nil=fe.strConcat=fe.str=fe._=void 0;var ke=Gs(),or=cf(),rn=Gs();Object.defineProperty(fe,"_",{enumerable:!0,get:function(){return rn._}});Object.defineProperty(fe,"str",{enumerable:!0,get:function(){return rn.str}});Object.defineProperty(fe,"strConcat",{enumerable:!0,get:function(){return rn.strConcat}});Object.defineProperty(fe,"nil",{enumerable:!0,get:function(){return rn.nil}});Object.defineProperty(fe,"getProperty",{enumerable:!0,get:function(){return rn.getProperty}});Object.defineProperty(fe,"stringify",{enumerable:!0,get:function(){return rn.stringify}});Object.defineProperty(fe,"regexpCode",{enumerable:!0,get:function(){return rn.regexpCode}});Object.defineProperty(fe,"Name",{enumerable:!0,get:function(){return rn.Name}});var Rc=cf();Object.defineProperty(fe,"Scope",{enumerable:!0,get:function(){return Rc.Scope}});Object.defineProperty(fe,"ValueScope",{enumerable:!0,get:function(){return Rc.ValueScope}});Object.defineProperty(fe,"ValueScopeName",{enumerable:!0,get:function(){return Rc.ValueScopeName}});Object.defineProperty(fe,"varKinds",{enumerable:!0,get:function(){return Rc.varKinds}});fe.operators={GT:new ke._Code(">"),GTE:new ke._Code(">="),LT:new ke._Code("<"),LTE:new ke._Code("<="),EQ:new ke._Code("==="),NEQ:new ke._Code("!=="),NOT:new ke._Code("!"),OR:new ke._Code("||"),AND:new ke._Code("&&"),ADD:new ke._Code("+")};var Cr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},lf=class extends Cr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?or.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=Co(this.rhs,e,r)),this}get names(){return this.rhs instanceof ke._CodeOrName?this.rhs.names:{}}},Sc=class extends Cr{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof ke.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Co(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ke.Name?{}:{...this.lhs.names};return Ec(e,this.rhs)}},uf=class extends Sc{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},df=class extends Cr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},pf=class extends Cr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},hf=class extends Cr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},ff=class extends Cr{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=Co(this.code,e,r),this}get names(){return this.code instanceof ke._CodeOrName?this.code.names:{}}},Js=class extends Cr{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)||(EN(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Fn(e,r.names),{})}},Nr=class extends Js{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},mf=class extends Js{},Oo=class extends Nr{};Oo.kind="else";var Bn=class t extends Nr{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 Oo(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Cx(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=Co(this.condition,e,r),this}get names(){let e=super.names;return Ec(e,this.condition),this.else&&Fn(e,this.else.names),e}};Bn.kind="if";var Zn=class extends Nr{};Zn.kind="for";var gf=class extends Zn{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=Co(this.iteration,e,r),this}get names(){return Fn(super.names,this.iteration.names)}},yf=class extends Zn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?or.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=Ec(super.names,this.from);return Ec(e,this.to)}},Tc=class extends Zn{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=Co(this.iterable,e,r),this}get names(){return Fn(super.names,this.iterable.names)}},Ys=class extends Nr{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)}};Ys.kind="func";var Xs=class extends Js{render(e){return"return "+super.render(e)}};Xs.kind="return";var bf=class extends Nr{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&&Fn(e,this.catch.names),this.finally&&Fn(e,this.finally.names),e}},Qs=class extends Nr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Qs.kind="catch";var ei=class extends Nr{render(e){return"finally"+super.render(e)}};ei.kind="finally";var wf=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
2041
+ `:""},this._extScope=e,this._scope=new or.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 lf(e,s,n)),s}const(e,r,n){return this._def(or.varKinds.const,e,r,n)}let(e,r,n){return this._def(or.varKinds.let,e,r,n)}var(e,r,n){return this._def(or.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Sc(e,r,n))}add(e,r){return this._leafNode(new uf(e,fe.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ke.nil&&this._leafNode(new ff(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,ke.addCodeArg)(r,o));return r.push("}"),new ke._Code(r)}if(e,r,n){if(this._blockNode(new Bn(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 Bn(e))}else(){return this._elseNode(new Oo)}endIf(){return this._endBlockNode(Bn,Oo)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new gf(e),r)}forRange(e,r,n,o,s=this.opts.es5?or.varKinds.var:or.varKinds.let){let i=this._scope.toName(e);return this._for(new yf(s,i,r,n),()=>o(i))}forOf(e,r,n,o=or.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof ke.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ke._)`${i}.length`,a=>{this.var(s,(0,ke._)`${i}[${a}]`),n(s)})}return this._for(new Tc("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?or.varKinds.var:or.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ke._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Tc("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Zn)}label(e){return this._leafNode(new df(e))}break(e){return this._leafNode(new pf(e))}return(e){let r=new Xs;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Xs)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new bf;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Qs(s),r(s)}return n&&(this._currNode=o.finally=new ei,this.code(n)),this._endBlockNode(Qs,ei)}throw(e){return this._leafNode(new hf(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=ke.nil,n,o){return this._blockNode(new Ys(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Ys)}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 Bn))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=wf;function Fn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Ec(t,e){return e instanceof ke._CodeOrName?Fn(t,e.names):t}function Co(t,e,r){if(t instanceof ke.Name)return n(t);if(!o(t))return t;return new ke._Code(t._items.reduce((s,i)=>(i instanceof ke.Name&&(i=n(i)),i instanceof ke._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof ke._Code&&s._items.some(i=>i instanceof ke.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function EN(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Cx(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ke._)`!${vf(t)}`}fe.not=Cx;var RN=Nx(fe.operators.AND);function PN(...t){return t.reduce(RN)}fe.and=PN;var AN=Nx(fe.operators.OR);function IN(...t){return t.reduce(AN)}fe.or=IN;function Nx(t){return(e,r)=>e===ke.nil?r:r===ke.nil?e:(0,ke._)`${vf(e)} ${t} ${vf(r)}`}function vf(t){return t instanceof ke.Name?t:(0,ke._)`(${t})`}});var Se=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=he(),ON=Gs();function CN(t){let e={};for(let r of t)e[r]=!0;return e}me.toHash=CN;function NN(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Lx(t,e),!Dx(e,t.self.RULES.all))}me.alwaysValidSchema=NN;function Lx(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]||qx(t,`unknown keyword: "${s}"`)}me.checkUnknownRules=Lx;function Dx(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}me.schemaHasRules=Dx;function zN(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=zN;function jN({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=jN;function LN(t){return Mx(decodeURIComponent(t))}me.unescapeFragment=LN;function DN(t){return encodeURIComponent(xf(t))}me.escapeFragment=DN;function xf(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}me.escapeJsonPointer=xf;function Mx(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}me.unescapeJsonPointer=Mx;function MN(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}me.eachItem=MN;function zx({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:zx({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:Ux}),items:zx({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 Ux(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=Ux;function kf(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Oe._)`${e}${(0,Oe.getProperty)(n)}`,!0))}me.setEvaluated=kf;var jx={};function UN(t,e){return t.scopeValue("func",{ref:e,code:jx[e.code]||(jx[e.code]=new ON._Code(e.code))})}me.useFunc=UN;var _f;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(_f||(me.Type=_f={}));function qN(t,e,r){if(t instanceof Oe.Name){let n=e===_f.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():"/"+xf(t)}me.getErrorPath=qN;function qx(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=qx});var zr=Z($f=>{"use strict";Object.defineProperty($f,"__esModule",{value:!0});var dt=he(),BN={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")};$f.default=BN});var ti=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 Te=he(),Pc=Se(),wt=zr();pt.keywordError={message:({keyword:t})=>(0,Te.str)`must pass "${t}" keyword validation`};pt.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,Te.str)`"${t}" keyword must be ${e} ($data)`:(0,Te.str)`"${t}" keyword is invalid ($data)`};function ZN(t,e=pt.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Fx(t,e,r);n??(i||a)?Bx(s,c):Zx(o,(0,Te._)`[${c}]`)}pt.reportError=ZN;function FN(t,e=pt.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Fx(t,e,r);Bx(o,a),s||i||Zx(n,wt.default.vErrors)}pt.reportExtraError=FN;function HN(t,e){t.assign(wt.default.errors,e),t.if((0,Te._)`${wt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,Te._)`${wt.default.vErrors}.length`,e),()=>t.assign(wt.default.vErrors,null)))}pt.resetErrorsCount=HN;function VN({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,Te._)`${wt.default.vErrors}[${a}]`),t.if((0,Te._)`${i}.instancePath === undefined`,()=>t.assign((0,Te._)`${i}.instancePath`,(0,Te.strConcat)(wt.default.instancePath,s.errorPath))),t.assign((0,Te._)`${i}.schemaPath`,(0,Te.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,Te._)`${i}.schema`,r),t.assign((0,Te._)`${i}.data`,n))})}pt.extendErrors=VN;function Bx(t,e){let r=t.const("err",e);t.if((0,Te._)`${wt.default.vErrors} === null`,()=>t.assign(wt.default.vErrors,(0,Te._)`[${r}]`),(0,Te._)`${wt.default.vErrors}.push(${r})`),t.code((0,Te._)`${wt.default.errors}++`)}function Zx(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,Te._)`new ${t.ValidationError}(${e})`):(r.assign((0,Te._)`${n}.errors`,e),r.return(!1))}var Hn={keyword:new Te.Name("keyword"),schemaPath:new Te.Name("schemaPath"),params:new Te.Name("params"),propertyName:new Te.Name("propertyName"),message:new Te.Name("message"),schema:new Te.Name("schema"),parentSchema:new Te.Name("parentSchema")};function Fx(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,Te._)`{}`:KN(t,e,r)}function KN(t,e,r={}){let{gen:n,it:o}=t,s=[WN(o,r),GN(t,r)];return JN(t,e,s),n.object(...s)}function WN({errorPath:t},{instancePath:e}){let r=e?(0,Te.str)`${t}${(0,Pc.getErrorPath)(e,Pc.Type.Str)}`:t;return[wt.default.instancePath,(0,Te.strConcat)(wt.default.instancePath,r)]}function GN({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,Te.str)`${e}/${t}`;return r&&(o=(0,Te.str)`${o}${(0,Pc.getErrorPath)(r,Pc.Type.Str)}`),[Hn.schemaPath,o]}function JN(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:p}=a;n.push([Hn.keyword,o],[Hn.params,typeof e=="function"?e(t):e||(0,Te._)`{}`]),c.messages&&n.push([Hn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Hn.schema,i],[Hn.parentSchema,(0,Te._)`${u}${p}`],[wt.default.data,s]),l&&n.push([Hn.propertyName,l])}});var Vx=Z(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});No.boolOrEmptySchema=No.topBoolOrEmptySchema=void 0;var YN=ti(),XN=he(),QN=zr(),ez={message:"boolean schema is false"};function tz(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Hx(t,!1):typeof r=="object"&&r.$async===!0?e.return(QN.default.data):(e.assign((0,XN._)`${n}.errors`,null),e.return(!0))}No.topBoolOrEmptySchema=tz;function rz(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Hx(t)):r.var(e,!0)}No.boolOrEmptySchema=rz;function Hx(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,YN.reportError)(o,ez,void 0,e)}});var Sf=Z(zo=>{"use strict";Object.defineProperty(zo,"__esModule",{value:!0});zo.getRules=zo.isJSONType=void 0;var nz=["string","number","integer","boolean","null","object","array"],oz=new Set(nz);function sz(t){return typeof t=="string"&&oz.has(t)}zo.isJSONType=sz;function iz(){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:{}}}zo.getRules=iz});var Tf=Z(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});nn.shouldUseRule=nn.shouldUseGroup=nn.schemaHasRulesForType=void 0;function az({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Kx(t,n)}nn.schemaHasRulesForType=az;function Kx(t,e){return e.rules.some(r=>Wx(t,r))}nn.shouldUseGroup=Kx;function Wx(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))}nn.shouldUseRule=Wx});var ri=Z(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.reportTypeError=ht.checkDataTypes=ht.checkDataType=ht.coerceAndCheckDataType=ht.getJSONTypes=ht.getSchemaTypes=ht.DataType=void 0;var cz=Sf(),lz=Tf(),uz=ti(),de=he(),Gx=Se(),jo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(jo||(ht.DataType=jo={}));function dz(t){let e=Jx(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}ht.getSchemaTypes=dz;function Jx(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(cz.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ht.getJSONTypes=Jx;function pz(t,e){let{gen:r,data:n,opts:o}=t,s=hz(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,lz.schemaHasRulesForType)(t,e[0]));if(i){let a=Rf(e,n,o.strictNumbers,jo.Wrong);r.if(a,()=>{s.length?fz(t,e,s):Pf(t)})}return i}ht.coerceAndCheckDataType=pz;var Yx=new Set(["string","number","integer","boolean","null"]);function hz(t,e){return e?t.filter(r=>Yx.has(r)||e==="array"&&r==="array"):[]}function fz(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,de._)`typeof ${o}`),a=n.let("coerced",(0,de._)`undefined`);s.coerceTypes==="array"&&n.if((0,de._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,de._)`${o}[0]`).assign(i,(0,de._)`typeof ${o}`).if(Rf(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,de._)`${a} !== undefined`);for(let l of r)(Yx.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),Pf(t),n.endIf(),n.if((0,de._)`${a} !== undefined`,()=>{n.assign(o,a),mz(t,a)});function c(l){switch(l){case"string":n.elseIf((0,de._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,de._)`"" + ${o}`).elseIf((0,de._)`${o} === null`).assign(a,(0,de._)`""`);return;case"number":n.elseIf((0,de._)`${i} == "boolean" || ${o} === null
2035
2042
  || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,de._)`+${o}`);return;case"integer":n.elseIf((0,de._)`${i} === "boolean" || ${o} === null
2036
2043
  || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,de._)`+${o}`);return;case"boolean":n.elseIf((0,de._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,de._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,de._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,de._)`${i} === "string" || ${i} === "number"
2037
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,de._)`[${o}]`)}}}function lz({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,de._)`${e} !== undefined`,()=>t.assign((0,de._)`${e}[${r}]`,n))}function Sf(t,e,r,n=jo.Correct){let o=n===jo.Correct?de.operators.EQ:de.operators.NEQ,s;switch(t){case"null":return(0,de._)`${e} ${o} null`;case"array":s=(0,de._)`Array.isArray(${e})`;break;case"object":s=(0,de._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,de._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,de._)`typeof ${e} ${o} ${t}`}return n===jo.Correct?s:(0,de.not)(s);function i(a=de.nil){return(0,de.and)((0,de._)`typeof ${e} == "number"`,a,r?(0,de._)`isFinite(${e})`:de.nil)}}ht.checkDataType=Sf;function Tf(t,e,r,n){if(t.length===1)return Sf(t[0],e,r,n);let o,s=(0,Vx.toHash)(t);if(s.array&&s.object){let i=(0,de._)`typeof ${e} != "object"`;o=s.null?i:(0,de._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=de.nil;s.number&&delete s.integer;for(let i in s)o=(0,de.and)(o,Sf(i,e,r,n));return o}ht.checkDataTypes=Tf;var uz={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,de._)`{type: ${t}}`:(0,de._)`{type: ${e}}`};function Ef(t){let e=dz(t);(0,oz.reportError)(e,uz)}ht.reportTypeError=Ef;function dz(t){let{gen:e,data:r,schema:n}=t,o=(0,Vx.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Jx=Z(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});Rc.assignDefaults=void 0;var Lo=he(),pz=Se();function hz(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Gx(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Gx(t,s,o.default))}Rc.assignDefaults=hz;function Gx(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Lo._)`${s}${(0,Lo.getProperty)(e)}`;if(o){(0,pz.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Lo._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Lo._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Lo._)`${a} = ${(0,Lo.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=he(),Rf=Se(),on=zr(),fz=Se();function mz(t,e){let{gen:r,data:n,it:o}=t;r.if(Af(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Le._)`${e}`},!0),t.error()})}Ie.checkReportMissingProp=mz;function gz({gen:t,data:e,it:{opts:r}},n,o){return(0,Le.or)(...n.map(s=>(0,Le.and)(Af(t,e,s,r.ownProperties),(0,Le._)`${o} = ${s}`)))}Ie.checkMissingProp=gz;function yz(t,e){t.setParams({missingProperty:e},!0),t.error()}Ie.reportMissingProp=yz;function Yx(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Le._)`Object.prototype.hasOwnProperty`})}Ie.hasPropFunc=Yx;function Pf(t,e,r){return(0,Le._)`${Yx(t)}.call(${e}, ${r})`}Ie.isOwnProperty=Pf;function bz(t,e,r,n){let o=(0,Le._)`${e}${(0,Le.getProperty)(r)} !== undefined`;return n?(0,Le._)`${o} && ${Pf(t,e,r)}`:o}Ie.propertyInData=bz;function Af(t,e,r,n){let o=(0,Le._)`${e}${(0,Le.getProperty)(r)} === undefined`;return n?(0,Le.or)(o,(0,Le.not)(Pf(t,e,r))):o}Ie.noPropertyInData=Af;function Xx(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Ie.allSchemaProperties=Xx;function wz(t,e){return Xx(e).filter(r=>!(0,Rf.alwaysValidSchema)(t,e[r]))}Ie.schemaProperties=wz;function vz({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,p=[[on.default.instancePath,(0,Le.strConcat)(on.default.instancePath,s)],[on.default.parentData,i.parentData],[on.default.parentDataProperty,i.parentDataProperty],[on.default.rootData,on.default.rootData]];i.opts.dynamicRef&&p.push([on.default.dynamicAnchors,on.default.dynamicAnchors]);let w=(0,Le._)`${u}, ${r.object(...p)}`;return c!==Le.nil?(0,Le._)`${a}.call(${c}, ${w})`:(0,Le._)`${a}(${w})`}Ie.callValidateCode=vz;var _z=(0,Le._)`new RegExp`;function xz({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"?_z:(0,fz.useFunc)(t,o)}(${r}, ${n})`})}Ie.usePattern=xz;function kz(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:Rf.Type.Num},s),e.if((0,Le.not)(s),a)})}}Ie.validateArray=kz;function $z(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,Rf.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=$z});var tk=Z(br=>{"use strict";Object.defineProperty(br,"__esModule",{value:!0});br.validateKeywordUsage=br.validSchemaType=br.funcKeywordCode=br.macroKeywordCode=void 0;var vt=he(),Vn=zr(),Sz=Vt(),Tz=ti();function Ez(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=ek(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=r.name("valid");t.subschema({schema:a,schemaPath:vt.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}br.macroKeywordCode=Ez;function Rz(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;Az(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,u=ek(n,o,l),p=n.let("valid");t.block$data(p,w),t.ok((r=e.valid)!==null&&r!==void 0?r:p);function w(){if(e.errors===!1)b(),e.modifying&&Qx(t),$(()=>t.error());else{let E=e.async?f():h();e.modifying&&Qx(t),$(()=>Pz(t,E))}}function f(){let E=n.let("ruleErrs",null);return n.try(()=>b((0,vt._)`await `),P=>n.assign(p,!1).if((0,vt._)`${P} instanceof ${c.ValidationError}`,()=>n.assign(E,(0,vt._)`${P}.errors`),()=>n.throw(P))),E}function h(){let E=(0,vt._)`${u}.errors`;return n.assign(E,null),b(vt.nil),E}function b(E=e.async?(0,vt._)`await `:vt.nil){let P=c.opts.passContext?Vn.default.this:Vn.default.self,z=!("compile"in e&&!a||e.schema===!1);n.assign(p,(0,vt._)`${E}${(0,Sz.callValidateCode)(t,u,P,z)}`,e.modifying)}function $(E){var P;n.if((0,vt.not)((P=e.valid)!==null&&P!==void 0?P:p),E)}}br.funcKeywordCode=Rz;function Qx(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,vt._)`${n.parentData}[${n.parentDataProperty}]`))}function Pz(t,e){let{gen:r}=t;r.if((0,vt._)`Array.isArray(${e})`,()=>{r.assign(Vn.default.vErrors,(0,vt._)`${Vn.default.vErrors} === null ? ${e} : ${Vn.default.vErrors}.concat(${e})`).assign(Vn.default.errors,(0,vt._)`${Vn.default.vErrors}.length`),(0,Tz.extendErrors)(t)},()=>t.error())}function Az({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function ek(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,vt.stringify)(r)})}function Iz(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")}br.validSchemaType=Iz;function Oz({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)}}br.validateKeywordUsage=Oz});var nk=Z(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.extendSubschemaMode=sn.extendSubschemaData=sn.getSubschema=void 0;var wr=he(),rk=Se();function Cz(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,wr._)`${t.schemaPath}${(0,wr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,wr._)`${t.schemaPath}${(0,wr.getProperty)(e)}${(0,wr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,rk.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')}sn.getSubschema=Cz;function Nz(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:p}=e,w=a.let("data",(0,wr._)`${e.data}${(0,wr.getProperty)(r)}`,!0);c(w),t.errorPath=(0,wr.str)`${l}${(0,rk.getErrorPath)(r,n,p.jsPropertySyntax)}`,t.parentDataProperty=(0,wr._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(o!==void 0){let l=o instanceof wr.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]}}sn.extendSubschemaData=Nz;function zz(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}sn.extendSubschemaMode=zz});var If=Z((GV,ok)=>{"use strict";ok.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 ik=Z((JV,sk)=>{"use strict";var an=sk.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)};an.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};an.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};an.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};an.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 p=n[u];if(Array.isArray(p)){if(u in an.arrayKeywords)for(var w=0;w<p.length;w++)Pc(t,e,r,p[w],o+"/"+u+"/"+w,s,o,u,n,w)}else if(u in an.propsKeywords){if(p&&typeof p=="object")for(var f in p)Pc(t,e,r,p[f],o+"/"+u+"/"+jz(f),s,o,u,n,f)}else(u in an.keywords||t.allKeys&&!(u in an.skipKeywords))&&Pc(t,e,r,p,o+"/"+u,s,o,u,n)}r(n,o,s,i,a,c,l)}}function jz(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var ni=Z(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.getSchemaRefs=At.resolveUrl=At.normalizeId=At._getFullPath=At.getFullPath=At.inlineRef=void 0;var Lz=Se(),Dz=If(),Mz=ik(),Uz=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function qz(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Of(t):e?ak(t)<=e:!1}At.inlineRef=qz;var Bz=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Of(t){for(let e in t){if(Bz.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Of)||typeof r=="object"&&Of(r))return!0}return!1}function ak(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!Uz.has(r)&&(typeof t[r]=="object"&&(0,Lz.eachItem)(t[r],n=>e+=ak(n)),e===1/0))return 1/0}return e}function ck(t,e="",r){r!==!1&&(e=Do(e));let n=t.parse(e);return lk(t,n)}At.getFullPath=ck;function lk(t,e){return t.serialize(e).split("#")[0]+"#"}At._getFullPath=lk;var Zz=/#\/?$/;function Do(t){return t?t.replace(Zz,""):""}At.normalizeId=Do;function Fz(t,e,r){return r=Do(r),t.resolve(e,r)}At.resolveUrl=Fz;var Hz=/^[a-z_][-a-z0-9._]*$/i;function Vz(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Do(t[r]||e),s={"":o},i=ck(n,o,!1),a={},c=new Set;return Mz(t,{allKeys:!0},(p,w,f,h)=>{if(h===void 0)return;let b=i+w,$=s[h];typeof p[r]=="string"&&($=E.call(this,p[r])),P.call(this,p.$anchor),P.call(this,p.$dynamicAnchor),s[w]=$;function E(z){let B=this.opts.uriResolver.resolve;if(z=Do($?B($,z):z),c.has(z))throw u(z);c.add(z);let W=this.refs[z];return typeof W=="string"&&(W=this.refs[W]),typeof W=="object"?l(p,W.schema,z):z!==Do(b)&&(z[0]==="#"?(l(p,a[z],z),a[z]=p):this.refs[z]=b),z}function P(z){if(typeof z=="string"){if(!Hz.test(z))throw new Error(`invalid anchor "${z}"`);E.call(this,`#${z}`)}}}),a;function l(p,w,f){if(w!==void 0&&!Dz(p,w))throw u(f)}function u(p){return new Error(`reference "${p}" resolves to more than one schema`)}}At.getSchemaRefs=Vz});var ii=Z(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.getData=cn.KeywordCxt=cn.validateFunctionCode=void 0;var fk=Zx(),uk=ri(),Nf=$f(),Ac=ri(),Kz=Jx(),si=tk(),Cf=nk(),X=he(),ce=zr(),Wz=ni(),jr=Se(),oi=ti();function Gz(t){if(yk(t)&&(bk(t),gk(t))){Xz(t);return}mk(t,()=>(0,fk.topBoolOrEmptySchema)(t))}cn.validateFunctionCode=Gz;function mk({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,X._)`${ce.default.data}, ${ce.default.valCxt}`,n.$async,()=>{t.code((0,X._)`"use strict"; ${dk(r,o)}`),Yz(t,o),t.code(s)}):t.func(e,(0,X._)`${ce.default.data}, ${Jz(o)}`,n.$async,()=>t.code(dk(r,o)).code(s))}function Jz(t){return(0,X._)`{${ce.default.instancePath}="", ${ce.default.parentData}, ${ce.default.parentDataProperty}, ${ce.default.rootData}=${ce.default.data}${t.dynamicRef?(0,X._)`, ${ce.default.dynamicAnchors}={}`:X.nil}}={}`}function Yz(t,e){t.if(ce.default.valCxt,()=>{t.var(ce.default.instancePath,(0,X._)`${ce.default.valCxt}.${ce.default.instancePath}`),t.var(ce.default.parentData,(0,X._)`${ce.default.valCxt}.${ce.default.parentData}`),t.var(ce.default.parentDataProperty,(0,X._)`${ce.default.valCxt}.${ce.default.parentDataProperty}`),t.var(ce.default.rootData,(0,X._)`${ce.default.valCxt}.${ce.default.rootData}`),e.dynamicRef&&t.var(ce.default.dynamicAnchors,(0,X._)`${ce.default.valCxt}.${ce.default.dynamicAnchors}`)},()=>{t.var(ce.default.instancePath,(0,X._)`""`),t.var(ce.default.parentData,(0,X._)`undefined`),t.var(ce.default.parentDataProperty,(0,X._)`undefined`),t.var(ce.default.rootData,ce.default.data),e.dynamicRef&&t.var(ce.default.dynamicAnchors,(0,X._)`{}`)})}function Xz(t){let{schema:e,opts:r,gen:n}=t;mk(t,()=>{r.$comment&&e.$comment&&vk(t),nj(t),n.let(ce.default.vErrors,null),n.let(ce.default.errors,0),r.unevaluated&&Qz(t),wk(t),ij(t)})}function Qz(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,X._)`${r}.evaluated`),e.if((0,X._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,X._)`${t.evaluated}.props`,(0,X._)`undefined`)),e.if((0,X._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,X._)`${t.evaluated}.items`,(0,X._)`undefined`))}function dk(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,X._)`/*# sourceURL=${r} */`:X.nil}function ej(t,e){if(yk(t)&&(bk(t),gk(t))){tj(t,e);return}(0,fk.boolOrEmptySchema)(t,e)}function gk({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 yk(t){return typeof t.schema!="boolean"}function tj(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&vk(t),oj(t),sj(t);let s=n.const("_errs",ce.default.errors);wk(t,s),n.var(e,(0,X._)`${s} === ${ce.default.errors}`)}function bk(t){(0,jr.checkUnknownRules)(t),rj(t)}function wk(t,e){if(t.opts.jtd)return pk(t,[],!1,e);let r=(0,uk.getSchemaTypes)(t.schema),n=(0,uk.coerceAndCheckDataType)(t,r);pk(t,r,!n,e)}function rj(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,jr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function nj(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,jr.checkStrictMode)(t,"default is ignored in the schema root")}function oj(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,Wz.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function sj(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function vk({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,X._)`${ce.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,X.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,X._)`${ce.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function ij(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,X._)`${ce.default.errors} === 0`,()=>e.return(ce.default.data),()=>e.throw((0,X._)`new ${o}(${ce.default.vErrors})`)):(e.assign((0,X._)`${n}.errors`,ce.default.vErrors),s.unevaluated&&aj(t),e.return((0,X._)`${ce.default.errors} === 0`))}function aj({gen:t,evaluated:e,props:r,items:n}){r instanceof X.Name&&t.assign((0,X._)`${e}.props`,r),n instanceof X.Name&&t.assign((0,X._)`${e}.items`,n)}function pk(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,jr.schemaHasRulesButRef)(s,u))){o.block(()=>xk(t,"$ref",u.all.$ref.definition));return}c.jtd||cj(t,e),o.block(()=>{for(let w of u.rules)p(w);p(u.post)});function p(w){(0,Nf.shouldUseGroup)(s,w)&&(w.type?(o.if((0,Ac.checkDataType)(w.type,i,c.strictNumbers)),hk(t,w),e.length===1&&e[0]===w.type&&r&&(o.else(),(0,Ac.reportTypeError)(t)),o.endIf()):hk(t,w),a||o.if((0,X._)`${ce.default.errors} === ${n||0}`))}}function hk(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,Kz.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Nf.shouldUseRule)(n,s)&&xk(t,s.keyword,s.definition,e.type)})}function cj(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(lj(t,e),t.opts.allowUnionTypes||uj(t,e),dj(t,t.dataTypes))}function lj(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{_k(t.dataTypes,r)||zf(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),hj(t,e)}}function uj(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&zf(t,"use allowUnionTypes to allow union type keyword")}function dj(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Nf.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>pj(e,i))&&zf(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function pj(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function _k(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function hj(t,e){let r=[];for(let n of t.dataTypes)_k(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function zf(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,jr.checkStrictMode)(t,e,t.opts.strictTypes)}var Ic=class{constructor(e,r,n){if((0,si.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,jr.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",kk(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,si.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",ce.default.errors))}result(e,r,n){this.failResult((0,X.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,X.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,X._)`${r} !== undefined && (${(0,X.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?oi.reportExtraError:oi.reportError)(this,this.def.error,r)}$dataError(){(0,oi.reportError)(this,this.def.$dataError||oi.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,oi.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=X.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=X.nil,r=X.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,X.or)((0,X._)`${o} === undefined`,r)),e!==X.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==X.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,X.or)(i(),a());function i(){if(n.length){if(!(r instanceof X.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,X._)`${(0,Ac.checkDataTypes)(c,r,s.opts.strictNumbers,Ac.DataType.Wrong)}`}return X.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,X._)`!${c}(${r})`}return X.nil}}subschema(e,r){let n=(0,Cf.getSubschema)(this.it,e);(0,Cf.extendSubschemaData)(n,this.it,e),(0,Cf.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return ej(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=jr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=jr.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,X.Name)),!0}};cn.KeywordCxt=Ic;function xk(t,e,r,n){let o=new Ic(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,si.funcKeywordCode)(o,r):"macro"in r?(0,si.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,si.funcKeywordCode)(o,r)}var fj=/^\/(?:[^~]|~0|~1)*$/,mj=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function kk(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return ce.default.rootData;if(t[0]==="/"){if(!fj.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ce.default.rootData}else{let l=mj.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,X._)`${s}${(0,X.getProperty)((0,jr.unescapeJsonPointer)(l))}`,i=(0,X._)`${i} && ${s}`);return i;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}cn.getData=kk});var Oc=Z(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});var jf=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Lf.default=jf});var ai=Z(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});var Df=ni(),Mf=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Df.resolveUrl)(e,r,n),this.missingSchema=(0,Df.normalizeId)((0,Df.getFullPath)(e,this.missingRef))}};Uf.default=Mf});var Nc=Z(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.resolveSchema=Kt.getCompilingSchema=Kt.resolveRef=Kt.compileSchema=Kt.SchemaEnv=void 0;var sr=he(),gj=Oc(),Kn=zr(),ir=ni(),$k=Se(),yj=ii(),Mo=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,ir.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=Mo;function Bf(t){let e=Sk.call(this,t);if(e)return e;let r=(0,ir.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new sr.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:gj.default,code:(0,sr._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:Kn.default.data,parentData:Kn.default.parentData,parentDataProperty:Kn.default.parentDataProperty,dataNames:[Kn.default.data],dataPathArr:[sr.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,sr.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:sr.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,sr._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,yj.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let p=i.toString();u=`${i.scopeRefs(Kn.default.scope)}return ${p}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let f=new Function(`${Kn.default.self}`,`${Kn.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:p,scopeValues:i._values}),this.opts.unevaluated){let{props:h,items:b}=l;f.evaluated={props:h instanceof sr.Name?void 0:h,items:b instanceof sr.Name?void 0:b,dynamicProps:h instanceof sr.Name,dynamicItems:b instanceof sr.Name},f.source&&(f.source.evaluated=(0,sr.stringify)(f.evaluated))}return t.validate=f,t}catch(p){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),p}finally{this._compilations.delete(t)}}Kt.compileSchema=Bf;function bj(t,e,r){var n;r=(0,ir.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=_j.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 Mo({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=wj.call(this,s)}Kt.resolveRef=bj;function wj(t){return(0,ir.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Bf.call(this,t)}function Sk(t){for(let e of this._compilations)if(vj(e,t))return e}Kt.getCompilingSchema=Sk;function vj(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function _j(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Cc.call(this,t,e)}function Cc(t,e){let r=this.opts.uriResolver.parse(e),n=(0,ir._getFullPath)(this.opts.uriResolver,r),o=(0,ir.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return qf.call(this,r,t);let s=(0,ir.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Cc.call(this,t,i);return typeof a?.schema!="object"?void 0:qf.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Bf.call(this,i),s===(0,ir.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,ir.resolveUrl)(this.opts.uriResolver,o,l)),new Mo({schema:a,schemaId:c,root:t,baseId:o})}return qf.call(this,r,i)}}Kt.resolveSchema=Cc;var xj=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function qf(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,$k.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!xj.has(a)&&l&&(e=(0,ir.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,$k.schemaHasRulesButRef)(r,this.RULES)){let a=(0,ir.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Cc.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Mo({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Tk=Z((r9,kj)=>{kj.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 Hf=Z((n9,Ok)=>{"use strict";var $j=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Rk=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),Zf=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Pk=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Sj=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Ff(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 Tj=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Ek(t){return t.length=0,!0}function Ej(t,e,r){if(t.length){let n=Ff(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function Rj(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=Ej;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=Ek}else{o.push(l);continue}}return o.length&&(a===Ek?r.zone=o.join(""):i?n.push(o.join("")):n.push(Ff(o))),r.address=n.join(""),r}function Ak(t){if(Pj(t,":")<2)return{host:t,isIPV6:!1};let e=Rj(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 Pj(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function Aj(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 Ij={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Oj=/[@/?#:]/g,Cj=/[@/?#]/g;function Ik(t,e){let r=e?Cj:Oj;return r.lastIndex=0,t.replace(r,n=>Ij[n])}function Nj(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(Zf(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Pk(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function zj(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(Zf(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Pk(s)?e+=s:e+="%"+o,r+=2;continue}}Sj(t[r])?e+=t[r]:e+=escape(t[r])}return e}function jj(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(Zf(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function Lj(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!Rk(r)){let n=Ak(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Ik(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}Ok.exports={nonSimpleDomain:Tj,recomposeAuthority:Lj,reescapeHostDelimiters:Ik,normalizePercentEncoding:Nj,normalizePathEncoding:zj,escapePreservingEscapes:jj,removeDotSegments:Aj,isIPv4:Rk,isUUID:$j,normalizeIPv6:Ak,stringArrayToHexStripped:Ff}});var Lk=Z((o9,jk)=>{"use strict";var{isUUID:Dj}=Hf(),Mj=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Uj=["http","https","ws","wss","urn","urn:uuid"];function qj(t){return Uj.indexOf(t)!==-1}function Vf(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 Ck(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Nk(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 Bj(t){return t.secure=Vf(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function Zj(t){if((t.port===(Vf(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 Fj(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(Mj);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=Kf(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function Hj(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=Kf(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 Vj(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!Dj(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Kj(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var zk={scheme:"http",domainHost:!0,parse:Ck,serialize:Nk},Wj={scheme:"https",domainHost:zk.domainHost,parse:Ck,serialize:Nk},zc={scheme:"ws",domainHost:!0,parse:Bj,serialize:Zj},Gj={scheme:"wss",domainHost:zc.domainHost,parse:zc.parse,serialize:zc.serialize},Jj={scheme:"urn",parse:Fj,serialize:Hj,skipNormalize:!0},Yj={scheme:"urn:uuid",parse:Vj,serialize:Kj,skipNormalize:!0},jc={http:zk,https:Wj,ws:zc,wss:Gj,urn:Jj,"urn:uuid":Yj};Object.setPrototypeOf(jc,null);function Kf(t){return t&&(jc[t]||jc[t.toLowerCase()])||void 0}jk.exports={wsIsSecure:Vf,SCHEMES:jc,isValidSchemeName:qj,getSchemeHandler:Kf}});var Bk=Z((s9,Mc)=>{"use strict";var{normalizeIPv6:Xj,removeDotSegments:ci,recomposeAuthority:Qj,normalizePercentEncoding:eL,normalizePathEncoding:tL,escapePreservingEscapes:rL,reescapeHostDelimiters:nL,isIPv4:oL,nonSimpleDomain:sL}=Hf(),{SCHEMES:iL,getSchemeHandler:Mk}=Lk();function aL(t,e){return typeof t=="string"?t=fL(t,e):typeof t=="object"&&(t=Dc(Wn(t,e),e)),t}function cL(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=Lc(t,n),{parsed:i,malformedAuthorityOrPort:a}=Lc(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let c=Uk(o,i,n,!0);return n.skipEscape=!0,Wn(c,n)}function Uk(t,e,r,n){let o={};return n||(t=Dc(Wn(t,r),r),e=Dc(Wn(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=ci(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=ci(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=ci(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=ci(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 lL(t,e,r){let n=Dk(t,r),o=Dk(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Wn(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=Mk(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=eL(r.path):(r.path=rL(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=Qj(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=ci(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 uL=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,dL=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,pL=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function hL(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 Lc(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(dL);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(pL);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(uL);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=hL(n,c);if(l!==void 0&&(n.error=n.error||l,o=!0),n.host)if(oL(n.host)===!1){let w=Xj(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=Mk(r.scheme||n.scheme);if(!r.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(r.domainHost||u&&u.domainHost)&&s===!1&&sL(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(p){n.error=n.error||"Host's domain name can not be converted to ASCII: "+p}if((!u||u&&!u.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=nL(unescape(n.host),s))),n.path&&(n.path=tL(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 Dc(t,e){return Lc(t,e).parsed}function fL(t,e){return qk(t,e).normalized}function qk(t,e){let{parsed:r,malformedAuthorityOrPort:n}=Lc(t,e);return{normalized:n?t:Wn(r,e),malformedAuthorityOrPort:n}}function Dk(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=qk(t,e);return n?void 0:r}if(typeof t=="object")return Wn(t,e)}var Wf={SCHEMES:iL,normalize:aL,resolve:cL,resolveComponent:Uk,equal:lL,serialize:Wn,parse:Dc};Mc.exports=Wf;Mc.exports.default=Wf;Mc.exports.fastUri=Wf});var Fk=Z(Gf=>{"use strict";Object.defineProperty(Gf,"__esModule",{value:!0});var Zk=Bk();Zk.code='require("ajv/dist/runtime/uri").default';Gf.default=Zk});var Xk=Z(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.CodeGen=at.Name=at.nil=at.stringify=at.str=at._=at.KeywordCxt=void 0;var mL=ii();Object.defineProperty(at,"KeywordCxt",{enumerable:!0,get:function(){return mL.KeywordCxt}});var Uo=he();Object.defineProperty(at,"_",{enumerable:!0,get:function(){return Uo._}});Object.defineProperty(at,"str",{enumerable:!0,get:function(){return Uo.str}});Object.defineProperty(at,"stringify",{enumerable:!0,get:function(){return Uo.stringify}});Object.defineProperty(at,"nil",{enumerable:!0,get:function(){return Uo.nil}});Object.defineProperty(at,"Name",{enumerable:!0,get:function(){return Uo.Name}});Object.defineProperty(at,"CodeGen",{enumerable:!0,get:function(){return Uo.CodeGen}});var gL=Oc(),Gk=ai(),yL=kf(),li=Nc(),bL=he(),ui=ni(),Uc=ri(),Yf=Se(),Hk=Tk(),wL=Fk(),Jk=(t,e)=>new RegExp(t,e);Jk.code="new RegExp";var vL=["removeAdditional","useDefaults","coerceTypes"],_L=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),xL={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."},kL={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Vk=200;function $L(t){var e,r,n,o,s,i,a,c,l,u,p,w,f,h,b,$,E,P,z,B,W,Ve,Ye,Gt,Dr;let pn=t.strict,Mr=(e=t.code)===null||e===void 0?void 0:e.optimize,lr=Mr===!0||Mr===void 0?1:Mr||0,$i=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Jk,pl=(o=t.uriResolver)!==null&&o!==void 0?o:wL.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:pn)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:pn)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:pn)!==null&&u!==void 0?u:"log",strictTuples:(w=(p=t.strictTuples)!==null&&p!==void 0?p:pn)!==null&&w!==void 0?w:"log",strictRequired:(h=(f=t.strictRequired)!==null&&f!==void 0?f:pn)!==null&&h!==void 0?h:!1,code:t.code?{...t.code,optimize:lr,regExp:$i}:{optimize:lr,regExp:$i},loopRequired:(b=t.loopRequired)!==null&&b!==void 0?b:Vk,loopEnum:($=t.loopEnum)!==null&&$!==void 0?$:Vk,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:(B=t.schemaId)!==null&&B!==void 0?B:"$id",addUsedSchema:(W=t.addUsedSchema)!==null&&W!==void 0?W:!0,validateSchema:(Ve=t.validateSchema)!==null&&Ve!==void 0?Ve:!0,validateFormats:(Ye=t.validateFormats)!==null&&Ye!==void 0?Ye:!0,unicodeRegExp:(Gt=t.unicodeRegExp)!==null&&Gt!==void 0?Gt:!0,int32range:(Dr=t.int32range)!==null&&Dr!==void 0?Dr:!0,uriResolver:pl}}var di=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,...$L(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new bL.ValueScope({scope:{},prefixes:_L,es5:r,lines:n}),this.logger=AL(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,yL.getRules)(),Kk.call(this,xL,e,"NOT SUPPORTED"),Kk.call(this,kL,e,"DEPRECATED","warn"),this._metaOpts=RL.call(this),e.formats&&TL.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&EL.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),SL.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=Hk;n==="id"&&(o={...Hk},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,p){await s.call(this,u.$schema);let w=this._addSchema(u,p);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(p){if(!(p instanceof Gk.default))throw p;return a.call(this,p),await c.call(this,p.missingSchema),i.call(this,u)}}function a({missingSchema:u,missingRef:p}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${p} cannot be resolved`)}async function c(u){let p=await l.call(this,u);this.refs[u]||await s.call(this,p.$schema),this.refs[u]||this.addSchema(p,u,r)}async function l(u){let p=this._loading[u];if(p)return p;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,ui.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=Wk.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new li.SchemaEnv({schema:{},schemaId:n});if(r=li.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=Wk.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,ui.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(OL.call(this,n,r),!r)return(0,Yf.eachItem)(n,s=>Jf.call(this,s)),this;NL.call(this,r);let o={...r,type:(0,Uc.getJSONTypes)(r.type),schemaType:(0,Uc.getJSONTypes)(r.schemaType)};return(0,Yf.eachItem)(n,o.type.length===0?s=>Jf.call(this,s,o):s=>o.type.forEach(i=>Jf.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]=Yk(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,ui.normalizeId)(i||n);let l=ui.getSchemaRefs.call(this,e,n);return c=new li.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):li.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{li.compileSchema.call(this,e)}finally{this.opts=r}}};di.ValidationError=gL.default;di.MissingRefError=Gk.default;at.default=di;function Kk(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 Wk(t){return t=(0,ui.normalizeId)(t),this.schemas[t]||this.refs[t]}function SL(){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 TL(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function EL(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 RL(){let t={...this.opts};for(let e of vL)delete t[e];return t}var PL={log(){},warn(){},error(){}};function AL(t){if(t===!1)return PL;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 IL=/^[a-z_$][a-z0-9_$:-]*$/i;function OL(t,e){let{RULES:r}=this;if((0,Yf.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!IL.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 Jf(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,Uc.getJSONTypes)(e.type),schemaType:(0,Uc.getJSONTypes)(e.schemaType)}};e.before?CL.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 CL(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 NL(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Yk(e)),t.validateSchema=this.compile(e,!0))}var zL={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Yk(t){return{anyOf:[t,zL]}}});var Qk=Z(Xf=>{"use strict";Object.defineProperty(Xf,"__esModule",{value:!0});var jL={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Xf.default=jL});var n$=Z(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.callRef=Gn.getValidate=void 0;var LL=ai(),e$=Vt(),It=he(),qo=zr(),t$=Nc(),qc=Se(),DL={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 p();let u=t$.resolveRef.call(c,l,o,r);if(u===void 0)throw new LL.default(n.opts.uriResolver,o,r);if(u instanceof t$.SchemaEnv)return w(u);return f(u);function p(){if(s===l)return Bc(t,i,s,s.$async);let h=e.scopeValue("root",{ref:l});return Bc(t,(0,It._)`${h}.validate`,l,l.$async)}function w(h){let b=r$(t,h);Bc(t,b,h,h.$async)}function f(h){let b=e.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,It.stringify)(h)}:{ref:h}),$=e.name("valid"),E=t.subschema({schema:h,dataTypes:[],schemaPath:It.nil,topSchemaRef:b,errSchemaPath:r},$);t.mergeEvaluated(E),t.ok($)}}};function r$(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,It._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Gn.getValidate=r$;function Bc(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?qo.default.this:It.nil;n?u():p();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=o.let("valid");o.try(()=>{o.code((0,It._)`await ${(0,e$.callValidateCode)(t,e,l)}`),f(e),i||o.assign(h,!0)},b=>{o.if((0,It._)`!(${b} instanceof ${s.ValidationError})`,()=>o.throw(b)),w(b),i||o.assign(h,!1)}),t.ok(h)}function p(){t.result((0,e$.callValidateCode)(t,e,l),()=>f(e),()=>w(e))}function w(h){let b=(0,It._)`${h}.errors`;o.assign(qo.default.vErrors,(0,It._)`${qo.default.vErrors} === null ? ${b} : ${qo.default.vErrors}.concat(${b})`),o.assign(qo.default.errors,(0,It._)`${qo.default.vErrors}.length`)}function f(h){var b;if(!s.opts.unevaluated)return;let $=(b=r?.validate)===null||b===void 0?void 0:b.evaluated;if(s.props!==!0)if($&&!$.dynamicProps)$.props!==void 0&&(s.props=qc.mergeEvaluated.props(o,$.props,s.props));else{let E=o.var("props",(0,It._)`${h}.evaluated.props`);s.props=qc.mergeEvaluated.props(o,E,s.props,It.Name)}if(s.items!==!0)if($&&!$.dynamicItems)$.items!==void 0&&(s.items=qc.mergeEvaluated.items(o,$.items,s.items));else{let E=o.var("items",(0,It._)`${h}.evaluated.items`);s.items=qc.mergeEvaluated.items(o,E,s.items,It.Name)}}}Gn.callRef=Bc;Gn.default=DL});var o$=Z(Qf=>{"use strict";Object.defineProperty(Qf,"__esModule",{value:!0});var ML=Qk(),UL=n$(),qL=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",ML.default,UL.default];Qf.default=qL});var s$=Z(em=>{"use strict";Object.defineProperty(em,"__esModule",{value:!0});var Zc=he(),ln=Zc.operators,Fc={maximum:{okStr:"<=",ok:ln.LTE,fail:ln.GT},minimum:{okStr:">=",ok:ln.GTE,fail:ln.LT},exclusiveMaximum:{okStr:"<",ok:ln.LT,fail:ln.GTE},exclusiveMinimum:{okStr:">",ok:ln.GT,fail:ln.LTE}},BL={message:({keyword:t,schemaCode:e})=>(0,Zc.str)`must be ${Fc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Zc._)`{comparison: ${Fc[t].okStr}, limit: ${e}}`},ZL={keyword:Object.keys(Fc),type:"number",schemaType:"number",$data:!0,error:BL,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Zc._)`${r} ${Fc[e].fail} ${n} || isNaN(${r})`)}};em.default=ZL});var i$=Z(tm=>{"use strict";Object.defineProperty(tm,"__esModule",{value:!0});var pi=he(),FL={message:({schemaCode:t})=>(0,pi.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,pi._)`{multipleOf: ${t}}`},HL={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:FL,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,pi._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,pi._)`${i} !== parseInt(${i})`;t.fail$data((0,pi._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};tm.default=HL});var c$=Z(rm=>{"use strict";Object.defineProperty(rm,"__esModule",{value:!0});function a$(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}rm.default=a$;a$.code='require("ajv/dist/runtime/ucs2length").default'});var l$=Z(nm=>{"use strict";Object.defineProperty(nm,"__esModule",{value:!0});var Jn=he(),VL=Se(),KL=c$(),WL={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Jn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Jn._)`{limit: ${t}}`},GL={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:WL,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Jn.operators.GT:Jn.operators.LT,i=o.opts.unicode===!1?(0,Jn._)`${r}.length`:(0,Jn._)`${(0,VL.useFunc)(t.gen,KL.default)}(${r})`;t.fail$data((0,Jn._)`${i} ${s} ${n}`)}};nm.default=GL});var u$=Z(om=>{"use strict";Object.defineProperty(om,"__esModule",{value:!0});var JL=Vt(),YL=Se(),Bo=he(),XL={message:({schemaCode:t})=>(0,Bo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Bo._)`{pattern: ${t}}`},QL={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:XL,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,Bo._)`new RegExp`:(0,YL.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,Bo._)`${l}(${s}, ${a}).test(${r})`),()=>e.assign(u,!1)),t.fail$data((0,Bo._)`!${u}`)}else{let c=(0,JL.usePattern)(t,o);t.fail$data((0,Bo._)`!${c}.test(${r})`)}}};om.default=QL});var d$=Z(sm=>{"use strict";Object.defineProperty(sm,"__esModule",{value:!0});var hi=he(),e1={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,hi.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,hi._)`{limit: ${t}}`},t1={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:e1,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?hi.operators.GT:hi.operators.LT;t.fail$data((0,hi._)`Object.keys(${r}).length ${o} ${n}`)}};sm.default=t1});var p$=Z(im=>{"use strict";Object.defineProperty(im,"__esModule",{value:!0});var fi=Vt(),mi=he(),r1=Se(),n1={message:({params:{missingProperty:t}})=>(0,mi.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,mi._)`{missingProperty: ${t}}`},o1={keyword:"required",type:"object",schemaType:"array",$data:!0,error:n1,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 f=t.parentSchema.properties,{definedProperties:h}=t.it;for(let b of r)if(f?.[b]===void 0&&!h.has(b)){let $=i.schemaEnv.baseId+i.errSchemaPath,E=`required property "${b}" is not defined at "${$}" (strictRequired)`;(0,r1.checkStrictMode)(i,E,i.opts.strictRequired)}}function l(){if(c||s)t.block$data(mi.nil,p);else for(let f of r)(0,fi.checkReportMissingProp)(t,f)}function u(){let f=e.let("missing");if(c||s){let h=e.let("valid",!0);t.block$data(h,()=>w(f,h)),t.ok(h)}else e.if((0,fi.checkMissingProp)(t,r,f)),(0,fi.reportMissingProp)(t,f),e.else()}function p(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,fi.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function w(f,h){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(h,(0,fi.propertyInData)(e,o,f,a.ownProperties)),e.if((0,mi.not)(h),()=>{t.error(),e.break()})},mi.nil)}}};im.default=o1});var h$=Z(am=>{"use strict";Object.defineProperty(am,"__esModule",{value:!0});var gi=he(),s1={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,gi.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,gi._)`{limit: ${t}}`},i1={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:s1,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?gi.operators.GT:gi.operators.LT;t.fail$data((0,gi._)`${r}.length ${o} ${n}`)}};am.default=i1});var Hc=Z(cm=>{"use strict";Object.defineProperty(cm,"__esModule",{value:!0});var f$=If();f$.code='require("ajv/dist/runtime/equal").default';cm.default=f$});var m$=Z(um=>{"use strict";Object.defineProperty(um,"__esModule",{value:!0});var lm=ri(),ct=he(),a1=Se(),c1=Hc(),l1={message:({params:{i:t,j:e}})=>(0,ct.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,ct._)`{i: ${t}, j: ${e}}`},u1={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:l1,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,lm.getSchemaTypes)(s.items):[];t.block$data(c,u,(0,ct._)`${i} === false`),t.ok(c);function u(){let h=e.let("i",(0,ct._)`${r}.length`),b=e.let("j");t.setParams({i:h,j:b}),e.assign(c,!0),e.if((0,ct._)`${h} > 1`,()=>(p()?w:f)(h,b))}function p(){return l.length>0&&!l.some(h=>h==="object"||h==="array")}function w(h,b){let $=e.name("item"),E=(0,lm.checkDataTypes)(l,$,a.opts.strictNumbers,lm.DataType.Wrong),P=e.const("indices",(0,ct._)`{}`);e.for((0,ct._)`;${h}--;`,()=>{e.let($,(0,ct._)`${r}[${h}]`),e.if(E,(0,ct._)`continue`),l.length>1&&e.if((0,ct._)`typeof ${$} == "string"`,(0,ct._)`${$} += "_"`),e.if((0,ct._)`typeof ${P}[${$}] == "number"`,()=>{e.assign(b,(0,ct._)`${P}[${$}]`),t.error(),e.assign(c,!1).break()}).code((0,ct._)`${P}[${$}] = ${h}`)})}function f(h,b){let $=(0,a1.useFunc)(e,c1.default),E=e.name("outer");e.label(E).for((0,ct._)`;${h}--;`,()=>e.for((0,ct._)`${b} = ${h}; ${b}--;`,()=>e.if((0,ct._)`${$}(${r}[${h}], ${r}[${b}])`,()=>{t.error(),e.assign(c,!1).break(E)})))}}};um.default=u1});var g$=Z(pm=>{"use strict";Object.defineProperty(pm,"__esModule",{value:!0});var dm=he(),d1=Se(),p1=Hc(),h1={message:"must be equal to constant",params:({schemaCode:t})=>(0,dm._)`{allowedValue: ${t}}`},f1={keyword:"const",$data:!0,error:h1,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,dm._)`!${(0,d1.useFunc)(e,p1.default)}(${r}, ${o})`):t.fail((0,dm._)`${s} !== ${r}`)}};pm.default=f1});var y$=Z(hm=>{"use strict";Object.defineProperty(hm,"__esModule",{value:!0});var yi=he(),m1=Se(),g1=Hc(),y1={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,yi._)`{allowedValues: ${t}}`},b1={keyword:"enum",schemaType:"array",$data:!0,error:y1,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,m1.useFunc)(e,g1.default)),u;if(a||n)u=e.let("valid"),t.block$data(u,p);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=e.const("vSchema",s);u=(0,yi.or)(...o.map((h,b)=>w(f,b)))}t.pass(u);function p(){e.assign(u,!1),e.forOf("v",s,f=>e.if((0,yi._)`${l()}(${r}, ${f})`,()=>e.assign(u,!0).break()))}function w(f,h){let b=o[h];return typeof b=="object"&&b!==null?(0,yi._)`${l()}(${r}, ${f}[${h}])`:(0,yi._)`${r} === ${b}`}}};hm.default=b1});var b$=Z(fm=>{"use strict";Object.defineProperty(fm,"__esModule",{value:!0});var w1=s$(),v1=i$(),_1=l$(),x1=u$(),k1=d$(),$1=p$(),S1=h$(),T1=m$(),E1=g$(),R1=y$(),P1=[w1.default,v1.default,_1.default,x1.default,k1.default,$1.default,S1.default,T1.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},E1.default,R1.default];fm.default=P1});var gm=Z(bi=>{"use strict";Object.defineProperty(bi,"__esModule",{value:!0});bi.validateAdditionalItems=void 0;var Yn=he(),mm=Se(),A1={message:({params:{len:t}})=>(0,Yn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Yn._)`{limit: ${t}}`},I1={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:A1,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,mm.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}w$(t,n)}};function w$(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Yn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Yn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,mm.alwaysValidSchema)(i,n)){let l=r.var("valid",(0,Yn._)`${a} <= ${e.length}`);r.if((0,Yn.not)(l),()=>c(l)),t.ok(l)}function c(l){r.forRange("i",e.length,a,u=>{t.subschema({keyword:s,dataProp:u,dataPropType:mm.Type.Num},l),i.allErrors||r.if((0,Yn.not)(l),()=>r.break())})}}bi.validateAdditionalItems=w$;bi.default=I1});var ym=Z(wi=>{"use strict";Object.defineProperty(wi,"__esModule",{value:!0});wi.validateTuple=void 0;var v$=he(),Vc=Se(),O1=Vt(),C1={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return _$(t,"additionalItems",e);r.items=!0,!(0,Vc.alwaysValidSchema)(r,e)&&t.ok((0,O1.validateArray)(t))}};function _$(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;u(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Vc.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,v$._)`${s}.length`);r.forEach((p,w)=>{(0,Vc.alwaysValidSchema)(a,p)||(n.if((0,v$._)`${l} > ${w}`,()=>t.subschema({keyword:i,schemaProp:w,dataProp:w},c)),t.ok(c))});function u(p){let{opts:w,errSchemaPath:f}=a,h=r.length,b=h===p.minItems&&(h===p.maxItems||p[e]===!1);if(w.strictTuples&&!b){let $=`"${i}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,Vc.checkStrictMode)(a,$,w.strictTuples)}}}wi.validateTuple=_$;wi.default=C1});var x$=Z(bm=>{"use strict";Object.defineProperty(bm,"__esModule",{value:!0});var N1=ym(),z1={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,N1.validateTuple)(t,"items")};bm.default=z1});var $$=Z(wm=>{"use strict";Object.defineProperty(wm,"__esModule",{value:!0});var k$=he(),j1=Se(),L1=Vt(),D1=gm(),M1={message:({params:{len:t}})=>(0,k$.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,k$._)`{limit: ${t}}`},U1={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:M1,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,j1.alwaysValidSchema)(n,e)&&(o?(0,D1.validateAdditionalItems)(t,o):t.ok((0,L1.validateArray)(t)))}};wm.default=U1});var S$=Z(vm=>{"use strict";Object.defineProperty(vm,"__esModule",{value:!0});var Wt=he(),Kc=Se(),q1={message:({params:{min:t,max:e}})=>e===void 0?(0,Wt.str)`must contain at least ${t} valid item(s)`:(0,Wt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Wt._)`{minContains: ${t}}`:(0,Wt._)`{minContains: ${t}, maxContains: ${e}}`},B1={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:q1,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,Wt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Kc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Kc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Kc.alwaysValidSchema)(s,r)){let b=(0,Wt._)`${u} >= ${i}`;a!==void 0&&(b=(0,Wt._)`${b} && ${u} <= ${a}`),t.pass(b);return}s.items=!0;let p=e.name("valid");a===void 0&&i===1?f(p,()=>e.if(p,()=>e.break())):i===0?(e.let(p,!0),a!==void 0&&e.if((0,Wt._)`${o}.length > 0`,w)):(e.let(p,!1),w()),t.result(p,()=>t.reset());function w(){let b=e.name("_valid"),$=e.let("count",0);f(b,()=>e.if(b,()=>h($)))}function f(b,$){e.forRange("i",0,u,E=>{t.subschema({keyword:"contains",dataProp:E,dataPropType:Kc.Type.Num,compositeRule:!0},b),$()})}function h(b){e.code((0,Wt._)`${b}++`),a===void 0?e.if((0,Wt._)`${b} >= ${i}`,()=>e.assign(p,!0).break()):(e.if((0,Wt._)`${b} > ${a}`,()=>e.assign(p,!1).break()),i===1?e.assign(p,!0):e.if((0,Wt._)`${b} >= ${i}`,()=>e.assign(p,!0)))}}};vm.default=B1});var R$=Z(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.validateSchemaDeps=vr.validatePropertyDeps=vr.error=void 0;var _m=he(),Z1=Se(),vi=Vt();vr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,_m.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,_m._)`{property: ${t},
2044
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,de._)`[${o}]`)}}}function mz({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,de._)`${e} !== undefined`,()=>t.assign((0,de._)`${e}[${r}]`,n))}function Ef(t,e,r,n=jo.Correct){let o=n===jo.Correct?de.operators.EQ:de.operators.NEQ,s;switch(t){case"null":return(0,de._)`${e} ${o} null`;case"array":s=(0,de._)`Array.isArray(${e})`;break;case"object":s=(0,de._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,de._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,de._)`typeof ${e} ${o} ${t}`}return n===jo.Correct?s:(0,de.not)(s);function i(a=de.nil){return(0,de.and)((0,de._)`typeof ${e} == "number"`,a,r?(0,de._)`isFinite(${e})`:de.nil)}}ht.checkDataType=Ef;function Rf(t,e,r,n){if(t.length===1)return Ef(t[0],e,r,n);let o,s=(0,Gx.toHash)(t);if(s.array&&s.object){let i=(0,de._)`typeof ${e} != "object"`;o=s.null?i:(0,de._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=de.nil;s.number&&delete s.integer;for(let i in s)o=(0,de.and)(o,Ef(i,e,r,n));return o}ht.checkDataTypes=Rf;var gz={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,de._)`{type: ${t}}`:(0,de._)`{type: ${e}}`};function Pf(t){let e=yz(t);(0,uz.reportError)(e,gz)}ht.reportTypeError=Pf;function yz(t){let{gen:e,data:r,schema:n}=t,o=(0,Gx.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Qx=Z(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});Ac.assignDefaults=void 0;var Lo=he(),bz=Se();function wz(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Xx(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Xx(t,s,o.default))}Ac.assignDefaults=wz;function Xx(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Lo._)`${s}${(0,Lo.getProperty)(e)}`;if(o){(0,bz.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Lo._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Lo._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Lo._)`${a} = ${(0,Lo.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=he(),Af=Se(),on=zr(),vz=Se();function _z(t,e){let{gen:r,data:n,it:o}=t;r.if(Of(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Le._)`${e}`},!0),t.error()})}Ie.checkReportMissingProp=_z;function xz({gen:t,data:e,it:{opts:r}},n,o){return(0,Le.or)(...n.map(s=>(0,Le.and)(Of(t,e,s,r.ownProperties),(0,Le._)`${o} = ${s}`)))}Ie.checkMissingProp=xz;function kz(t,e){t.setParams({missingProperty:e},!0),t.error()}Ie.reportMissingProp=kz;function ek(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Le._)`Object.prototype.hasOwnProperty`})}Ie.hasPropFunc=ek;function If(t,e,r){return(0,Le._)`${ek(t)}.call(${e}, ${r})`}Ie.isOwnProperty=If;function $z(t,e,r,n){let o=(0,Le._)`${e}${(0,Le.getProperty)(r)} !== undefined`;return n?(0,Le._)`${o} && ${If(t,e,r)}`:o}Ie.propertyInData=$z;function Of(t,e,r,n){let o=(0,Le._)`${e}${(0,Le.getProperty)(r)} === undefined`;return n?(0,Le.or)(o,(0,Le.not)(If(t,e,r))):o}Ie.noPropertyInData=Of;function tk(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Ie.allSchemaProperties=tk;function Sz(t,e){return tk(e).filter(r=>!(0,Af.alwaysValidSchema)(t,e[r]))}Ie.schemaProperties=Sz;function Tz({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,p=[[on.default.instancePath,(0,Le.strConcat)(on.default.instancePath,s)],[on.default.parentData,i.parentData],[on.default.parentDataProperty,i.parentDataProperty],[on.default.rootData,on.default.rootData]];i.opts.dynamicRef&&p.push([on.default.dynamicAnchors,on.default.dynamicAnchors]);let w=(0,Le._)`${u}, ${r.object(...p)}`;return c!==Le.nil?(0,Le._)`${a}.call(${c}, ${w})`:(0,Le._)`${a}(${w})`}Ie.callValidateCode=Tz;var Ez=(0,Le._)`new RegExp`;function Rz({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"?Ez:(0,vz.useFunc)(t,o)}(${r}, ${n})`})}Ie.usePattern=Rz;function Pz(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:Af.Type.Num},s),e.if((0,Le.not)(s),a)})}}Ie.validateArray=Pz;function Az(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,Af.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=Az});var ok=Z(br=>{"use strict";Object.defineProperty(br,"__esModule",{value:!0});br.validateKeywordUsage=br.validSchemaType=br.funcKeywordCode=br.macroKeywordCode=void 0;var vt=he(),Vn=zr(),Iz=Vt(),Oz=ti();function Cz(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=nk(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=r.name("valid");t.subschema({schema:a,schemaPath:vt.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}br.macroKeywordCode=Cz;function Nz(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;jz(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,u=nk(n,o,l),p=n.let("valid");t.block$data(p,w),t.ok((r=e.valid)!==null&&r!==void 0?r:p);function w(){if(e.errors===!1)b(),e.modifying&&rk(t),$(()=>t.error());else{let E=e.async?f():h();e.modifying&&rk(t),$(()=>zz(t,E))}}function f(){let E=n.let("ruleErrs",null);return n.try(()=>b((0,vt._)`await `),P=>n.assign(p,!1).if((0,vt._)`${P} instanceof ${c.ValidationError}`,()=>n.assign(E,(0,vt._)`${P}.errors`),()=>n.throw(P))),E}function h(){let E=(0,vt._)`${u}.errors`;return n.assign(E,null),b(vt.nil),E}function b(E=e.async?(0,vt._)`await `:vt.nil){let P=c.opts.passContext?Vn.default.this:Vn.default.self,z=!("compile"in e&&!a||e.schema===!1);n.assign(p,(0,vt._)`${E}${(0,Iz.callValidateCode)(t,u,P,z)}`,e.modifying)}function $(E){var P;n.if((0,vt.not)((P=e.valid)!==null&&P!==void 0?P:p),E)}}br.funcKeywordCode=Nz;function rk(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,vt._)`${n.parentData}[${n.parentDataProperty}]`))}function zz(t,e){let{gen:r}=t;r.if((0,vt._)`Array.isArray(${e})`,()=>{r.assign(Vn.default.vErrors,(0,vt._)`${Vn.default.vErrors} === null ? ${e} : ${Vn.default.vErrors}.concat(${e})`).assign(Vn.default.errors,(0,vt._)`${Vn.default.vErrors}.length`),(0,Oz.extendErrors)(t)},()=>t.error())}function jz({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function nk(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,vt.stringify)(r)})}function Lz(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")}br.validSchemaType=Lz;function Dz({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)}}br.validateKeywordUsage=Dz});var ik=Z(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.extendSubschemaMode=sn.extendSubschemaData=sn.getSubschema=void 0;var wr=he(),sk=Se();function Mz(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,wr._)`${t.schemaPath}${(0,wr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,wr._)`${t.schemaPath}${(0,wr.getProperty)(e)}${(0,wr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,sk.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')}sn.getSubschema=Mz;function Uz(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:p}=e,w=a.let("data",(0,wr._)`${e.data}${(0,wr.getProperty)(r)}`,!0);c(w),t.errorPath=(0,wr.str)`${l}${(0,sk.getErrorPath)(r,n,p.jsPropertySyntax)}`,t.parentDataProperty=(0,wr._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(o!==void 0){let l=o instanceof wr.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]}}sn.extendSubschemaData=Uz;function qz(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}sn.extendSubschemaMode=qz});var Cf=Z((t9,ak)=>{"use strict";ak.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 lk=Z((r9,ck)=>{"use strict";var an=ck.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(){};Ic(e,n,o,t,"",t)};an.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};an.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};an.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};an.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 Ic(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 p=n[u];if(Array.isArray(p)){if(u in an.arrayKeywords)for(var w=0;w<p.length;w++)Ic(t,e,r,p[w],o+"/"+u+"/"+w,s,o,u,n,w)}else if(u in an.propsKeywords){if(p&&typeof p=="object")for(var f in p)Ic(t,e,r,p[f],o+"/"+u+"/"+Bz(f),s,o,u,n,f)}else(u in an.keywords||t.allKeys&&!(u in an.skipKeywords))&&Ic(t,e,r,p,o+"/"+u,s,o,u,n)}r(n,o,s,i,a,c,l)}}function Bz(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var ni=Z(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.getSchemaRefs=At.resolveUrl=At.normalizeId=At._getFullPath=At.getFullPath=At.inlineRef=void 0;var Zz=Se(),Fz=Cf(),Hz=lk(),Vz=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Kz(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Nf(t):e?uk(t)<=e:!1}At.inlineRef=Kz;var Wz=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Nf(t){for(let e in t){if(Wz.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Nf)||typeof r=="object"&&Nf(r))return!0}return!1}function uk(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!Vz.has(r)&&(typeof t[r]=="object"&&(0,Zz.eachItem)(t[r],n=>e+=uk(n)),e===1/0))return 1/0}return e}function dk(t,e="",r){r!==!1&&(e=Do(e));let n=t.parse(e);return pk(t,n)}At.getFullPath=dk;function pk(t,e){return t.serialize(e).split("#")[0]+"#"}At._getFullPath=pk;var Gz=/#\/?$/;function Do(t){return t?t.replace(Gz,""):""}At.normalizeId=Do;function Jz(t,e,r){return r=Do(r),t.resolve(e,r)}At.resolveUrl=Jz;var Yz=/^[a-z_][-a-z0-9._]*$/i;function Xz(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Do(t[r]||e),s={"":o},i=dk(n,o,!1),a={},c=new Set;return Hz(t,{allKeys:!0},(p,w,f,h)=>{if(h===void 0)return;let b=i+w,$=s[h];typeof p[r]=="string"&&($=E.call(this,p[r])),P.call(this,p.$anchor),P.call(this,p.$dynamicAnchor),s[w]=$;function E(z){let B=this.opts.uriResolver.resolve;if(z=Do($?B($,z):z),c.has(z))throw u(z);c.add(z);let W=this.refs[z];return typeof W=="string"&&(W=this.refs[W]),typeof W=="object"?l(p,W.schema,z):z!==Do(b)&&(z[0]==="#"?(l(p,a[z],z),a[z]=p):this.refs[z]=b),z}function P(z){if(typeof z=="string"){if(!Yz.test(z))throw new Error(`invalid anchor "${z}"`);E.call(this,`#${z}`)}}}),a;function l(p,w,f){if(w!==void 0&&!Fz(p,w))throw u(f)}function u(p){return new Error(`reference "${p}" resolves to more than one schema`)}}At.getSchemaRefs=Xz});var ii=Z(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.getData=cn.KeywordCxt=cn.validateFunctionCode=void 0;var yk=Vx(),hk=ri(),jf=Tf(),Oc=ri(),Qz=Qx(),si=ok(),zf=ik(),X=he(),ce=zr(),ej=ni(),jr=Se(),oi=ti();function tj(t){if(vk(t)&&(_k(t),wk(t))){oj(t);return}bk(t,()=>(0,yk.topBoolOrEmptySchema)(t))}cn.validateFunctionCode=tj;function bk({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,X._)`${ce.default.data}, ${ce.default.valCxt}`,n.$async,()=>{t.code((0,X._)`"use strict"; ${fk(r,o)}`),nj(t,o),t.code(s)}):t.func(e,(0,X._)`${ce.default.data}, ${rj(o)}`,n.$async,()=>t.code(fk(r,o)).code(s))}function rj(t){return(0,X._)`{${ce.default.instancePath}="", ${ce.default.parentData}, ${ce.default.parentDataProperty}, ${ce.default.rootData}=${ce.default.data}${t.dynamicRef?(0,X._)`, ${ce.default.dynamicAnchors}={}`:X.nil}}={}`}function nj(t,e){t.if(ce.default.valCxt,()=>{t.var(ce.default.instancePath,(0,X._)`${ce.default.valCxt}.${ce.default.instancePath}`),t.var(ce.default.parentData,(0,X._)`${ce.default.valCxt}.${ce.default.parentData}`),t.var(ce.default.parentDataProperty,(0,X._)`${ce.default.valCxt}.${ce.default.parentDataProperty}`),t.var(ce.default.rootData,(0,X._)`${ce.default.valCxt}.${ce.default.rootData}`),e.dynamicRef&&t.var(ce.default.dynamicAnchors,(0,X._)`${ce.default.valCxt}.${ce.default.dynamicAnchors}`)},()=>{t.var(ce.default.instancePath,(0,X._)`""`),t.var(ce.default.parentData,(0,X._)`undefined`),t.var(ce.default.parentDataProperty,(0,X._)`undefined`),t.var(ce.default.rootData,ce.default.data),e.dynamicRef&&t.var(ce.default.dynamicAnchors,(0,X._)`{}`)})}function oj(t){let{schema:e,opts:r,gen:n}=t;bk(t,()=>{r.$comment&&e.$comment&&kk(t),lj(t),n.let(ce.default.vErrors,null),n.let(ce.default.errors,0),r.unevaluated&&sj(t),xk(t),pj(t)})}function sj(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,X._)`${r}.evaluated`),e.if((0,X._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,X._)`${t.evaluated}.props`,(0,X._)`undefined`)),e.if((0,X._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,X._)`${t.evaluated}.items`,(0,X._)`undefined`))}function fk(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,X._)`/*# sourceURL=${r} */`:X.nil}function ij(t,e){if(vk(t)&&(_k(t),wk(t))){aj(t,e);return}(0,yk.boolOrEmptySchema)(t,e)}function wk({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 vk(t){return typeof t.schema!="boolean"}function aj(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&kk(t),uj(t),dj(t);let s=n.const("_errs",ce.default.errors);xk(t,s),n.var(e,(0,X._)`${s} === ${ce.default.errors}`)}function _k(t){(0,jr.checkUnknownRules)(t),cj(t)}function xk(t,e){if(t.opts.jtd)return mk(t,[],!1,e);let r=(0,hk.getSchemaTypes)(t.schema),n=(0,hk.coerceAndCheckDataType)(t,r);mk(t,r,!n,e)}function cj(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,jr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function lj(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,jr.checkStrictMode)(t,"default is ignored in the schema root")}function uj(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,ej.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function dj(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function kk({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,X._)`${ce.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,X.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,X._)`${ce.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function pj(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,X._)`${ce.default.errors} === 0`,()=>e.return(ce.default.data),()=>e.throw((0,X._)`new ${o}(${ce.default.vErrors})`)):(e.assign((0,X._)`${n}.errors`,ce.default.vErrors),s.unevaluated&&hj(t),e.return((0,X._)`${ce.default.errors} === 0`))}function hj({gen:t,evaluated:e,props:r,items:n}){r instanceof X.Name&&t.assign((0,X._)`${e}.props`,r),n instanceof X.Name&&t.assign((0,X._)`${e}.items`,n)}function mk(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,jr.schemaHasRulesButRef)(s,u))){o.block(()=>Sk(t,"$ref",u.all.$ref.definition));return}c.jtd||fj(t,e),o.block(()=>{for(let w of u.rules)p(w);p(u.post)});function p(w){(0,jf.shouldUseGroup)(s,w)&&(w.type?(o.if((0,Oc.checkDataType)(w.type,i,c.strictNumbers)),gk(t,w),e.length===1&&e[0]===w.type&&r&&(o.else(),(0,Oc.reportTypeError)(t)),o.endIf()):gk(t,w),a||o.if((0,X._)`${ce.default.errors} === ${n||0}`))}}function gk(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,Qz.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,jf.shouldUseRule)(n,s)&&Sk(t,s.keyword,s.definition,e.type)})}function fj(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(mj(t,e),t.opts.allowUnionTypes||gj(t,e),yj(t,t.dataTypes))}function mj(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{$k(t.dataTypes,r)||Lf(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),wj(t,e)}}function gj(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Lf(t,"use allowUnionTypes to allow union type keyword")}function yj(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,jf.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>bj(e,i))&&Lf(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function bj(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function $k(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function wj(t,e){let r=[];for(let n of t.dataTypes)$k(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Lf(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,jr.checkStrictMode)(t,e,t.opts.strictTypes)}var Cc=class{constructor(e,r,n){if((0,si.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,jr.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",Tk(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,si.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",ce.default.errors))}result(e,r,n){this.failResult((0,X.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,X.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,X._)`${r} !== undefined && (${(0,X.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?oi.reportExtraError:oi.reportError)(this,this.def.error,r)}$dataError(){(0,oi.reportError)(this,this.def.$dataError||oi.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,oi.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=X.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=X.nil,r=X.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,X.or)((0,X._)`${o} === undefined`,r)),e!==X.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==X.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,X.or)(i(),a());function i(){if(n.length){if(!(r instanceof X.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,X._)`${(0,Oc.checkDataTypes)(c,r,s.opts.strictNumbers,Oc.DataType.Wrong)}`}return X.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,X._)`!${c}(${r})`}return X.nil}}subschema(e,r){let n=(0,zf.getSubschema)(this.it,e);(0,zf.extendSubschemaData)(n,this.it,e),(0,zf.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return ij(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=jr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=jr.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,X.Name)),!0}};cn.KeywordCxt=Cc;function Sk(t,e,r,n){let o=new Cc(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,si.funcKeywordCode)(o,r):"macro"in r?(0,si.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,si.funcKeywordCode)(o,r)}var vj=/^\/(?:[^~]|~0|~1)*$/,_j=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Tk(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return ce.default.rootData;if(t[0]==="/"){if(!vj.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ce.default.rootData}else{let l=_j.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,X._)`${s}${(0,X.getProperty)((0,jr.unescapeJsonPointer)(l))}`,i=(0,X._)`${i} && ${s}`);return i;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}cn.getData=Tk});var Nc=Z(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var Df=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Mf.default=Df});var ai=Z(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});var Uf=ni(),qf=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Uf.resolveUrl)(e,r,n),this.missingSchema=(0,Uf.normalizeId)((0,Uf.getFullPath)(e,this.missingRef))}};Bf.default=qf});var jc=Z(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.resolveSchema=Kt.getCompilingSchema=Kt.resolveRef=Kt.compileSchema=Kt.SchemaEnv=void 0;var sr=he(),xj=Nc(),Kn=zr(),ir=ni(),Ek=Se(),kj=ii(),Mo=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,ir.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=Mo;function Ff(t){let e=Rk.call(this,t);if(e)return e;let r=(0,ir.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new sr.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:xj.default,code:(0,sr._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:Kn.default.data,parentData:Kn.default.parentData,parentDataProperty:Kn.default.parentDataProperty,dataNames:[Kn.default.data],dataPathArr:[sr.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,sr.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:sr.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,sr._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,kj.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let p=i.toString();u=`${i.scopeRefs(Kn.default.scope)}return ${p}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let f=new Function(`${Kn.default.self}`,`${Kn.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:p,scopeValues:i._values}),this.opts.unevaluated){let{props:h,items:b}=l;f.evaluated={props:h instanceof sr.Name?void 0:h,items:b instanceof sr.Name?void 0:b,dynamicProps:h instanceof sr.Name,dynamicItems:b instanceof sr.Name},f.source&&(f.source.evaluated=(0,sr.stringify)(f.evaluated))}return t.validate=f,t}catch(p){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),p}finally{this._compilations.delete(t)}}Kt.compileSchema=Ff;function $j(t,e,r){var n;r=(0,ir.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=Ej.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 Mo({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=Sj.call(this,s)}Kt.resolveRef=$j;function Sj(t){return(0,ir.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Ff.call(this,t)}function Rk(t){for(let e of this._compilations)if(Tj(e,t))return e}Kt.getCompilingSchema=Rk;function Tj(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Ej(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||zc.call(this,t,e)}function zc(t,e){let r=this.opts.uriResolver.parse(e),n=(0,ir._getFullPath)(this.opts.uriResolver,r),o=(0,ir.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Zf.call(this,r,t);let s=(0,ir.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=zc.call(this,t,i);return typeof a?.schema!="object"?void 0:Zf.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Ff.call(this,i),s===(0,ir.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,ir.resolveUrl)(this.opts.uriResolver,o,l)),new Mo({schema:a,schemaId:c,root:t,baseId:o})}return Zf.call(this,r,i)}}Kt.resolveSchema=zc;var Rj=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Zf(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,Ek.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!Rj.has(a)&&l&&(e=(0,ir.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Ek.schemaHasRulesButRef)(r,this.RULES)){let a=(0,ir.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=zc.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Mo({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Pk=Z((c9,Pj)=>{Pj.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 Kf=Z((l9,zk)=>{"use strict";var Aj=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Ik=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),Hf=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Ok=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Ij=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Vf(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 Oj=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Ak(t){return t.length=0,!0}function Cj(t,e,r){if(t.length){let n=Vf(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function Nj(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=Cj;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=Ak}else{o.push(l);continue}}return o.length&&(a===Ak?r.zone=o.join(""):i?n.push(o.join("")):n.push(Vf(o))),r.address=n.join(""),r}function Ck(t){if(zj(t,":")<2)return{host:t,isIPV6:!1};let e=Nj(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 zj(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function jj(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 Lj={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Dj=/[@/?#:]/g,Mj=/[@/?#]/g;function Nk(t,e){let r=e?Mj:Dj;return r.lastIndex=0,t.replace(r,n=>Lj[n])}function Uj(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(Hf(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Ok(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function qj(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(Hf(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Ok(s)?e+=s:e+="%"+o,r+=2;continue}}Ij(t[r])?e+=t[r]:e+=escape(t[r])}return e}function Bj(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(Hf(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function Zj(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!Ik(r)){let n=Ck(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Nk(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}zk.exports={nonSimpleDomain:Oj,recomposeAuthority:Zj,reescapeHostDelimiters:Nk,normalizePercentEncoding:Uj,normalizePathEncoding:qj,escapePreservingEscapes:Bj,removeDotSegments:jj,isIPv4:Ik,isUUID:Aj,normalizeIPv6:Ck,stringArrayToHexStripped:Vf}});var Uk=Z((u9,Mk)=>{"use strict";var{isUUID:Fj}=Kf(),Hj=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Vj=["http","https","ws","wss","urn","urn:uuid"];function Kj(t){return Vj.indexOf(t)!==-1}function Wf(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 jk(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Lk(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 Wj(t){return t.secure=Wf(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function Gj(t){if((t.port===(Wf(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 Jj(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(Hj);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=Gf(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function Yj(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=Gf(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 Xj(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!Fj(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Qj(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Dk={scheme:"http",domainHost:!0,parse:jk,serialize:Lk},eL={scheme:"https",domainHost:Dk.domainHost,parse:jk,serialize:Lk},Lc={scheme:"ws",domainHost:!0,parse:Wj,serialize:Gj},tL={scheme:"wss",domainHost:Lc.domainHost,parse:Lc.parse,serialize:Lc.serialize},rL={scheme:"urn",parse:Jj,serialize:Yj,skipNormalize:!0},nL={scheme:"urn:uuid",parse:Xj,serialize:Qj,skipNormalize:!0},Dc={http:Dk,https:eL,ws:Lc,wss:tL,urn:rL,"urn:uuid":nL};Object.setPrototypeOf(Dc,null);function Gf(t){return t&&(Dc[t]||Dc[t.toLowerCase()])||void 0}Mk.exports={wsIsSecure:Wf,SCHEMES:Dc,isValidSchemeName:Kj,getSchemeHandler:Gf}});var Hk=Z((d9,qc)=>{"use strict";var{normalizeIPv6:oL,removeDotSegments:ci,recomposeAuthority:sL,normalizePercentEncoding:iL,normalizePathEncoding:aL,escapePreservingEscapes:cL,reescapeHostDelimiters:lL,isIPv4:uL,nonSimpleDomain:dL}=Kf(),{SCHEMES:pL,getSchemeHandler:Bk}=Uk();function hL(t,e){return typeof t=="string"?t=vL(t,e):typeof t=="object"&&(t=Uc(Wn(t,e),e)),t}function fL(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=Zk(o,i,n,!0);return n.skipEscape=!0,Wn(c,n)}function Zk(t,e,r,n){let o={};return n||(t=Uc(Wn(t,r),r),e=Uc(Wn(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=ci(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=ci(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=ci(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=ci(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 mL(t,e,r){let n=qk(t,r),o=qk(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Wn(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=Bk(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=iL(r.path):(r.path=cL(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=sL(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=ci(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 gL=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,yL=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,bL=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function wL(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(yL);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(bL);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(gL);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=wL(n,c);if(l!==void 0&&(n.error=n.error||l,o=!0),n.host)if(uL(n.host)===!1){let w=oL(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=Bk(r.scheme||n.scheme);if(!r.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(r.domainHost||u&&u.domainHost)&&s===!1&&dL(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(p){n.error=n.error||"Host's domain name can not be converted to ASCII: "+p}if((!u||u&&!u.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=lL(unescape(n.host),s))),n.path&&(n.path=aL(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 Uc(t,e){return Mc(t,e).parsed}function vL(t,e){return Fk(t,e).normalized}function Fk(t,e){let{parsed:r,malformedAuthorityOrPort:n}=Mc(t,e);return{normalized:n?t:Wn(r,e),malformedAuthorityOrPort:n}}function qk(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Fk(t,e);return n?void 0:r}if(typeof t=="object")return Wn(t,e)}var Jf={SCHEMES:pL,normalize:hL,resolve:fL,resolveComponent:Zk,equal:mL,serialize:Wn,parse:Uc};qc.exports=Jf;qc.exports.default=Jf;qc.exports.fastUri=Jf});var Kk=Z(Yf=>{"use strict";Object.defineProperty(Yf,"__esModule",{value:!0});var Vk=Hk();Vk.code='require("ajv/dist/runtime/uri").default';Yf.default=Vk});var t$=Z(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.CodeGen=at.Name=at.nil=at.stringify=at.str=at._=at.KeywordCxt=void 0;var _L=ii();Object.defineProperty(at,"KeywordCxt",{enumerable:!0,get:function(){return _L.KeywordCxt}});var Uo=he();Object.defineProperty(at,"_",{enumerable:!0,get:function(){return Uo._}});Object.defineProperty(at,"str",{enumerable:!0,get:function(){return Uo.str}});Object.defineProperty(at,"stringify",{enumerable:!0,get:function(){return Uo.stringify}});Object.defineProperty(at,"nil",{enumerable:!0,get:function(){return Uo.nil}});Object.defineProperty(at,"Name",{enumerable:!0,get:function(){return Uo.Name}});Object.defineProperty(at,"CodeGen",{enumerable:!0,get:function(){return Uo.CodeGen}});var xL=Nc(),Xk=ai(),kL=Sf(),li=jc(),$L=he(),ui=ni(),Bc=ri(),Qf=Se(),Wk=Pk(),SL=Kk(),Qk=(t,e)=>new RegExp(t,e);Qk.code="new RegExp";var TL=["removeAdditional","useDefaults","coerceTypes"],EL=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),RL={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."},PL={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Gk=200;function AL(t){var e,r,n,o,s,i,a,c,l,u,p,w,f,h,b,$,E,P,z,B,W,Ve,Ye,Gt,Dr;let pn=t.strict,Mr=(e=t.code)===null||e===void 0?void 0:e.optimize,lr=Mr===!0||Mr===void 0?1:Mr||0,$i=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Qk,fl=(o=t.uriResolver)!==null&&o!==void 0?o:SL.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:pn)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:pn)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:pn)!==null&&u!==void 0?u:"log",strictTuples:(w=(p=t.strictTuples)!==null&&p!==void 0?p:pn)!==null&&w!==void 0?w:"log",strictRequired:(h=(f=t.strictRequired)!==null&&f!==void 0?f:pn)!==null&&h!==void 0?h:!1,code:t.code?{...t.code,optimize:lr,regExp:$i}:{optimize:lr,regExp:$i},loopRequired:(b=t.loopRequired)!==null&&b!==void 0?b:Gk,loopEnum:($=t.loopEnum)!==null&&$!==void 0?$:Gk,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:(B=t.schemaId)!==null&&B!==void 0?B:"$id",addUsedSchema:(W=t.addUsedSchema)!==null&&W!==void 0?W:!0,validateSchema:(Ve=t.validateSchema)!==null&&Ve!==void 0?Ve:!0,validateFormats:(Ye=t.validateFormats)!==null&&Ye!==void 0?Ye:!0,unicodeRegExp:(Gt=t.unicodeRegExp)!==null&&Gt!==void 0?Gt:!0,int32range:(Dr=t.int32range)!==null&&Dr!==void 0?Dr:!0,uriResolver:fl}}var di=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,...AL(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new $L.ValueScope({scope:{},prefixes:EL,es5:r,lines:n}),this.logger=jL(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,kL.getRules)(),Jk.call(this,RL,e,"NOT SUPPORTED"),Jk.call(this,PL,e,"DEPRECATED","warn"),this._metaOpts=NL.call(this),e.formats&&OL.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&CL.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),IL.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=Wk;n==="id"&&(o={...Wk},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,p){await s.call(this,u.$schema);let w=this._addSchema(u,p);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(p){if(!(p instanceof Xk.default))throw p;return a.call(this,p),await c.call(this,p.missingSchema),i.call(this,u)}}function a({missingSchema:u,missingRef:p}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${p} cannot be resolved`)}async function c(u){let p=await l.call(this,u);this.refs[u]||await s.call(this,p.$schema),this.refs[u]||this.addSchema(p,u,r)}async function l(u){let p=this._loading[u];if(p)return p;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,ui.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=Yk.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new li.SchemaEnv({schema:{},schemaId:n});if(r=li.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=Yk.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,ui.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(DL.call(this,n,r),!r)return(0,Qf.eachItem)(n,s=>Xf.call(this,s)),this;UL.call(this,r);let o={...r,type:(0,Bc.getJSONTypes)(r.type),schemaType:(0,Bc.getJSONTypes)(r.schemaType)};return(0,Qf.eachItem)(n,o.type.length===0?s=>Xf.call(this,s,o):s=>o.type.forEach(i=>Xf.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]=e$(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,ui.normalizeId)(i||n);let l=ui.getSchemaRefs.call(this,e,n);return c=new li.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):li.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{li.compileSchema.call(this,e)}finally{this.opts=r}}};di.ValidationError=xL.default;di.MissingRefError=Xk.default;at.default=di;function Jk(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 Yk(t){return t=(0,ui.normalizeId)(t),this.schemas[t]||this.refs[t]}function IL(){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 OL(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function CL(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 NL(){let t={...this.opts};for(let e of TL)delete t[e];return t}var zL={log(){},warn(){},error(){}};function jL(t){if(t===!1)return zL;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 LL=/^[a-z_$][a-z0-9_$:-]*$/i;function DL(t,e){let{RULES:r}=this;if((0,Qf.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!LL.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 Xf(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?ML.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 ML(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 UL(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=e$(e)),t.validateSchema=this.compile(e,!0))}var qL={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function e$(t){return{anyOf:[t,qL]}}});var r$=Z(em=>{"use strict";Object.defineProperty(em,"__esModule",{value:!0});var BL={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};em.default=BL});var i$=Z(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.callRef=Gn.getValidate=void 0;var ZL=ai(),n$=Vt(),It=he(),qo=zr(),o$=jc(),Zc=Se(),FL={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 p();let u=o$.resolveRef.call(c,l,o,r);if(u===void 0)throw new ZL.default(n.opts.uriResolver,o,r);if(u instanceof o$.SchemaEnv)return w(u);return f(u);function p(){if(s===l)return Fc(t,i,s,s.$async);let h=e.scopeValue("root",{ref:l});return Fc(t,(0,It._)`${h}.validate`,l,l.$async)}function w(h){let b=s$(t,h);Fc(t,b,h,h.$async)}function f(h){let b=e.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,It.stringify)(h)}:{ref:h}),$=e.name("valid"),E=t.subschema({schema:h,dataTypes:[],schemaPath:It.nil,topSchemaRef:b,errSchemaPath:r},$);t.mergeEvaluated(E),t.ok($)}}};function s$(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,It._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Gn.getValidate=s$;function Fc(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?qo.default.this:It.nil;n?u():p();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=o.let("valid");o.try(()=>{o.code((0,It._)`await ${(0,n$.callValidateCode)(t,e,l)}`),f(e),i||o.assign(h,!0)},b=>{o.if((0,It._)`!(${b} instanceof ${s.ValidationError})`,()=>o.throw(b)),w(b),i||o.assign(h,!1)}),t.ok(h)}function p(){t.result((0,n$.callValidateCode)(t,e,l),()=>f(e),()=>w(e))}function w(h){let b=(0,It._)`${h}.errors`;o.assign(qo.default.vErrors,(0,It._)`${qo.default.vErrors} === null ? ${b} : ${qo.default.vErrors}.concat(${b})`),o.assign(qo.default.errors,(0,It._)`${qo.default.vErrors}.length`)}function f(h){var b;if(!s.opts.unevaluated)return;let $=(b=r?.validate)===null||b===void 0?void 0:b.evaluated;if(s.props!==!0)if($&&!$.dynamicProps)$.props!==void 0&&(s.props=Zc.mergeEvaluated.props(o,$.props,s.props));else{let E=o.var("props",(0,It._)`${h}.evaluated.props`);s.props=Zc.mergeEvaluated.props(o,E,s.props,It.Name)}if(s.items!==!0)if($&&!$.dynamicItems)$.items!==void 0&&(s.items=Zc.mergeEvaluated.items(o,$.items,s.items));else{let E=o.var("items",(0,It._)`${h}.evaluated.items`);s.items=Zc.mergeEvaluated.items(o,E,s.items,It.Name)}}}Gn.callRef=Fc;Gn.default=FL});var a$=Z(tm=>{"use strict";Object.defineProperty(tm,"__esModule",{value:!0});var HL=r$(),VL=i$(),KL=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",HL.default,VL.default];tm.default=KL});var c$=Z(rm=>{"use strict";Object.defineProperty(rm,"__esModule",{value:!0});var Hc=he(),ln=Hc.operators,Vc={maximum:{okStr:"<=",ok:ln.LTE,fail:ln.GT},minimum:{okStr:">=",ok:ln.GTE,fail:ln.LT},exclusiveMaximum:{okStr:"<",ok:ln.LT,fail:ln.GTE},exclusiveMinimum:{okStr:">",ok:ln.GT,fail:ln.LTE}},WL={message:({keyword:t,schemaCode:e})=>(0,Hc.str)`must be ${Vc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Hc._)`{comparison: ${Vc[t].okStr}, limit: ${e}}`},GL={keyword:Object.keys(Vc),type:"number",schemaType:"number",$data:!0,error:WL,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Hc._)`${r} ${Vc[e].fail} ${n} || isNaN(${r})`)}};rm.default=GL});var l$=Z(nm=>{"use strict";Object.defineProperty(nm,"__esModule",{value:!0});var pi=he(),JL={message:({schemaCode:t})=>(0,pi.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,pi._)`{multipleOf: ${t}}`},YL={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:JL,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,pi._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,pi._)`${i} !== parseInt(${i})`;t.fail$data((0,pi._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};nm.default=YL});var d$=Z(om=>{"use strict";Object.defineProperty(om,"__esModule",{value:!0});function u$(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}om.default=u$;u$.code='require("ajv/dist/runtime/ucs2length").default'});var p$=Z(sm=>{"use strict";Object.defineProperty(sm,"__esModule",{value:!0});var Jn=he(),XL=Se(),QL=d$(),e1={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Jn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Jn._)`{limit: ${t}}`},t1={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:e1,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Jn.operators.GT:Jn.operators.LT,i=o.opts.unicode===!1?(0,Jn._)`${r}.length`:(0,Jn._)`${(0,XL.useFunc)(t.gen,QL.default)}(${r})`;t.fail$data((0,Jn._)`${i} ${s} ${n}`)}};sm.default=t1});var h$=Z(im=>{"use strict";Object.defineProperty(im,"__esModule",{value:!0});var r1=Vt(),n1=Se(),Bo=he(),o1={message:({schemaCode:t})=>(0,Bo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Bo._)`{pattern: ${t}}`},s1={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:o1,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,Bo._)`new RegExp`:(0,n1.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,Bo._)`${l}(${s}, ${a}).test(${r})`),()=>e.assign(u,!1)),t.fail$data((0,Bo._)`!${u}`)}else{let c=(0,r1.usePattern)(t,o);t.fail$data((0,Bo._)`!${c}.test(${r})`)}}};im.default=s1});var f$=Z(am=>{"use strict";Object.defineProperty(am,"__esModule",{value:!0});var hi=he(),i1={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,hi.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,hi._)`{limit: ${t}}`},a1={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:i1,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?hi.operators.GT:hi.operators.LT;t.fail$data((0,hi._)`Object.keys(${r}).length ${o} ${n}`)}};am.default=a1});var m$=Z(cm=>{"use strict";Object.defineProperty(cm,"__esModule",{value:!0});var fi=Vt(),mi=he(),c1=Se(),l1={message:({params:{missingProperty:t}})=>(0,mi.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,mi._)`{missingProperty: ${t}}`},u1={keyword:"required",type:"object",schemaType:"array",$data:!0,error:l1,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 f=t.parentSchema.properties,{definedProperties:h}=t.it;for(let b of r)if(f?.[b]===void 0&&!h.has(b)){let $=i.schemaEnv.baseId+i.errSchemaPath,E=`required property "${b}" is not defined at "${$}" (strictRequired)`;(0,c1.checkStrictMode)(i,E,i.opts.strictRequired)}}function l(){if(c||s)t.block$data(mi.nil,p);else for(let f of r)(0,fi.checkReportMissingProp)(t,f)}function u(){let f=e.let("missing");if(c||s){let h=e.let("valid",!0);t.block$data(h,()=>w(f,h)),t.ok(h)}else e.if((0,fi.checkMissingProp)(t,r,f)),(0,fi.reportMissingProp)(t,f),e.else()}function p(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,fi.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function w(f,h){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(h,(0,fi.propertyInData)(e,o,f,a.ownProperties)),e.if((0,mi.not)(h),()=>{t.error(),e.break()})},mi.nil)}}};cm.default=u1});var g$=Z(lm=>{"use strict";Object.defineProperty(lm,"__esModule",{value:!0});var gi=he(),d1={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,gi.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,gi._)`{limit: ${t}}`},p1={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:d1,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?gi.operators.GT:gi.operators.LT;t.fail$data((0,gi._)`${r}.length ${o} ${n}`)}};lm.default=p1});var Kc=Z(um=>{"use strict";Object.defineProperty(um,"__esModule",{value:!0});var y$=Cf();y$.code='require("ajv/dist/runtime/equal").default';um.default=y$});var b$=Z(pm=>{"use strict";Object.defineProperty(pm,"__esModule",{value:!0});var dm=ri(),ct=he(),h1=Se(),f1=Kc(),m1={message:({params:{i:t,j:e}})=>(0,ct.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,ct._)`{i: ${t}, j: ${e}}`},g1={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:m1,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,dm.getSchemaTypes)(s.items):[];t.block$data(c,u,(0,ct._)`${i} === false`),t.ok(c);function u(){let h=e.let("i",(0,ct._)`${r}.length`),b=e.let("j");t.setParams({i:h,j:b}),e.assign(c,!0),e.if((0,ct._)`${h} > 1`,()=>(p()?w:f)(h,b))}function p(){return l.length>0&&!l.some(h=>h==="object"||h==="array")}function w(h,b){let $=e.name("item"),E=(0,dm.checkDataTypes)(l,$,a.opts.strictNumbers,dm.DataType.Wrong),P=e.const("indices",(0,ct._)`{}`);e.for((0,ct._)`;${h}--;`,()=>{e.let($,(0,ct._)`${r}[${h}]`),e.if(E,(0,ct._)`continue`),l.length>1&&e.if((0,ct._)`typeof ${$} == "string"`,(0,ct._)`${$} += "_"`),e.if((0,ct._)`typeof ${P}[${$}] == "number"`,()=>{e.assign(b,(0,ct._)`${P}[${$}]`),t.error(),e.assign(c,!1).break()}).code((0,ct._)`${P}[${$}] = ${h}`)})}function f(h,b){let $=(0,h1.useFunc)(e,f1.default),E=e.name("outer");e.label(E).for((0,ct._)`;${h}--;`,()=>e.for((0,ct._)`${b} = ${h}; ${b}--;`,()=>e.if((0,ct._)`${$}(${r}[${h}], ${r}[${b}])`,()=>{t.error(),e.assign(c,!1).break(E)})))}}};pm.default=g1});var w$=Z(fm=>{"use strict";Object.defineProperty(fm,"__esModule",{value:!0});var hm=he(),y1=Se(),b1=Kc(),w1={message:"must be equal to constant",params:({schemaCode:t})=>(0,hm._)`{allowedValue: ${t}}`},v1={keyword:"const",$data:!0,error:w1,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,hm._)`!${(0,y1.useFunc)(e,b1.default)}(${r}, ${o})`):t.fail((0,hm._)`${s} !== ${r}`)}};fm.default=v1});var v$=Z(mm=>{"use strict";Object.defineProperty(mm,"__esModule",{value:!0});var yi=he(),_1=Se(),x1=Kc(),k1={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,yi._)`{allowedValues: ${t}}`},$1={keyword:"enum",schemaType:"array",$data:!0,error:k1,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,_1.useFunc)(e,x1.default)),u;if(a||n)u=e.let("valid"),t.block$data(u,p);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=e.const("vSchema",s);u=(0,yi.or)(...o.map((h,b)=>w(f,b)))}t.pass(u);function p(){e.assign(u,!1),e.forOf("v",s,f=>e.if((0,yi._)`${l()}(${r}, ${f})`,()=>e.assign(u,!0).break()))}function w(f,h){let b=o[h];return typeof b=="object"&&b!==null?(0,yi._)`${l()}(${r}, ${f}[${h}])`:(0,yi._)`${r} === ${b}`}}};mm.default=$1});var _$=Z(gm=>{"use strict";Object.defineProperty(gm,"__esModule",{value:!0});var S1=c$(),T1=l$(),E1=p$(),R1=h$(),P1=f$(),A1=m$(),I1=g$(),O1=b$(),C1=w$(),N1=v$(),z1=[S1.default,T1.default,E1.default,R1.default,P1.default,A1.default,I1.default,O1.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},C1.default,N1.default];gm.default=z1});var bm=Z(bi=>{"use strict";Object.defineProperty(bi,"__esModule",{value:!0});bi.validateAdditionalItems=void 0;var Yn=he(),ym=Se(),j1={message:({params:{len:t}})=>(0,Yn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Yn._)`{limit: ${t}}`},L1={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:j1,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,ym.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}x$(t,n)}};function x$(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Yn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Yn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,ym.alwaysValidSchema)(i,n)){let l=r.var("valid",(0,Yn._)`${a} <= ${e.length}`);r.if((0,Yn.not)(l),()=>c(l)),t.ok(l)}function c(l){r.forRange("i",e.length,a,u=>{t.subschema({keyword:s,dataProp:u,dataPropType:ym.Type.Num},l),i.allErrors||r.if((0,Yn.not)(l),()=>r.break())})}}bi.validateAdditionalItems=x$;bi.default=L1});var wm=Z(wi=>{"use strict";Object.defineProperty(wi,"__esModule",{value:!0});wi.validateTuple=void 0;var k$=he(),Wc=Se(),D1=Vt(),M1={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return $$(t,"additionalItems",e);r.items=!0,!(0,Wc.alwaysValidSchema)(r,e)&&t.ok((0,D1.validateArray)(t))}};function $$(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=Wc.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,k$._)`${s}.length`);r.forEach((p,w)=>{(0,Wc.alwaysValidSchema)(a,p)||(n.if((0,k$._)`${l} > ${w}`,()=>t.subschema({keyword:i,schemaProp:w,dataProp:w},c)),t.ok(c))});function u(p){let{opts:w,errSchemaPath:f}=a,h=r.length,b=h===p.minItems&&(h===p.maxItems||p[e]===!1);if(w.strictTuples&&!b){let $=`"${i}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,Wc.checkStrictMode)(a,$,w.strictTuples)}}}wi.validateTuple=$$;wi.default=M1});var S$=Z(vm=>{"use strict";Object.defineProperty(vm,"__esModule",{value:!0});var U1=wm(),q1={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,U1.validateTuple)(t,"items")};vm.default=q1});var E$=Z(_m=>{"use strict";Object.defineProperty(_m,"__esModule",{value:!0});var T$=he(),B1=Se(),Z1=Vt(),F1=bm(),H1={message:({params:{len:t}})=>(0,T$.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,T$._)`{limit: ${t}}`},V1={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:H1,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,B1.alwaysValidSchema)(n,e)&&(o?(0,F1.validateAdditionalItems)(t,o):t.ok((0,Z1.validateArray)(t)))}};_m.default=V1});var R$=Z(xm=>{"use strict";Object.defineProperty(xm,"__esModule",{value:!0});var Wt=he(),Gc=Se(),K1={message:({params:{min:t,max:e}})=>e===void 0?(0,Wt.str)`must contain at least ${t} valid item(s)`:(0,Wt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Wt._)`{minContains: ${t}}`:(0,Wt._)`{minContains: ${t}, maxContains: ${e}}`},W1={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:K1,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,Wt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Gc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Gc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Gc.alwaysValidSchema)(s,r)){let b=(0,Wt._)`${u} >= ${i}`;a!==void 0&&(b=(0,Wt._)`${b} && ${u} <= ${a}`),t.pass(b);return}s.items=!0;let p=e.name("valid");a===void 0&&i===1?f(p,()=>e.if(p,()=>e.break())):i===0?(e.let(p,!0),a!==void 0&&e.if((0,Wt._)`${o}.length > 0`,w)):(e.let(p,!1),w()),t.result(p,()=>t.reset());function w(){let b=e.name("_valid"),$=e.let("count",0);f(b,()=>e.if(b,()=>h($)))}function f(b,$){e.forRange("i",0,u,E=>{t.subschema({keyword:"contains",dataProp:E,dataPropType:Gc.Type.Num,compositeRule:!0},b),$()})}function h(b){e.code((0,Wt._)`${b}++`),a===void 0?e.if((0,Wt._)`${b} >= ${i}`,()=>e.assign(p,!0).break()):(e.if((0,Wt._)`${b} > ${a}`,()=>e.assign(p,!1).break()),i===1?e.assign(p,!0):e.if((0,Wt._)`${b} >= ${i}`,()=>e.assign(p,!0)))}}};xm.default=W1});var I$=Z(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.validateSchemaDeps=vr.validatePropertyDeps=vr.error=void 0;var km=he(),G1=Se(),vi=Vt();vr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,km.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,km._)`{property: ${t},
2038
2045
  missingProperty: ${n},
2039
2046
  depsCount: ${e},
2040
- deps: ${r}}`};var F1={keyword:"dependencies",type:"object",schemaType:"object",error:vr.error,code(t){let[e,r]=H1(t);T$(t,e),E$(t,r)}};function H1({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 T$(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,vi.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,vi.checkReportMissingProp)(t,l)}):(r.if((0,_m._)`${c} && (${(0,vi.checkMissingProp)(t,a,s)})`),(0,vi.reportMissingProp)(t,s),r.else())}}vr.validatePropertyDeps=T$;function E$(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,Z1.alwaysValidSchema)(s,e[a])||(r.if((0,vi.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))}vr.validateSchemaDeps=E$;vr.default=F1});var A$=Z(xm=>{"use strict";Object.defineProperty(xm,"__esModule",{value:!0});var P$=he(),V1=Se(),K1={message:"property name must be valid",params:({params:t})=>(0,P$._)`{propertyName: ${t.propertyName}}`},W1={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:K1,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,V1.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,P$.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};xm.default=W1});var $m=Z(km=>{"use strict";Object.defineProperty(km,"__esModule",{value:!0});var Wc=Vt(),ar=he(),G1=zr(),Gc=Se(),J1={message:"must NOT have additional properties",params:({params:t})=>(0,ar._)`{additionalProperty: ${t.additionalProperty}}`},Y1={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:J1,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,Gc.alwaysValidSchema)(i,r))return;let l=(0,Wc.allSchemaProperties)(n.properties),u=(0,Wc.allSchemaProperties)(n.patternProperties);p(),t.ok((0,ar._)`${s} === ${G1.default.errors}`);function p(){e.forIn("key",o,$=>{!l.length&&!u.length?h($):e.if(w($),()=>h($))})}function w($){let E;if(l.length>8){let P=(0,Gc.schemaRefOrVal)(i,n.properties,"properties");E=(0,Wc.isOwnProperty)(e,P,$)}else l.length?E=(0,ar.or)(...l.map(P=>(0,ar._)`${$} === ${P}`)):E=ar.nil;return u.length&&(E=(0,ar.or)(E,...u.map(P=>(0,ar._)`${(0,Wc.usePattern)(t,P)}.test(${$})`))),(0,ar.not)(E)}function f($){e.code((0,ar._)`delete ${o}[${$}]`)}function h($){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f($);return}if(r===!1){t.setParams({additionalProperty:$}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Gc.alwaysValidSchema)(i,r)){let E=e.name("valid");c.removeAdditional==="failing"?(b($,E,!1),e.if((0,ar.not)(E),()=>{t.reset(),f($)})):(b($,E),a||e.if((0,ar.not)(E),()=>e.break()))}}function b($,E,P){let z={keyword:"additionalProperties",dataProp:$,dataPropType:Gc.Type.Str};P===!1&&Object.assign(z,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(z,E)}}};km.default=Y1});var C$=Z(Tm=>{"use strict";Object.defineProperty(Tm,"__esModule",{value:!0});var X1=ii(),I$=Vt(),Sm=Se(),O$=$m(),Q1={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&O$.default.code(new X1.KeywordCxt(s,O$.default,"additionalProperties"));let i=(0,I$.allSchemaProperties)(r);for(let p of i)s.definedProperties.add(p);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Sm.mergeEvaluated.props(e,(0,Sm.toHash)(i),s.props));let a=i.filter(p=>!(0,Sm.alwaysValidSchema)(s,r[p]));if(a.length===0)return;let c=e.name("valid");for(let p of a)l(p)?u(p):(e.if((0,I$.propertyInData)(e,o,p,s.opts.ownProperties)),u(p),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(p),t.ok(c);function l(p){return s.opts.useDefaults&&!s.compositeRule&&r[p].default!==void 0}function u(p){t.subschema({keyword:"properties",schemaProp:p,dataProp:p},c)}}};Tm.default=Q1});var L$=Z(Em=>{"use strict";Object.defineProperty(Em,"__esModule",{value:!0});var N$=Vt(),Jc=he(),z$=Se(),j$=Se(),eD={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,N$.allSchemaProperties)(r),c=a.filter(b=>(0,z$.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 Jc.Name)&&(s.props=(0,j$.evaluatedPropsToName)(e,s.props));let{props:p}=s;w();function w(){for(let b of a)l&&f(b),s.allErrors?h(b):(e.var(u,!0),h(b),e.if(u))}function f(b){for(let $ in l)new RegExp(b).test($)&&(0,z$.checkStrictMode)(s,`property ${$} matches pattern ${b} (use allowMatchingProperties)`)}function h(b){e.forIn("key",n,$=>{e.if((0,Jc._)`${(0,N$.usePattern)(t,b)}.test(${$})`,()=>{let E=c.includes(b);E||t.subschema({keyword:"patternProperties",schemaProp:b,dataProp:$,dataPropType:j$.Type.Str},u),s.opts.unevaluated&&p!==!0?e.assign((0,Jc._)`${p}[${$}]`,!0):!E&&!s.allErrors&&e.if((0,Jc.not)(u),()=>e.break())})})}}};Em.default=eD});var D$=Z(Rm=>{"use strict";Object.defineProperty(Rm,"__esModule",{value:!0});var tD=Se(),rD={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,tD.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"}};Rm.default=rD});var M$=Z(Pm=>{"use strict";Object.defineProperty(Pm,"__esModule",{value:!0});var nD=Vt(),oD={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:nD.validateUnion,error:{message:"must match a schema in anyOf"}};Pm.default=oD});var U$=Z(Am=>{"use strict";Object.defineProperty(Am,"__esModule",{value:!0});var Yc=he(),sD=Se(),iD={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Yc._)`{passingSchemas: ${t.passing}}`},aD={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:iD,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,p)=>{let w;(0,sD.alwaysValidSchema)(o,u)?e.var(c,!0):w=t.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},c),p>0&&e.if((0,Yc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Yc._)`[${a}, ${p}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,p),w&&t.mergeEvaluated(w,Yc.Name)})})}}};Am.default=aD});var q$=Z(Im=>{"use strict";Object.defineProperty(Im,"__esModule",{value:!0});var cD=Se(),lD={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,cD.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Im.default=lD});var F$=Z(Om=>{"use strict";Object.defineProperty(Om,"__esModule",{value:!0});var Xc=he(),Z$=Se(),uD={message:({params:t})=>(0,Xc.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Xc._)`{failingKeyword: ${t.ifClause}}`},dD={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:uD,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Z$.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=B$(n,"then"),s=B$(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,Xc.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,p){return()=>{let w=t.subschema({keyword:u},a);e.assign(i,a),t.mergeValidEvaluated(w,i),p?e.assign(p,(0,Xc._)`${u}`):t.setParams({ifClause:u})}}}};function B$(t,e){let r=t.schema[e];return r!==void 0&&!(0,Z$.alwaysValidSchema)(t,r)}Om.default=dD});var H$=Z(Cm=>{"use strict";Object.defineProperty(Cm,"__esModule",{value:!0});var pD=Se(),hD={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,pD.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Cm.default=hD});var V$=Z(Nm=>{"use strict";Object.defineProperty(Nm,"__esModule",{value:!0});var fD=gm(),mD=x$(),gD=ym(),yD=$$(),bD=S$(),wD=R$(),vD=A$(),_D=$m(),xD=C$(),kD=L$(),$D=D$(),SD=M$(),TD=U$(),ED=q$(),RD=F$(),PD=H$();function AD(t=!1){let e=[$D.default,SD.default,TD.default,ED.default,RD.default,PD.default,vD.default,_D.default,wD.default,xD.default,kD.default];return t?e.push(mD.default,yD.default):e.push(fD.default,gD.default),e.push(bD.default),e}Nm.default=AD});var K$=Z(zm=>{"use strict";Object.defineProperty(zm,"__esModule",{value:!0});var We=he(),ID={message:({schemaCode:t})=>(0,We.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,We._)`{format: ${t}}`},OD={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:ID,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:l,schemaEnv:u,self:p}=a;if(!c.validateFormats)return;o?w():f();function w(){let h=r.scopeValue("formats",{ref:p.formats,code:c.code.formats}),b=r.const("fDef",(0,We._)`${h}[${i}]`),$=r.let("fType"),E=r.let("format");r.if((0,We._)`typeof ${b} == "object" && !(${b} instanceof RegExp)`,()=>r.assign($,(0,We._)`${b}.type || "string"`).assign(E,(0,We._)`${b}.validate`),()=>r.assign($,(0,We._)`"string"`).assign(E,b)),t.fail$data((0,We.or)(P(),z()));function P(){return c.strictSchema===!1?We.nil:(0,We._)`${i} && !${E}`}function z(){let B=u.$async?(0,We._)`(${b}.async ? await ${E}(${n}) : ${E}(${n}))`:(0,We._)`${E}(${n})`,W=(0,We._)`(typeof ${E} == "function" ? ${B} : ${E}.test(${n}))`;return(0,We._)`${E} && ${E} !== true && ${$} === ${e} && !${W}`}}function f(){let h=p.formats[s];if(!h){P();return}if(h===!0)return;let[b,$,E]=z(h);b===e&&t.pass(B());function P(){if(c.strictSchema===!1){p.logger.warn(W());return}throw new Error(W());function W(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function z(W){let Ve=W instanceof RegExp?(0,We.regexpCode)(W):c.code.formats?(0,We._)`${c.code.formats}${(0,We.getProperty)(s)}`:void 0,Ye=r.scopeValue("formats",{key:s,ref:W,code:Ve});return typeof W=="object"&&!(W instanceof RegExp)?[W.type||"string",W.validate,(0,We._)`${Ye}.validate`]:["string",W,Ye]}function B(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!u.$async)throw new Error("async format in sync schema");return(0,We._)`await ${E}(${n})`}return typeof $=="function"?(0,We._)`${E}(${n})`:(0,We._)`${E}.test(${n})`}}}};zm.default=OD});var W$=Z(jm=>{"use strict";Object.defineProperty(jm,"__esModule",{value:!0});var CD=K$(),ND=[CD.default];jm.default=ND});var G$=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 Y$=Z(Lm=>{"use strict";Object.defineProperty(Lm,"__esModule",{value:!0});var zD=o$(),jD=b$(),LD=V$(),DD=W$(),J$=G$(),MD=[zD.default,jD.default,(0,LD.default)(),DD.default,J$.metadataVocabulary,J$.contentVocabulary];Lm.default=MD});var Q$=Z(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});Qc.DiscrError=void 0;var X$;(function(t){t.Tag="tag",t.Mapping="mapping"})(X$||(Qc.DiscrError=X$={}))});var tS=Z(Mm=>{"use strict";Object.defineProperty(Mm,"__esModule",{value:!0});var Fo=he(),Dm=Q$(),eS=Nc(),UD=ai(),qD=Se(),BD={message:({params:{discrError:t,tagName:e}})=>t===Dm.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Fo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},ZD={keyword:"discriminator",type:"object",schemaType:"object",error:BD,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,Fo._)`${r}${(0,Fo.getProperty)(a)}`);e.if((0,Fo._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:Dm.DiscrError.Tag,tag:l,tagName:a})),t.ok(c);function u(){let f=w();e.if(!1);for(let h in f)e.elseIf((0,Fo._)`${l} === ${h}`),e.assign(c,p(f[h]));e.else(),t.error(!1,{discrError:Dm.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function p(f){let h=e.name("valid"),b=t.subschema({keyword:"oneOf",schemaProp:f},h);return t.mergeEvaluated(b,Fo.Name),h}function w(){var f;let h={},b=E(o),$=!0;for(let B=0;B<i.length;B++){let W=i[B];if(W?.$ref&&!(0,qD.schemaHasRulesButRef)(W,s.self.RULES)){let Ye=W.$ref;if(W=eS.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Ye),W instanceof eS.SchemaEnv&&(W=W.schema),W===void 0)throw new UD.default(s.opts.uriResolver,s.baseId,Ye)}let Ve=(f=W?.properties)===null||f===void 0?void 0:f[a];if(typeof Ve!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);$=$&&(b||E(W)),P(Ve,B)}if(!$)throw new Error(`discriminator: "${a}" must be required`);return h;function E({required:B}){return Array.isArray(B)&&B.includes(a)}function P(B,W){if(B.const)z(B.const,W);else if(B.enum)for(let Ve of B.enum)z(Ve,W);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function z(B,W){if(typeof B!="string"||B in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[B]=W}}}};Mm.default=ZD});var rS=Z((K9,FD)=>{FD.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 qm=Z((De,Um)=>{"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 HD=Xk(),VD=Y$(),KD=tS(),nS=rS(),WD=["/properties"],el="http://json-schema.org/draft-07/schema",Ho=class extends HD.default{_addVocabularies(){super._addVocabularies(),VD.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(KD.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(nS,WD):nS;this.addMetaSchema(e,el,!1),this.refs["http://json-schema.org/schema"]=el}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(el)?el:void 0)}};De.Ajv=Ho;Um.exports=De=Ho;Um.exports.Ajv=Ho;Object.defineProperty(De,"__esModule",{value:!0});De.default=Ho;var GD=ii();Object.defineProperty(De,"KeywordCxt",{enumerable:!0,get:function(){return GD.KeywordCxt}});var Vo=he();Object.defineProperty(De,"_",{enumerable:!0,get:function(){return Vo._}});Object.defineProperty(De,"str",{enumerable:!0,get:function(){return Vo.str}});Object.defineProperty(De,"stringify",{enumerable:!0,get:function(){return Vo.stringify}});Object.defineProperty(De,"nil",{enumerable:!0,get:function(){return Vo.nil}});Object.defineProperty(De,"Name",{enumerable:!0,get:function(){return Vo.Name}});Object.defineProperty(De,"CodeGen",{enumerable:!0,get:function(){return Vo.CodeGen}});var JD=Oc();Object.defineProperty(De,"ValidationError",{enumerable:!0,get:function(){return JD.default}});var YD=ai();Object.defineProperty(De,"MissingRefError",{enumerable:!0,get:function(){return YD.default}})});var dS=Z(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.formatNames=xr.fastFormats=xr.fullFormats=void 0;function _r(t,e){return{validate:t,compare:e}}xr.fullFormats={date:_r(aS,Hm),time:_r(Zm(!0),Vm),"date-time":_r(oS(!0),lS),"iso-time":_r(Zm(),cS),"iso-date-time":_r(oS(),uS),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:nM,"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:uM,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:oM,int32:{type:"number",validate:aM},int64:{type:"number",validate:cM},float:{type:"number",validate:iS},double:{type:"number",validate:iS},password:!0,binary:!0};xr.fastFormats={...xr.fullFormats,date:_r(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Hm),time:_r(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Vm),"date-time":_r(/^\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,lS),"iso-time":_r(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,cS),"iso-date-time":_r(/^\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,uS),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};xr.formatNames=Object.keys(xr.fullFormats);function XD(t){return t%4===0&&(t%100!==0||t%400===0)}var QD=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,eM=[0,31,28,31,30,31,30,31,31,30,31,30,31];function aS(t){let e=QD.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&&XD(r)?29:eM[n])}function Hm(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Bm=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Zm(t){return function(r){let n=Bm.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 p=s-u*c,w=o-l*c-(p<0?1:0);return(w===23||w===-1)&&(p===59||p===-1)&&i<61}}function Vm(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 cS(t,e){if(!(t&&e))return;let r=Bm.exec(t),n=Bm.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 Fm=/t|\s/i;function oS(t){let e=Zm(t);return function(n){let o=n.split(Fm);return o.length===2&&aS(o[0])&&e(o[1])}}function lS(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function uS(t,e){if(!(t&&e))return;let[r,n]=t.split(Fm),[o,s]=e.split(Fm),i=Hm(r,o);if(i!==void 0)return i||Vm(n,s)}var tM=/\/|:/,rM=/^(?:[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 nM(t){return tM.test(t)&&rM.test(t)}var sS=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function oM(t){return sS.lastIndex=0,sS.test(t)}var sM=-(2**31),iM=2**31-1;function aM(t){return Number.isInteger(t)&&t<=iM&&t>=sM}function cM(t){return Number.isInteger(t)}function iS(){return!0}var lM=/[^\\]\\Z/;function uM(t){if(lM.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var pS=Z(Ko=>{"use strict";Object.defineProperty(Ko,"__esModule",{value:!0});Ko.formatLimitDefinition=void 0;var dM=qm(),cr=he(),un=cr.operators,tl={formatMaximum:{okStr:"<=",ok:un.LTE,fail:un.GT},formatMinimum:{okStr:">=",ok:un.GTE,fail:un.LT},formatExclusiveMaximum:{okStr:"<",ok:un.LT,fail:un.GTE},formatExclusiveMinimum:{okStr:">",ok:un.GT,fail:un.LTE}},pM={message:({keyword:t,schemaCode:e})=>(0,cr.str)`should be ${tl[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,cr._)`{comparison: ${tl[t].okStr}, limit: ${e}}`};Ko.formatLimitDefinition={keyword:Object.keys(tl),type:"string",schemaType:"string",$data:!0,error:pM,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 dM.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}),f=e.const("fmt",(0,cr._)`${w}[${c.schemaCode}]`);t.fail$data((0,cr.or)((0,cr._)`typeof ${f} != "object"`,(0,cr._)`${f} instanceof RegExp`,(0,cr._)`typeof ${f}.compare != "function"`,p(f)))}function u(){let w=c.schema,f=a.formats[w];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${w}" does not define "compare" function`);let h=e.scopeValue("formats",{key:w,ref:f,code:i.code.formats?(0,cr._)`${i.code.formats}${(0,cr.getProperty)(w)}`:void 0});t.fail$data(p(h))}function p(w){return(0,cr._)`${w}.compare(${r}, ${n}) ${tl[o].fail} 0`}},dependencies:["format"]};var hM=t=>(t.addKeyword(Ko.formatLimitDefinition),t);Ko.default=hM});var gS=Z((_i,mS)=>{"use strict";Object.defineProperty(_i,"__esModule",{value:!0});var Wo=dS(),fM=pS(),Km=he(),hS=new Km.Name("fullFormats"),mM=new Km.Name("fastFormats"),Wm=(t,e={keywords:!0})=>{if(Array.isArray(e))return fS(t,e,Wo.fullFormats,hS),t;let[r,n]=e.mode==="fast"?[Wo.fastFormats,mM]:[Wo.fullFormats,hS],o=e.formats||Wo.formatNames;return fS(t,o,r,n),e.keywords&&(0,fM.default)(t),t};Wm.get=(t,e="full")=>{let n=(e==="fast"?Wo.fastFormats:Wo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function fS(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Km._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}mS.exports=_i=Wm;Object.defineProperty(_i,"__esModule",{value:!0});_i.default=Wm});function gM(){let t=new yS.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,bS.default)(t),t}var yS,bS,rl,wS=C(()=>{yS=gl(qm(),1),bS=gl(gS(),1);rl=class{constructor(e){this._ajv=e??gM()}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 nl,vS=C(()=>{Io();nl=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)),p=new Set(s.filter(w=>w.type==="tool_result").map(w=>w.toolUseId));if(u.size!==p.size||![...u].every(w=>p.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},Hs,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},Ao,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 _S(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 xS(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 kS=C(()=>{});var ol,$S=C(()=>{Ex();Io();wS();Cs();vS();kS();ol=class extends wc{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Fs.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 rl,this.setRequestHandler(ah,n=>this._oninitialize(n)),this.setNotificationHandler(ch,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(mh,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Fs.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new nl(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Tx(this._capabilities,e)}setRequestHandler(e,r){let o=Xr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=So(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=Yr(Po,c);if(!u.success){let h=u.error instanceof Error?u.error.message:String(u.error);throw new J(te.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:p}=u.data,w=await Promise.resolve(r(c,l));if(p.task){let h=Yr(Eo,w);if(!h.success){let b=h.error instanceof Error?h.error.message:String(h.error);throw new J(te.InvalidParams,`Invalid task creation result: ${b}`)}return h.data}let f=Yr(ac,w);if(!f.success){let h=f.error instanceof Error?f.error.message:String(f.error);throw new J(te.InvalidParams,`Invalid tools/call result: ${h}`)}return f.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){xS(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&_S(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:T_.includes(r)?r:rh,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"},Ha)}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(p=>p.type==="tool_use").map(p=>p.id)),u=new Set(o.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==u.size||![...l].every(p=>u.has(p)))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},gh,r):this.request({method:"sampling/createMessage",params:e},Hs,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},Ao,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},Ao,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new J(te.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof J?i:new J(te.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},yh,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 Gm(t){return!!t&&typeof t=="object"&&TS in t}function ES(t){return t[TS]?.complete}var TS,SS,RS=C(()=>{TS=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(SS||(SS={}))});var PS=C(()=>{});function bM(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"),!yM.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 wM(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 Jm(t){let e=bM(t);return wM(t,e.warnings),e.isValid}var yM,AS=C(()=>{yM=/^[A-Za-z0-9._-]{1,128}$/});var sl,IS=C(()=>{sl=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 NS(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function zS(t){return"_def"in t||"_zod"in t||NS(t)}function Ym(t){return typeof t!="object"||t===null||zS(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(NS)}function OS(t){if(t){if(Ym(t))return Un(t);if(!zS(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function _M(t){let e=Xr(t);return e?Object.entries(e).map(([r,n])=>{let o=Yv(n),s=Xv(n);return{name:r,description:o,required:!s}}):[]}function dn(t){let r=Xr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=So(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function CS(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var il,vM,xi,jS=C(()=>{$S();Cs();ef();Io();RS();PS();AS();IS();An();il=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 ol(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new sl(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(dn(ic)),this.server.assertCanSetRequestHandler(dn(Po)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(ic,()=>({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=$o(r.inputSchema);return o?Yh(o,{strictUnions:!0,pipeStrategy:"input"}):vM})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=$o(r.outputSchema);o&&(n.outputSchema=Yh(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Po,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new J(te.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new J(te.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 J(te.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new J(te.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 J&&n.code===te.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=$o(e.inputSchema)??e.inputSchema,i=await Da(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Ma(a);throw new J(te.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 J(te.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=$o(e.outputSchema),s=await Da(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Ma(i);throw new J(te.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 p=await n.taskStore.getTask(c);if(!p)throw new J(te.InternalError,`Task ${c} not found during polling`);l=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(dn(cc)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(cc,async e=>{switch(e.params.ref.type){case"ref/prompt":return B_(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Z_(e),this.handleResourceCompletion(e,e.params.ref);default:throw new J(te.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new J(te.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new J(te.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return xi;let s=Xr(n.argsSchema)?.[e.params.argument.name];if(!Gm(s))return xi;let i=ES(s);if(!i)return xi;let a=await i(e.params.argument.value,e.params.context);return CS(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 xi;throw new J(te.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return xi;let s=await o(e.params.argument.value,e.params.context);return CS(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(dn(tc)),this.server.assertCanSetRequestHandler(dn(rc)),this.server.assertCanSetRequestHandler(dn(nc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(tc,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(rc,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(nc,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new J(te.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 J(te.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(dn(oc)),this.server.assertCanSetRequestHandler(dn(sc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(oc,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?_M(r.argsSchema):void 0}))})),this.server.setRequestHandler(sc,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new J(te.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new J(te.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=$o(n.argsSchema),s=await Da(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",l=Ma(c);throw new J(te.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:Un(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=Un(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 Gm(l)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,l){Jm(e);let u={title:r,description:n,inputSchema:OS(o),outputSchema:OS(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:p=>{typeof p.name<"u"&&p.name!==e&&(typeof p.name=="string"&&Jm(p.name),delete this._registeredTools[e],p.name&&(this._registeredTools[p.name]=u)),typeof p.title<"u"&&(u.title=p.title),typeof p.description<"u"&&(u.description=p.description),typeof p.paramsSchema<"u"&&(u.inputSchema=Un(p.paramsSchema)),typeof p.outputSchema<"u"&&(u.outputSchema=Un(p.outputSchema)),typeof p.callback<"u"&&(u.handler=p.callback),typeof p.annotations<"u"&&(u.annotations=p.annotations),typeof p._meta<"u"&&(u._meta=p._meta),typeof p.enabled<"u"&&(u.enabled=p.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(Ym(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Ym(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()}},vM={type:"object",properties:{}};xi={completion:{values:[],hasMore:!1}}});function kM(t){return N_.parse(JSON.parse(t))}function LS(t){return JSON.stringify(t)+`
2041
- `}var xM,al,DS=C(()=>{Io();xM=10*1024*1024,al=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??xM}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(`
2042
- `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),kM(r)}clear(){this._buffer=void 0}}});import MS from"node:process";var cl,US=C(()=>{DS();cl=class{constructor(e=MS.stdin,r=MS.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 al({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=LS(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var qS,BS=C(()=>{qS=[]});var YS={};Yo(YS,{AUTHORING_MCP_SERVER_NAME:()=>VS,AUTHORING_MCP_SERVER_VERSION:()=>KS,AUTHORING_RESOURCES:()=>AM,AUTHORING_TOOLS:()=>PM,AUTHORING_TOOLS_PUBLIC:()=>JS,buildAuthoringMcpServer:()=>GS,resolveSamplesDir:()=>WS,runAuthoringMcpServer:()=>IM});import{promises as $M}from"node:fs";import{isAbsolute as SM,resolve as ll,sep as TM}from"node:path";function HS(){return FS??=import("../mcp/grounding.js").then(e=>e,()=>null),FS}function WS(t,e){if(e===void 0)return ll(process.cwd(),t??"samples");let r=ll(e);if(t===void 0)return r;if(SM(t))return null;let n=ll(r,t);return n===r||n.startsWith(r+TM)?n:null}function He(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function RM(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 GS(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let f=await Xt(t.baseUrl);if(!f)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:f.baseUrl,token:f.token}}let r=t.grounding??{},n=await HS(),o=null;if(n)try{let f=await e();o={surface:"mcp-authoring",baseUrl:f.baseUrl,token:f.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(f=>({id:f.id,record_type:f.record_type,intent:f.intent}))}catch{c=[]}}let l=o?await RM(o,r):null,u=new il({name:VS,version:KS},n?{instructions:n.renderAuthoringInstructions({baseUrl:t.displayBaseUrl??o?.baseUrl??t.baseUrl??"this instance",sources:s,recipeIntents:c,promptNames:a.map(f=>f.id),deployedExtensions:l,docsToken:r.docsToken??n.docsPublicToken()})}:void 0);if(n&&o){let f=o;for(let h of a)u.registerPrompt(h.id,{title:h.name,description:h.description},async()=>{let b=await n.getMcpPromptSkill(f,h.id,r);if(!b)throw new Error(`unknown prompt: ${h.id}`);return{description:b.description,messages:[{role:"user",content:{type:"text",text:(b.prompts??[]).join(`
2047
+ deps: ${r}}`};var J1={keyword:"dependencies",type:"object",schemaType:"object",error:vr.error,code(t){let[e,r]=Y1(t);P$(t,e),A$(t,r)}};function Y1({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 P$(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,vi.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,vi.checkReportMissingProp)(t,l)}):(r.if((0,km._)`${c} && (${(0,vi.checkMissingProp)(t,a,s)})`),(0,vi.reportMissingProp)(t,s),r.else())}}vr.validatePropertyDeps=P$;function A$(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,G1.alwaysValidSchema)(s,e[a])||(r.if((0,vi.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))}vr.validateSchemaDeps=A$;vr.default=J1});var C$=Z($m=>{"use strict";Object.defineProperty($m,"__esModule",{value:!0});var O$=he(),X1=Se(),Q1={message:"property name must be valid",params:({params:t})=>(0,O$._)`{propertyName: ${t.propertyName}}`},eD={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Q1,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,X1.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,O$.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};$m.default=eD});var Tm=Z(Sm=>{"use strict";Object.defineProperty(Sm,"__esModule",{value:!0});var Jc=Vt(),ar=he(),tD=zr(),Yc=Se(),rD={message:"must NOT have additional properties",params:({params:t})=>(0,ar._)`{additionalProperty: ${t.additionalProperty}}`},nD={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:rD,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Yc.alwaysValidSchema)(i,r))return;let l=(0,Jc.allSchemaProperties)(n.properties),u=(0,Jc.allSchemaProperties)(n.patternProperties);p(),t.ok((0,ar._)`${s} === ${tD.default.errors}`);function p(){e.forIn("key",o,$=>{!l.length&&!u.length?h($):e.if(w($),()=>h($))})}function w($){let E;if(l.length>8){let P=(0,Yc.schemaRefOrVal)(i,n.properties,"properties");E=(0,Jc.isOwnProperty)(e,P,$)}else l.length?E=(0,ar.or)(...l.map(P=>(0,ar._)`${$} === ${P}`)):E=ar.nil;return u.length&&(E=(0,ar.or)(E,...u.map(P=>(0,ar._)`${(0,Jc.usePattern)(t,P)}.test(${$})`))),(0,ar.not)(E)}function f($){e.code((0,ar._)`delete ${o}[${$}]`)}function h($){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f($);return}if(r===!1){t.setParams({additionalProperty:$}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Yc.alwaysValidSchema)(i,r)){let E=e.name("valid");c.removeAdditional==="failing"?(b($,E,!1),e.if((0,ar.not)(E),()=>{t.reset(),f($)})):(b($,E),a||e.if((0,ar.not)(E),()=>e.break()))}}function b($,E,P){let z={keyword:"additionalProperties",dataProp:$,dataPropType:Yc.Type.Str};P===!1&&Object.assign(z,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(z,E)}}};Sm.default=nD});var j$=Z(Rm=>{"use strict";Object.defineProperty(Rm,"__esModule",{value:!0});var oD=ii(),N$=Vt(),Em=Se(),z$=Tm(),sD={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&&z$.default.code(new oD.KeywordCxt(s,z$.default,"additionalProperties"));let i=(0,N$.allSchemaProperties)(r);for(let p of i)s.definedProperties.add(p);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Em.mergeEvaluated.props(e,(0,Em.toHash)(i),s.props));let a=i.filter(p=>!(0,Em.alwaysValidSchema)(s,r[p]));if(a.length===0)return;let c=e.name("valid");for(let p of a)l(p)?u(p):(e.if((0,N$.propertyInData)(e,o,p,s.opts.ownProperties)),u(p),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(p),t.ok(c);function l(p){return s.opts.useDefaults&&!s.compositeRule&&r[p].default!==void 0}function u(p){t.subschema({keyword:"properties",schemaProp:p,dataProp:p},c)}}};Rm.default=sD});var U$=Z(Pm=>{"use strict";Object.defineProperty(Pm,"__esModule",{value:!0});var L$=Vt(),Xc=he(),D$=Se(),M$=Se(),iD={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,L$.allSchemaProperties)(r),c=a.filter(b=>(0,D$.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 Xc.Name)&&(s.props=(0,M$.evaluatedPropsToName)(e,s.props));let{props:p}=s;w();function w(){for(let b of a)l&&f(b),s.allErrors?h(b):(e.var(u,!0),h(b),e.if(u))}function f(b){for(let $ in l)new RegExp(b).test($)&&(0,D$.checkStrictMode)(s,`property ${$} matches pattern ${b} (use allowMatchingProperties)`)}function h(b){e.forIn("key",n,$=>{e.if((0,Xc._)`${(0,L$.usePattern)(t,b)}.test(${$})`,()=>{let E=c.includes(b);E||t.subschema({keyword:"patternProperties",schemaProp:b,dataProp:$,dataPropType:M$.Type.Str},u),s.opts.unevaluated&&p!==!0?e.assign((0,Xc._)`${p}[${$}]`,!0):!E&&!s.allErrors&&e.if((0,Xc.not)(u),()=>e.break())})})}}};Pm.default=iD});var q$=Z(Am=>{"use strict";Object.defineProperty(Am,"__esModule",{value:!0});var aD=Se(),cD={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,aD.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"}};Am.default=cD});var B$=Z(Im=>{"use strict";Object.defineProperty(Im,"__esModule",{value:!0});var lD=Vt(),uD={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:lD.validateUnion,error:{message:"must match a schema in anyOf"}};Im.default=uD});var Z$=Z(Om=>{"use strict";Object.defineProperty(Om,"__esModule",{value:!0});var Qc=he(),dD=Se(),pD={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Qc._)`{passingSchemas: ${t.passing}}`},hD={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:pD,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,p)=>{let w;(0,dD.alwaysValidSchema)(o,u)?e.var(c,!0):w=t.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},c),p>0&&e.if((0,Qc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Qc._)`[${a}, ${p}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,p),w&&t.mergeEvaluated(w,Qc.Name)})})}}};Om.default=hD});var F$=Z(Cm=>{"use strict";Object.defineProperty(Cm,"__esModule",{value:!0});var fD=Se(),mD={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,fD.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Cm.default=mD});var K$=Z(Nm=>{"use strict";Object.defineProperty(Nm,"__esModule",{value:!0});var el=he(),V$=Se(),gD={message:({params:t})=>(0,el.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,el._)`{failingKeyword: ${t.ifClause}}`},yD={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:gD,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,V$.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=H$(n,"then"),s=H$(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,el.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,p){return()=>{let w=t.subschema({keyword:u},a);e.assign(i,a),t.mergeValidEvaluated(w,i),p?e.assign(p,(0,el._)`${u}`):t.setParams({ifClause:u})}}}};function H$(t,e){let r=t.schema[e];return r!==void 0&&!(0,V$.alwaysValidSchema)(t,r)}Nm.default=yD});var W$=Z(zm=>{"use strict";Object.defineProperty(zm,"__esModule",{value:!0});var bD=Se(),wD={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,bD.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};zm.default=wD});var G$=Z(jm=>{"use strict";Object.defineProperty(jm,"__esModule",{value:!0});var vD=bm(),_D=S$(),xD=wm(),kD=E$(),$D=R$(),SD=I$(),TD=C$(),ED=Tm(),RD=j$(),PD=U$(),AD=q$(),ID=B$(),OD=Z$(),CD=F$(),ND=K$(),zD=W$();function jD(t=!1){let e=[AD.default,ID.default,OD.default,CD.default,ND.default,zD.default,TD.default,ED.default,SD.default,RD.default,PD.default];return t?e.push(_D.default,kD.default):e.push(vD.default,xD.default),e.push($D.default),e}jm.default=jD});var J$=Z(Lm=>{"use strict";Object.defineProperty(Lm,"__esModule",{value:!0});var We=he(),LD={message:({schemaCode:t})=>(0,We.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,We._)`{format: ${t}}`},DD={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:LD,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:l,schemaEnv:u,self:p}=a;if(!c.validateFormats)return;o?w():f();function w(){let h=r.scopeValue("formats",{ref:p.formats,code:c.code.formats}),b=r.const("fDef",(0,We._)`${h}[${i}]`),$=r.let("fType"),E=r.let("format");r.if((0,We._)`typeof ${b} == "object" && !(${b} instanceof RegExp)`,()=>r.assign($,(0,We._)`${b}.type || "string"`).assign(E,(0,We._)`${b}.validate`),()=>r.assign($,(0,We._)`"string"`).assign(E,b)),t.fail$data((0,We.or)(P(),z()));function P(){return c.strictSchema===!1?We.nil:(0,We._)`${i} && !${E}`}function z(){let B=u.$async?(0,We._)`(${b}.async ? await ${E}(${n}) : ${E}(${n}))`:(0,We._)`${E}(${n})`,W=(0,We._)`(typeof ${E} == "function" ? ${B} : ${E}.test(${n}))`;return(0,We._)`${E} && ${E} !== true && ${$} === ${e} && !${W}`}}function f(){let h=p.formats[s];if(!h){P();return}if(h===!0)return;let[b,$,E]=z(h);b===e&&t.pass(B());function P(){if(c.strictSchema===!1){p.logger.warn(W());return}throw new Error(W());function W(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function z(W){let Ve=W instanceof RegExp?(0,We.regexpCode)(W):c.code.formats?(0,We._)`${c.code.formats}${(0,We.getProperty)(s)}`:void 0,Ye=r.scopeValue("formats",{key:s,ref:W,code:Ve});return typeof W=="object"&&!(W instanceof RegExp)?[W.type||"string",W.validate,(0,We._)`${Ye}.validate`]:["string",W,Ye]}function B(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!u.$async)throw new Error("async format in sync schema");return(0,We._)`await ${E}(${n})`}return typeof $=="function"?(0,We._)`${E}(${n})`:(0,We._)`${E}.test(${n})`}}}};Lm.default=DD});var Y$=Z(Dm=>{"use strict";Object.defineProperty(Dm,"__esModule",{value:!0});var MD=J$(),UD=[MD.default];Dm.default=UD});var X$=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 eS=Z(Mm=>{"use strict";Object.defineProperty(Mm,"__esModule",{value:!0});var qD=a$(),BD=_$(),ZD=G$(),FD=Y$(),Q$=X$(),HD=[qD.default,BD.default,(0,ZD.default)(),FD.default,Q$.metadataVocabulary,Q$.contentVocabulary];Mm.default=HD});var rS=Z(tl=>{"use strict";Object.defineProperty(tl,"__esModule",{value:!0});tl.DiscrError=void 0;var tS;(function(t){t.Tag="tag",t.Mapping="mapping"})(tS||(tl.DiscrError=tS={}))});var oS=Z(qm=>{"use strict";Object.defineProperty(qm,"__esModule",{value:!0});var Fo=he(),Um=rS(),nS=jc(),VD=ai(),KD=Se(),WD={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,Fo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},GD={keyword:"discriminator",type:"object",schemaType:"object",error:WD,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,Fo._)`${r}${(0,Fo.getProperty)(a)}`);e.if((0,Fo._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:Um.DiscrError.Tag,tag:l,tagName:a})),t.ok(c);function u(){let f=w();e.if(!1);for(let h in f)e.elseIf((0,Fo._)`${l} === ${h}`),e.assign(c,p(f[h]));e.else(),t.error(!1,{discrError:Um.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function p(f){let h=e.name("valid"),b=t.subschema({keyword:"oneOf",schemaProp:f},h);return t.mergeEvaluated(b,Fo.Name),h}function w(){var f;let h={},b=E(o),$=!0;for(let B=0;B<i.length;B++){let W=i[B];if(W?.$ref&&!(0,KD.schemaHasRulesButRef)(W,s.self.RULES)){let Ye=W.$ref;if(W=nS.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Ye),W instanceof nS.SchemaEnv&&(W=W.schema),W===void 0)throw new VD.default(s.opts.uriResolver,s.baseId,Ye)}let Ve=(f=W?.properties)===null||f===void 0?void 0:f[a];if(typeof Ve!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);$=$&&(b||E(W)),P(Ve,B)}if(!$)throw new Error(`discriminator: "${a}" must be required`);return h;function E({required:B}){return Array.isArray(B)&&B.includes(a)}function P(B,W){if(B.const)z(B.const,W);else if(B.enum)for(let Ve of B.enum)z(Ve,W);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function z(B,W){if(typeof B!="string"||B in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[B]=W}}}};qm.default=GD});var sS=Z((Q9,JD)=>{JD.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 Zm=Z((De,Bm)=>{"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 YD=t$(),XD=eS(),QD=oS(),iS=sS(),eM=["/properties"],rl="http://json-schema.org/draft-07/schema",Ho=class extends YD.default{_addVocabularies(){super._addVocabularies(),XD.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(QD.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(iS,eM):iS;this.addMetaSchema(e,rl,!1),this.refs["http://json-schema.org/schema"]=rl}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(rl)?rl:void 0)}};De.Ajv=Ho;Bm.exports=De=Ho;Bm.exports.Ajv=Ho;Object.defineProperty(De,"__esModule",{value:!0});De.default=Ho;var tM=ii();Object.defineProperty(De,"KeywordCxt",{enumerable:!0,get:function(){return tM.KeywordCxt}});var Vo=he();Object.defineProperty(De,"_",{enumerable:!0,get:function(){return Vo._}});Object.defineProperty(De,"str",{enumerable:!0,get:function(){return Vo.str}});Object.defineProperty(De,"stringify",{enumerable:!0,get:function(){return Vo.stringify}});Object.defineProperty(De,"nil",{enumerable:!0,get:function(){return Vo.nil}});Object.defineProperty(De,"Name",{enumerable:!0,get:function(){return Vo.Name}});Object.defineProperty(De,"CodeGen",{enumerable:!0,get:function(){return Vo.CodeGen}});var rM=Nc();Object.defineProperty(De,"ValidationError",{enumerable:!0,get:function(){return rM.default}});var nM=ai();Object.defineProperty(De,"MissingRefError",{enumerable:!0,get:function(){return nM.default}})});var fS=Z(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.formatNames=xr.fastFormats=xr.fullFormats=void 0;function _r(t,e){return{validate:t,compare:e}}xr.fullFormats={date:_r(uS,Km),time:_r(Hm(!0),Wm),"date-time":_r(aS(!0),pS),"iso-time":_r(Hm(),dS),"iso-date-time":_r(aS(),hS),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:lM,"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:gM,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:uM,int32:{type:"number",validate:hM},int64:{type:"number",validate:fM},float:{type:"number",validate:lS},double:{type:"number",validate:lS},password:!0,binary:!0};xr.fastFormats={...xr.fullFormats,date:_r(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Km),time:_r(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Wm),"date-time":_r(/^\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,pS),"iso-time":_r(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,dS),"iso-date-time":_r(/^\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,hS),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};xr.formatNames=Object.keys(xr.fullFormats);function oM(t){return t%4===0&&(t%100!==0||t%400===0)}var sM=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,iM=[0,31,28,31,30,31,30,31,31,30,31,30,31];function uS(t){let e=sM.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&&oM(r)?29:iM[n])}function Km(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Fm=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Hm(t){return function(r){let n=Fm.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 p=s-u*c,w=o-l*c-(p<0?1:0);return(w===23||w===-1)&&(p===59||p===-1)&&i<61}}function Wm(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 dS(t,e){if(!(t&&e))return;let r=Fm.exec(t),n=Fm.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 Vm=/t|\s/i;function aS(t){let e=Hm(t);return function(n){let o=n.split(Vm);return o.length===2&&uS(o[0])&&e(o[1])}}function pS(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function hS(t,e){if(!(t&&e))return;let[r,n]=t.split(Vm),[o,s]=e.split(Vm),i=Km(r,o);if(i!==void 0)return i||Wm(n,s)}var aM=/\/|:/,cM=/^(?:[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 lM(t){return aM.test(t)&&cM.test(t)}var cS=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function uM(t){return cS.lastIndex=0,cS.test(t)}var dM=-(2**31),pM=2**31-1;function hM(t){return Number.isInteger(t)&&t<=pM&&t>=dM}function fM(t){return Number.isInteger(t)}function lS(){return!0}var mM=/[^\\]\\Z/;function gM(t){if(mM.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var mS=Z(Ko=>{"use strict";Object.defineProperty(Ko,"__esModule",{value:!0});Ko.formatLimitDefinition=void 0;var yM=Zm(),cr=he(),un=cr.operators,nl={formatMaximum:{okStr:"<=",ok:un.LTE,fail:un.GT},formatMinimum:{okStr:">=",ok:un.GTE,fail:un.LT},formatExclusiveMaximum:{okStr:"<",ok:un.LT,fail:un.GTE},formatExclusiveMinimum:{okStr:">",ok:un.GT,fail:un.LTE}},bM={message:({keyword:t,schemaCode:e})=>(0,cr.str)`should be ${nl[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,cr._)`{comparison: ${nl[t].okStr}, limit: ${e}}`};Ko.formatLimitDefinition={keyword:Object.keys(nl),type:"string",schemaType:"string",$data:!0,error:bM,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 yM.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}),f=e.const("fmt",(0,cr._)`${w}[${c.schemaCode}]`);t.fail$data((0,cr.or)((0,cr._)`typeof ${f} != "object"`,(0,cr._)`${f} instanceof RegExp`,(0,cr._)`typeof ${f}.compare != "function"`,p(f)))}function u(){let w=c.schema,f=a.formats[w];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${w}" does not define "compare" function`);let h=e.scopeValue("formats",{key:w,ref:f,code:i.code.formats?(0,cr._)`${i.code.formats}${(0,cr.getProperty)(w)}`:void 0});t.fail$data(p(h))}function p(w){return(0,cr._)`${w}.compare(${r}, ${n}) ${nl[o].fail} 0`}},dependencies:["format"]};var wM=t=>(t.addKeyword(Ko.formatLimitDefinition),t);Ko.default=wM});var wS=Z((_i,bS)=>{"use strict";Object.defineProperty(_i,"__esModule",{value:!0});var Wo=fS(),vM=mS(),Gm=he(),gS=new Gm.Name("fullFormats"),_M=new Gm.Name("fastFormats"),Jm=(t,e={keywords:!0})=>{if(Array.isArray(e))return yS(t,e,Wo.fullFormats,gS),t;let[r,n]=e.mode==="fast"?[Wo.fastFormats,_M]:[Wo.fullFormats,gS],o=e.formats||Wo.formatNames;return yS(t,o,r,n),e.keywords&&(0,vM.default)(t),t};Jm.get=(t,e="full")=>{let n=(e==="fast"?Wo.fastFormats:Wo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function yS(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Gm._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}bS.exports=_i=Jm;Object.defineProperty(_i,"__esModule",{value:!0});_i.default=Jm});function xM(){let t=new vS.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,_S.default)(t),t}var vS,_S,ol,xS=C(()=>{vS=bl(Zm(),1),_S=bl(wS(),1);ol=class{constructor(e){this._ajv=e??xM()}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 sl,kS=C(()=>{Io();sl=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)),p=new Set(s.filter(w=>w.type==="tool_result").map(w=>w.toolUseId));if(u.size!==p.size||![...u].every(w=>p.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},Hs,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},Ao,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 $S(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 SS(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 TS=C(()=>{});var il,ES=C(()=>{Ax();Io();xS();Cs();kS();TS();il=class extends _c{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Fs.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 ol,this.setRequestHandler(lh,n=>this._oninitialize(n)),this.setNotificationHandler(uh,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(yh,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Fs.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new sl(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Px(this._capabilities,e)}setRequestHandler(e,r){let o=Xr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=So(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=Yr(Po,c);if(!u.success){let h=u.error instanceof Error?u.error.message:String(u.error);throw new J(te.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:p}=u.data,w=await Promise.resolve(r(c,l));if(p.task){let h=Yr(Eo,w);if(!h.success){let b=h.error instanceof Error?h.error.message:String(h.error);throw new J(te.InvalidParams,`Invalid task creation result: ${b}`)}return h.data}let f=Yr(lc,w);if(!f.success){let h=f.error instanceof Error?f.error.message:String(f.error);throw new J(te.InvalidParams,`Invalid tools/call result: ${h}`)}return f.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){SS(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&$S(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:P_.includes(r)?r:oh,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(p=>p.type==="tool_use").map(p=>p.id)),u=new Set(o.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==u.size||![...l].every(p=>u.has(p)))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},bh,r):this.request({method:"sampling/createMessage",params:e},Hs,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},Ao,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},Ao,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new J(te.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof J?i:new J(te.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},wh,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 Ym(t){return!!t&&typeof t=="object"&&PS in t}function AS(t){return t[PS]?.complete}var PS,RS,IS=C(()=>{PS=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(RS||(RS={}))});var OS=C(()=>{});function $M(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"),!kM.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 SM(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=$M(t);return SM(t,e.warnings),e.isValid}var kM,CS=C(()=>{kM=/^[A-Za-z0-9._-]{1,128}$/});var al,NS=C(()=>{al=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 LS(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function DS(t){return"_def"in t||"_zod"in t||LS(t)}function Qm(t){return typeof t!="object"||t===null||DS(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(LS)}function zS(t){if(t){if(Qm(t))return Un(t);if(!DS(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function EM(t){let e=Xr(t);return e?Object.entries(e).map(([r,n])=>{let o=e_(n),s=t_(n);return{name:r,description:o,required:!s}}):[]}function dn(t){let r=Xr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=So(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function jS(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var cl,TM,xi,MS=C(()=>{ES();Cs();rf();Io();IS();OS();CS();NS();An();cl=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 il(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new al(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(dn(cc)),this.server.assertCanSetRequestHandler(dn(Po)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(cc,()=>({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=$o(r.inputSchema);return o?Qh(o,{strictUnions:!0,pipeStrategy:"input"}):TM})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=$o(r.outputSchema);o&&(n.outputSchema=Qh(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Po,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new J(te.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new J(te.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 J(te.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new J(te.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 J&&n.code===te.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=$o(e.inputSchema)??e.inputSchema,i=await Ua(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=qa(a);throw new J(te.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 J(te.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=$o(e.outputSchema),s=await Ua(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=qa(i);throw new J(te.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 p=await n.taskStore.getTask(c);if(!p)throw new J(te.InternalError,`Task ${c} not found during polling`);l=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(dn(uc)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(uc,async e=>{switch(e.params.ref.type){case"ref/prompt":return H_(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return V_(e),this.handleResourceCompletion(e,e.params.ref);default:throw new J(te.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new J(te.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new J(te.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return xi;let s=Xr(n.argsSchema)?.[e.params.argument.name];if(!Ym(s))return xi;let i=AS(s);if(!i)return xi;let a=await i(e.params.argument.value,e.params.context);return jS(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 xi;throw new J(te.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return xi;let s=await o(e.params.argument.value,e.params.context);return jS(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(dn(nc)),this.server.assertCanSetRequestHandler(dn(oc)),this.server.assertCanSetRequestHandler(dn(sc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(nc,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(oc,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(sc,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new J(te.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 J(te.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(dn(ic)),this.server.assertCanSetRequestHandler(dn(ac)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ic,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?EM(r.argsSchema):void 0}))})),this.server.setRequestHandler(ac,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new J(te.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new J(te.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=$o(n.argsSchema),s=await Ua(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",l=qa(c);throw new J(te.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:Un(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=Un(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 Ym(l)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,l){Xm(e);let u={title:r,description:n,inputSchema:zS(o),outputSchema:zS(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:p=>{typeof p.name<"u"&&p.name!==e&&(typeof p.name=="string"&&Xm(p.name),delete this._registeredTools[e],p.name&&(this._registeredTools[p.name]=u)),typeof p.title<"u"&&(u.title=p.title),typeof p.description<"u"&&(u.description=p.description),typeof p.paramsSchema<"u"&&(u.inputSchema=Un(p.paramsSchema)),typeof p.outputSchema<"u"&&(u.outputSchema=Un(p.outputSchema)),typeof p.callback<"u"&&(u.handler=p.callback),typeof p.annotations<"u"&&(u.annotations=p.annotations),typeof p._meta<"u"&&(u._meta=p._meta),typeof p.enabled<"u"&&(u.enabled=p.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(Qm(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Qm(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()}},TM={type:"object",properties:{}};xi={completion:{values:[],hasMore:!1}}});function PM(t){return L_.parse(JSON.parse(t))}function US(t){return JSON.stringify(t)+`
2048
+ `}var RM,ll,qS=C(()=>{Io();RM=10*1024*1024,ll=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??RM}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(`
2049
+ `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),PM(r)}clear(){this._buffer=void 0}}});import BS from"node:process";var ul,ZS=C(()=>{qS();ul=class{constructor(e=BS.stdin,r=BS.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 ll({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=US(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var FS,HS=C(()=>{FS=[]});var eT={};Yo(eT,{AUTHORING_MCP_SERVER_NAME:()=>GS,AUTHORING_MCP_SERVER_VERSION:()=>JS,AUTHORING_RESOURCES:()=>jM,AUTHORING_TOOLS:()=>zM,AUTHORING_TOOLS_PUBLIC:()=>QS,buildAuthoringMcpServer:()=>XS,resolveSamplesDir:()=>YS,runAuthoringMcpServer:()=>LM});import{promises as AM}from"node:fs";import{isAbsolute as IM,resolve as dl,sep as OM}from"node:path";function WS(){return KS??=import("../mcp/grounding.js").then(e=>e,()=>null),KS}function YS(t,e){if(e===void 0)return dl(process.cwd(),t??"samples");let r=dl(e);if(t===void 0)return r;if(IM(t))return null;let n=dl(r,t);return n===r||n.startsWith(r+OM)?n:null}function He(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function NM(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 XS(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let f=await Xt(t.baseUrl);if(!f)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:f.baseUrl,token:f.token}}let r=t.grounding??{},n=await WS(),o=null;if(n)try{let f=await e();o={surface:"mcp-authoring",baseUrl:f.baseUrl,token:f.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(f=>({id:f.id,record_type:f.record_type,intent:f.intent}))}catch{c=[]}}let l=o?await NM(o,r):null,u=new cl({name:GS,version:JS},n?{instructions:n.renderAuthoringInstructions({baseUrl:t.displayBaseUrl??o?.baseUrl??t.baseUrl??"this instance",sources:s,recipeIntents:c,promptNames:a.map(f=>f.id),deployedExtensions:l,docsToken:r.docsToken??n.docsPublicToken()})}:void 0);if(n&&o){let f=o;for(let h of a)u.registerPrompt(h.id,{title:h.name,description:h.description},async()=>{let b=await n.getMcpPromptSkill(f,h.id,r);if(!b)throw new Error(`unknown prompt: ${h.id}`);return{description:b.description,messages:[{role:"user",content:{type:"text",text:(b.prompts??[]).join(`
2043
2050
 
2044
- `)}}]}})}u.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:f,token:h}=await e(),b=await fetch(`${f}/v1/catalog/records`,{headers:{Authorization:`Bearer ${h}`,Accept:"application/json"}});if(!b.ok)throw new Error(`catalog fetch failed: ${b.status}`);return He(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:A.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:A.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:f,source:h})=>{let{baseUrl:b,token:$}=await e(),E=h?`?source=${encodeURIComponent(h)}`:"",P=await fetch(`${b}/v1/catalog/records/${encodeURIComponent(f)}${E}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown record type "${f}" \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:A.array(A.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:A.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:f,source:h})=>{let{baseUrl:b,token:$}=await e(),E=new URLSearchParams({types:f.join(",")});h&&E.set("source",h);let P=await fetch(`${b}/v1/catalog/columns?${E}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(P.status===404)throw new Error(`none of those record types resolved: ${f.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:f,token:h}=await e(),b=await fetch(`${f}/v1/catalog/census`,{headers:{Authorization:`Bearer ${h}`,Accept:"application/json"}});if(!b.ok)throw new Error(`catalog census failed: ${b.status}`);return He(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:A.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:A.enum(ZS).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:A.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:f,kind:h,limit:b})=>{let{baseUrl:$,token:E}=await e(),P=new URLSearchParams({q:f});h&&P.set("kind",h),b!==void 0&&P.set("limit",String(b));let z=await fetch(`${$}/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:A.enum(ZS),externalId:A.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:f,externalId:h})=>{let{baseUrl:b,token:$}=await e(),E=await fetch(`${b}/v1/catalog/objects/${encodeURIComponent(f)}/${encodeURIComponent(h)}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(E.status===404)throw new Error(`unknown object ${f}:${h} \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:A.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:A.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:f,limit:h})=>{let{baseUrl:b,token:$}=await e(),E=new URLSearchParams({q:f});h!==void 0&&E.set("limit",String(h));let P=await fetch(`${b}/v1/kb/search?${E}`,{headers:{Authorization:`Bearer ${$}`,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:A.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:f})=>{let{baseUrl:h,token:b}=await e(),$=await fetch(`${h}/v1/kb/document/${encodeURIComponent(f)}`,{headers:{Authorization:`Bearer ${b}`,Accept:"application/json"}});if(!$.ok&&$.status!==404)throw new Error(`kb document fetch failed: ${$.status}`);return He(await $.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:A.boolean().optional()}},async({recordsOnly:f})=>{let{baseUrl:h,token:b}=await e();return{content:[{type:"text",text:await In({baseUrl:h,token:b,recordsOnly:f})}]}}),u.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:A.string(),event:A.string().optional(),template:A.enum(["require-field","enforce-format","blank"]).optional(),field:A.string().optional(),regex:A.string().optional(),source:A.string().optional(),id:A.string().optional()}},async f=>{let h=fr("hook",{recordType:f.recordType,event:f.event,template:f.template,field:f.field,regex:f.regex,source:f.source,id:f.id});return He({path:h.relativePath,content:h.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:A.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:A.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:A.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:A.string().optional().describe("Target record type (defaults to the trigger record type)."),event:A.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:A.string().optional()}},async f=>{let h=fr("conduit",{recordType:f.recordType,source:f.source,to:f.to,toRecordType:f.toRecordType,event:f.event,id:f.id});return He({path:h.relativePath,content:h.content})}),u.registerTool("scaffold_process",{title:"Scaffold a process",description:"Generate a process file body \u2014 an ordered sequence of record writes an app invokes and the platform runs on the server (does not write to disk; returns path + content).",inputSchema:{recordType:A.string().describe('Record type the first step writes, e.g. "purchaseOrder".'),then:A.string().optional().describe('Record type of a second step that waits for the first, e.g. "vendorBill".'),onFailure:A.enum(["stop","rollback"]).optional().describe("What the engine does when a step fails (default stop)."),id:A.string().optional()}},async f=>{let h=fr("process",{recordType:f.recordType,then:f.then,onFailure:f.onFailure,id:f.id});return He({path:h.relativePath,content:h.content})}),u.registerTool("author_conduit",{title:"Draft and check a conduit",description:'Ask the instance to WRITE a conduit from a plain-English intent and check it before staging it for review \u2014 the cross-source counterpart to the hook the healing agent drafts. Returns {status, intentId, id?, reason?}: "written" staged a proposal, "rejected_by_validation" says why it could not (including a target system this instance can only read from). Nothing is deployed \u2014 an administrator applies the staged bridge from the Conduits tab. Prefer scaffold_conduit when you intend to write the transform yourself.',inputSchema:{intent:A.string().describe(`What the bridge should do, in the operator's words, e.g. "when a shopify order is paid, raise the matching NetSuite sales order".`),fromSource:A.string().describe('Origin source the record arrives from, e.g. "shopify".'),fromRecordType:A.string().describe('Canonical record type the bridge triggers on, e.g. "order".'),toSource:A.string().describe('Target source the bridge writes into, e.g. "netsuite".'),toRecordType:A.string().describe('Canonical record type written on the target, e.g. "salesOrder".'),intentId:A.string().optional().describe("Correlation id for the audit trail. The instance mints one when omitted."),columns:A.array(A.string()).optional().describe("Narrow the target columns the transform may write. Defaults to the target record's own.")}},async f=>{let{baseUrl:h,token:b}=await e(),$=new ee({baseUrl:h,token:b});return He(await $.authorConduit({intent:f.intent,from:{source:f.fromSource,recordType:f.fromRecordType},to:{source:f.toSource,recordType:f.toRecordType},...f.intentId?{intentId:f.intentId}:{},...f.columns?.length?{columns:f.columns}:{}}))}),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:A.string().describe("The extension TS source."),samplesDir:A.string().optional().describe('Samples directory (default "samples").')}},async({source:f,samplesDir:h})=>{let b=WS(h,t.samplesRoot);if(b===null)return{content:[{type:"text",text:JSON.stringify({error:"samples_dir_refused",message:EM})}],isError:!0};let $;try{$=await cs(b)}catch(z){if(t.samplesRoot!==void 0)return{content:[{type:"text",text:JSON.stringify({error:"samples_unreadable",message:"the samples directory could not be read"})}],isError:!0};throw z}let E=await Qi(f,$.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:A.string(),recordType:A.string(),event:A.string(),source:A.string().describe('Adapter id or "standalone".'),sourceCode:A.string().describe("The verbatim extension TS."),extensionKind:A.string().optional()}},async f=>{let{baseUrl:h,token:b}=await e(),E=await new ee({baseUrl:h,token:b}).deploy({id:f.id,recordType:f.recordType,event:f.event,source:f.source,sourceCode:f.sourceCode,extensionKind:f.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:A.string(),limit:A.number().int().positive().optional()}},async({id:f,limit:h})=>{let{baseUrl:b,token:$}=await e(),E=new ee({baseUrl:b,token:$});return He({id:f,logs:await E.logs(f,h)})}),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:f,token:h}=await e(),b=new ee({baseUrl:f,token:h});return He(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:A.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:A.string().optional().describe("Display name (defaults to the slug)."),description:A.string().optional().describe("Short description.")}},async({slug:f,name:h,description:b})=>{let{baseUrl:$,token:E}=await e(),P=new ee({baseUrl:$,token:E});return He(await P.appsCreate({slug:f,name:h,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:A.string().describe("App slug or id.")}},async({app:f})=>{let{baseUrl:h,token:b}=await e(),$=new ee({baseUrl:h,token:b});return He(await $.appsPull(f))}),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:A.string().describe("App slug or id."),files:A.record(A.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:A.string().optional().describe("Short note stored with the revision.")}},async({app:f,files:h,note:b})=>{let{baseUrl:$,token:E}=await e(),P=new ee({baseUrl:$,token:E});return He(await P.appsPush(f,h,{note:b}))});let p=A.object({name:A.string().describe("Field name (lowercase identifier)."),type:A.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:A.boolean().optional()}),w=A.object({slug:A.string().describe("Table slug; the physical table is cr_<slug>."),displayName:A.string().optional(),fields:A.array(p).describe("At least one field."),rowLevelOwner:A.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:f,token:h}=await e(),b=new ee({baseUrl:f,token:h});return He(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:A.array(w),claimedBy:A.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:f,claimedBy:h})=>{let{baseUrl:b,token:$}=await e(),E=new ee({baseUrl:b,token:$});return He(await E.tablesPlan({tables:f,claimedBy:h}))}),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:A.array(w),claimedBy:A.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:f,claimedBy:h})=>{let{baseUrl:b,token:$}=await e(),E=new ee({baseUrl:b,token:$});return He(await E.tablesApply({tables:f,claimedBy:h}))}),u.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async f=>{let{baseUrl:h,token:b}=await e(),E=await(await fetch(`${h}/v1/catalog/records`,{headers:{Authorization:`Bearer ${b}`,Accept:"application/json"}})).text();return{contents:[{uri:f.href,mimeType:"application/json",text:E}]}}),u.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async f=>{let{baseUrl:h,token:b}=await e(),$=await In({baseUrl:h,token:b});return{contents:[{uri:f.href,mimeType:"text/plain",text:$}]}}),u.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async f=>{let h=ll(process.cwd(),"samples"),b=[];try{b=(await $M.readdir(h)).filter(E=>E.endsWith(".json"))}catch{b=[]}let $=await cs(h);return{contents:[{uri:f.href,mimeType:"application/json",text:JSON.stringify({files:b,samples:$.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 f=>{let h=await HS(),b=[];if(h){let{baseUrl:$,token:E}=await e();b=await h.listRecipesForSurface({surface:"mcp-authoring",baseUrl:$,token:E},r)}return{contents:[{uri:f.href,mimeType:"application/json",text:JSON.stringify({recipes:b})}]}}),u}async function IM(t={}){let e=await GS(t),r=new cl;await e.connect(r)}var ZS,FS,VS,KS,EM,JS,PM,AM,XS=C(()=>{jS();US();An();Gl();ss();Pr();iu();oa();BS();ZS=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];VS="turbobase-authoring",KS="0.1.0";EM="samplesDir must be a relative path inside the samples directory this server serves; absolute paths and paths that leave it are refused over the network.";JS=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","search_catalog","catalog_census","explain_object","generate_types","scaffold_hook","scaffold_conduit","scaffold_process","author_conduit","mock_test","deploy","tail_logs","apps_list","apps_create","apps_pull","apps_push","tables_list","tables_plan","tables_apply"],PM=[...JS,...qS],AM=["catalog:///","types://all","samples:///","recipes:///"]});import{spawn as ng}from"node:child_process";import{promises as be}from"node:fs";import{homedir as OM}from"node:os";import{basename as tT,dirname as Lr,join as Ot,relative as dl,resolve as ge,sep as rg}from"node:path";var xg=gl(_g(),1),{program:tU,createCommand:rU,createArgument:nU,createOption:oU,CommanderError:sU,InvalidArgumentError:iU,InvalidOptionArgumentError:aU,Command:kg,Argument:cU,Option:lU,Help:uU}=xg.default;Gl();ss();Pr();iu();Xi();import{promises as by}from"node:fs";function yy(t,e){return e===t?"same-type-merge":"different-type-mint"}var wy=4;function au(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=uo(t,"id"),r=uo(t,"on"),n=uo(t,"source"),o=uo(t,"recordType"),s=[];for(let c of t.matchAll(/\bto\s*:\s*\{([^}]*)\}/g)){let l=uo(c[1]??"","source"),u=uo(c[1]??"","recordType");l&&u&&s.push({source:l,recordType:u})}let i=s[0],a=/cycleBudget\s*:\s*(\d+)/.exec(t);if(!e||!n||!o||!i)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.source,toRecordType:i.recordType,targets:s,cycleBudget:a?Number(a[1]):wy}}function uo(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function TR(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 vy(t,e,r="fixture",n={}){let o=e.name??r,s=[],i;try{i=au(t)}catch(l){return{fixtureName:o,conduit:RR(),guards:s,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],targets:[],logs:[],error:l instanceof Error?l.message:String(l)}}let a=TR(e),c=Object.entries(e.atlasLinks??{}).map(([l,u])=>({key:l,resolved:u}));try{let l=await Yi(t,{resolveDir:n.resolveDir}),p=!!(await as(l,a,{member:"when",timeoutMs:Ji})).whenResult;s.push({name:"from.when",status:p?"passed":"failed",detail:p?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let w=e.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${w} vs cycleBudget=${i.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),s.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)"}),s.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!p)return{fixtureName:o,conduit:i,guards:s,whenPassed:p,atlasResolutions:c,wouldWriteBindings:[],targets:[],logs:[]};let f=[],h=[],b=[];for(let E=0;E<i.targets.length;E+=1){let P=i.targets[E],z=await as(l,{...a,materialized:b.map(Dr=>({...Dr}))},{member:"transform",stepIndex:E,timeoutMs:Ji});f.push(...z.effects.logs);let B=z.effects.result;if(!B||typeof B!="object")throw new Error(`conduit ${i.id} transform${i.targets.length>1?` (target ${E+1})`:""} returned no result (expected { patch, createdFrom? })`);let W=B,Ve=yy(i.fromRecordType,P.recordType),{wouldWriteBindings:Ye,masterAction:Gt}=ER(i,P,Ve,e);h.push({to:P,transformResult:W,applyBranch:Ve,wouldWriteBindings:Ye,masterAction:Gt}),b.push({source:P.source,recordType:P.recordType,masterTable:`<${P.recordType} master, dry-run>`,masterRowId:`<dry-run target ${E+1}>`,externalId:null})}let $=h[0];return{fixtureName:o,conduit:i,guards:s,whenPassed:p,atlasResolutions:c,transformResult:$.transformResult,applyBranch:$.applyBranch,wouldWriteBindings:$.wouldWriteBindings,masterAction:$.masterAction,targets:h,logs:f}}catch(l){return{fixtureName:o,conduit:i,guards:s,whenPassed:!1,atlasResolutions:c,wouldWriteBindings:[],targets:[],logs:[],error:l instanceof Error?l.message:String(l)}}}function ER(t,e,r,n){return r==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${n.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:n.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:e.source,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${e.recordType} master (source_system='${e.source}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:e.source,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:n.externalId,role:"replica",why:"firing source bound onto the created master (supplementary lineage; best-effort, may collide in a 1\u2192N fan)"}]}}function RR(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",targets:[],cycleBudget:wy}}async function _y(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 xy(t){let e=await by.readFile(t,"utf8");return JSON.parse(e)}function ky(t){return by.readFile(t,"utf8")}function $y(t,e){let r=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;let n=t.targets.length>1;if(!e){if(!t.whenPassed)return`replay ${t.fixtureName} [${r.id}]: WHEN-FAILED (conduit short-circuited)`;if(n){let a=t.targets.reduce((c,l)=>c+l.wouldWriteBindings.length,0);return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.targets.length} targets in sequence (${a} binding(s) would be written)`}return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`}let o=[];o.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),o.push(`conduit: ${r.id}`);let s=(r.targets.length>0?r.targets:[{source:r.toSource,recordType:r.toRecordType}]).map(a=>`${a.source}.${a.recordType}`).join(" \u2192 ");o.push(`route: ${r.fromSource}.${r.fromRecordType} \u2192 ${s}${r.on?` on=${r.on}`:""}`),o.push(""),o.push("guards (dispatch order):");for(let a of t.guards){let c=a.status==="passed"?"\u2713":a.status==="failed"?"\u2717":"\u2298";o.push(` ${c} ${a.name} [${a.status}] \u2014 ${a.detail}`)}if(o.push(""),o.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)o.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let a of t.atlasResolutions)o.push(` ${a.key} \u2192 ${a.resolved===null?"null (no Atlas link \u2014 noted)":a.resolved}`);if(!t.whenPassed)return o.push(""),o.push("transform: SKIPPED (from.when gate did not fire)."),o.join(`
2045
- `);let i=t.targets.length>0?t.targets:[{to:{source:r.toSource,recordType:r.toRecordType},transformResult:t.transformResult??{patch:{}},applyBranch:t.applyBranch??"different-type-mint",wouldWriteBindings:t.wouldWriteBindings,masterAction:t.masterAction??""}];if(i.forEach((a,c)=>{let l=n?` (target ${c+1}/${i.length}: ${a.to.source}.${a.to.recordType})`:"";o.push(""),o.push(`transform${l} \u2192 patch:`),o.push(PR(JSON.stringify(a.transformResult.patch??{},null,2)," ")),a.transformResult.createdFrom&&o.push(` createdFrom: ${JSON.stringify(a.transformResult.createdFrom)}`),o.push(""),o.push(`apply-branch${l}: ${a.applyBranch}`),o.push(` ${a.masterAction}`),o.push(""),o.push(`bindings that WOULD be written (txn_source_link)${l}:`);for(let u of a.wouldWriteBindings)o.push(` ${u.source} role=${u.role} external_id=${u.externalId??"null"} \u2014 ${u.why}`)}),t.logs.length>0){o.push(""),o.push("conduit logs:");for(let a of t.logs)o.push(` [${a.level}] ${a.message}${a.meta?` ${JSON.stringify(a.meta)}`:""}`)}return o.join(`
2046
- `)}function PR(t,e){return t.split(`
2051
+ `)}}]}})}u.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:f,token:h}=await e(),b=await fetch(`${f}/v1/catalog/records`,{headers:{Authorization:`Bearer ${h}`,Accept:"application/json"}});if(!b.ok)throw new Error(`catalog fetch failed: ${b.status}`);return He(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:A.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:A.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:f,source:h})=>{let{baseUrl:b,token:$}=await e(),E=h?`?source=${encodeURIComponent(h)}`:"",P=await fetch(`${b}/v1/catalog/records/${encodeURIComponent(f)}${E}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown record type "${f}" \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:A.array(A.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:A.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:f,source:h})=>{let{baseUrl:b,token:$}=await e(),E=new URLSearchParams({types:f.join(",")});h&&E.set("source",h);let P=await fetch(`${b}/v1/catalog/columns?${E}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(P.status===404)throw new Error(`none of those record types resolved: ${f.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:f,token:h}=await e(),b=await fetch(`${f}/v1/catalog/census`,{headers:{Authorization:`Bearer ${h}`,Accept:"application/json"}});if(!b.ok)throw new Error(`catalog census failed: ${b.status}`);return He(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:A.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:A.enum(VS).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:A.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:f,kind:h,limit:b})=>{let{baseUrl:$,token:E}=await e(),P=new URLSearchParams({q:f});h&&P.set("kind",h),b!==void 0&&P.set("limit",String(b));let z=await fetch(`${$}/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:A.enum(VS),externalId:A.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:f,externalId:h})=>{let{baseUrl:b,token:$}=await e(),E=await fetch(`${b}/v1/catalog/objects/${encodeURIComponent(f)}/${encodeURIComponent(h)}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(E.status===404)throw new Error(`unknown object ${f}:${h} \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:A.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:A.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:f,limit:h})=>{let{baseUrl:b,token:$}=await e(),E=new URLSearchParams({q:f});h!==void 0&&E.set("limit",String(h));let P=await fetch(`${b}/v1/kb/search?${E}`,{headers:{Authorization:`Bearer ${$}`,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:A.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:f})=>{let{baseUrl:h,token:b}=await e(),$=await fetch(`${h}/v1/kb/document/${encodeURIComponent(f)}`,{headers:{Authorization:`Bearer ${b}`,Accept:"application/json"}});if(!$.ok&&$.status!==404)throw new Error(`kb document fetch failed: ${$.status}`);return He(await $.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:A.boolean().optional()}},async({recordsOnly:f})=>{let{baseUrl:h,token:b}=await e();return{content:[{type:"text",text:await In({baseUrl:h,token:b,recordsOnly:f})}]}}),u.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:A.string(),event:A.string().optional(),template:A.enum(["require-field","enforce-format","blank"]).optional(),field:A.string().optional(),regex:A.string().optional(),source:A.string().optional(),id:A.string().optional()}},async f=>{let h=fr("hook",{recordType:f.recordType,event:f.event,template:f.template,field:f.field,regex:f.regex,source:f.source,id:f.id});return He({path:h.relativePath,content:h.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:A.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:A.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:A.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:A.string().optional().describe("Target record type (defaults to the trigger record type)."),event:A.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:A.string().optional()}},async f=>{let h=fr("conduit",{recordType:f.recordType,source:f.source,to:f.to,toRecordType:f.toRecordType,event:f.event,id:f.id});return He({path:h.relativePath,content:h.content})}),u.registerTool("scaffold_process",{title:"Scaffold a process",description:"Generate a process file body \u2014 an ordered sequence of record writes an app invokes and the platform runs on the server (does not write to disk; returns path + content).",inputSchema:{recordType:A.string().describe('Record type the first step writes, e.g. "purchaseOrder".'),then:A.string().optional().describe('Record type of a second step that waits for the first, e.g. "vendorBill".'),onFailure:A.enum(["stop","rollback"]).optional().describe("What the engine does when a step fails (default stop)."),id:A.string().optional()}},async f=>{let h=fr("process",{recordType:f.recordType,then:f.then,onFailure:f.onFailure,id:f.id});return He({path:h.relativePath,content:h.content})}),u.registerTool("author_conduit",{title:"Draft and check a conduit",description:'Ask the instance to WRITE a conduit from a plain-English intent and check it before staging it for review \u2014 the cross-source counterpart to the hook the healing agent drafts. Returns {status, intentId, id?, reason?}: "written" staged a proposal, "rejected_by_validation" says why it could not (including a target system this instance can only read from). Nothing is deployed \u2014 an administrator applies the staged bridge from the Conduits tab. Prefer scaffold_conduit when you intend to write the transform yourself.',inputSchema:{intent:A.string().describe(`What the bridge should do, in the operator's words, e.g. "when a shopify order is paid, raise the matching NetSuite sales order".`),fromSource:A.string().describe('Origin source the record arrives from, e.g. "shopify".'),fromRecordType:A.string().describe('Canonical record type the bridge triggers on, e.g. "order".'),toSource:A.string().describe('Target source the bridge writes into, e.g. "netsuite".'),toRecordType:A.string().describe('Canonical record type written on the target, e.g. "salesOrder".'),intentId:A.string().optional().describe("Correlation id for the audit trail. The instance mints one when omitted."),columns:A.array(A.string()).optional().describe("Narrow the target columns the transform may write. Defaults to the target record's own.")}},async f=>{let{baseUrl:h,token:b}=await e(),$=new ee({baseUrl:h,token:b});return He(await $.authorConduit({intent:f.intent,from:{source:f.fromSource,recordType:f.fromRecordType},to:{source:f.toSource,recordType:f.toRecordType},...f.intentId?{intentId:f.intentId}:{},...f.columns?.length?{columns:f.columns}:{}}))}),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:A.string().describe("The extension TS source."),samplesDir:A.string().optional().describe('Samples directory (default "samples").')}},async({source:f,samplesDir:h})=>{let b=YS(h,t.samplesRoot);if(b===null)return{content:[{type:"text",text:JSON.stringify({error:"samples_dir_refused",message:CM})}],isError:!0};let $;try{$=await cs(b)}catch(z){if(t.samplesRoot!==void 0)return{content:[{type:"text",text:JSON.stringify({error:"samples_unreadable",message:"the samples directory could not be read"})}],isError:!0};throw z}let E=await ta(f,$.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:A.string(),recordType:A.string(),event:A.string(),source:A.string().describe('Adapter id or "standalone".'),sourceCode:A.string().describe("The verbatim extension TS."),extensionKind:A.string().optional()}},async f=>{let{baseUrl:h,token:b}=await e(),E=await new ee({baseUrl:h,token:b}).deploy({id:f.id,recordType:f.recordType,event:f.event,source:f.source,sourceCode:f.sourceCode,extensionKind:f.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:A.string(),limit:A.number().int().positive().optional()}},async({id:f,limit:h})=>{let{baseUrl:b,token:$}=await e(),E=new ee({baseUrl:b,token:$});return He({id:f,logs:await E.logs(f,h)})}),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:f,token:h}=await e(),b=new ee({baseUrl:f,token:h});return He(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:A.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:A.string().optional().describe("Display name (defaults to the slug)."),description:A.string().optional().describe("Short description.")}},async({slug:f,name:h,description:b})=>{let{baseUrl:$,token:E}=await e(),P=new ee({baseUrl:$,token:E});return He(await P.appsCreate({slug:f,name:h,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:A.string().describe("App slug or id.")}},async({app:f})=>{let{baseUrl:h,token:b}=await e(),$=new ee({baseUrl:h,token:b});return He(await $.appsPull(f))}),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:A.string().describe("App slug or id."),files:A.record(A.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:A.string().optional().describe("Short note stored with the revision.")}},async({app:f,files:h,note:b})=>{let{baseUrl:$,token:E}=await e(),P=new ee({baseUrl:$,token:E});return He(await P.appsPush(f,h,{note:b}))});let p=A.object({name:A.string().describe("Field name (lowercase identifier)."),type:A.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:A.boolean().optional()}),w=A.object({slug:A.string().describe("Table slug; the physical table is cr_<slug>."),displayName:A.string().optional(),fields:A.array(p).describe("At least one field."),rowLevelOwner:A.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:f,token:h}=await e(),b=new ee({baseUrl:f,token:h});return He(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:A.array(w),claimedBy:A.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:f,claimedBy:h})=>{let{baseUrl:b,token:$}=await e(),E=new ee({baseUrl:b,token:$});return He(await E.tablesPlan({tables:f,claimedBy:h}))}),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:A.array(w),claimedBy:A.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:f,claimedBy:h})=>{let{baseUrl:b,token:$}=await e(),E=new ee({baseUrl:b,token:$});return He(await E.tablesApply({tables:f,claimedBy:h}))}),u.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async f=>{let{baseUrl:h,token:b}=await e(),E=await(await fetch(`${h}/v1/catalog/records`,{headers:{Authorization:`Bearer ${b}`,Accept:"application/json"}})).text();return{contents:[{uri:f.href,mimeType:"application/json",text:E}]}}),u.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async f=>{let{baseUrl:h,token:b}=await e(),$=await In({baseUrl:h,token:b});return{contents:[{uri:f.href,mimeType:"text/plain",text:$}]}}),u.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async f=>{let h=dl(process.cwd(),"samples"),b=[];try{b=(await AM.readdir(h)).filter(E=>E.endsWith(".json"))}catch{b=[]}let $=await cs(h);return{contents:[{uri:f.href,mimeType:"application/json",text:JSON.stringify({files:b,samples:$.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 f=>{let h=await WS(),b=[];if(h){let{baseUrl:$,token:E}=await e();b=await h.listRecipesForSurface({surface:"mcp-authoring",baseUrl:$,token:E},r)}return{contents:[{uri:f.href,mimeType:"application/json",text:JSON.stringify({recipes:b})}]}}),u}async function LM(t={}){let e=await XS(t),r=new ul;await e.connect(r)}var VS,KS,GS,JS,CM,QS,zM,jM,tT=C(()=>{MS();ZS();An();Yl();ss();Pr();cu();ia();HS();VS=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];GS="turbobase-authoring",JS="0.1.0";CM="samplesDir must be a relative path inside the samples directory this server serves; absolute paths and paths that leave it are refused over the network.";QS=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","search_catalog","catalog_census","explain_object","generate_types","scaffold_hook","scaffold_conduit","scaffold_process","author_conduit","mock_test","deploy","tail_logs","apps_list","apps_create","apps_pull","apps_push","tables_list","tables_plan","tables_apply"],zM=[...QS,...FS],jM=["catalog:///","types://all","samples:///","recipes:///"]});import{spawn as sg}from"node:child_process";import{promises as be}from"node:fs";import{homedir as DM}from"node:os";import{basename as oT,dirname as Lr,join as Ot,relative as hl,resolve as ge,sep as og}from"node:path";var $g=bl(kg(),1),{program:aU,createCommand:cU,createArgument:lU,createOption:uU,CommanderError:dU,InvalidArgumentError:pU,InvalidOptionArgumentError:hU,Command:Sg,Argument:fU,Option:mU,Help:gU}=$g.default;Yl();ss();Pr();cu();ea();import{promises as _y}from"node:fs";function vy(t,e){return e===t?"same-type-merge":"different-type-mint"}var xy=4;function lu(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=uo(t,"id"),r=uo(t,"on"),n=uo(t,"source"),o=uo(t,"recordType"),s=[];for(let c of t.matchAll(/\bto\s*:\s*\{([^}]*)\}/g)){let l=uo(c[1]??"","source"),u=uo(c[1]??"","recordType");l&&u&&s.push({source:l,recordType:u})}let i=s[0],a=/cycleBudget\s*:\s*(\d+)/.exec(t);if(!e||!n||!o||!i)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.source,toRecordType:i.recordType,targets:s,cycleBudget:a?Number(a[1]):xy}}function uo(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function OR(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 ky(t,e,r="fixture",n={}){let o=e.name??r,s=[],i;try{i=lu(t)}catch(l){return{fixtureName:o,conduit:NR(),guards:s,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],targets:[],logs:[],error:l instanceof Error?l.message:String(l)}}let a=OR(e),c=Object.entries(e.atlasLinks??{}).map(([l,u])=>({key:l,resolved:u}));try{let l=await Qi(t,{resolveDir:n.resolveDir}),p=!!(await as(l,a,{member:"when",timeoutMs:Xi})).whenResult;s.push({name:"from.when",status:p?"passed":"failed",detail:p?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let w=e.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${w} vs cycleBudget=${i.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),s.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)"}),s.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!p)return{fixtureName:o,conduit:i,guards:s,whenPassed:p,atlasResolutions:c,wouldWriteBindings:[],targets:[],logs:[]};let f=[],h=[],b=[];for(let E=0;E<i.targets.length;E+=1){let P=i.targets[E],z=await as(l,{...a,materialized:b.map(Dr=>({...Dr}))},{member:"transform",stepIndex:E,timeoutMs:Xi});f.push(...z.effects.logs);let B=z.effects.result;if(!B||typeof B!="object")throw new Error(`conduit ${i.id} transform${i.targets.length>1?` (target ${E+1})`:""} returned no result (expected { patch, createdFrom? })`);let W=B,Ve=vy(i.fromRecordType,P.recordType),{wouldWriteBindings:Ye,masterAction:Gt}=CR(i,P,Ve,e);h.push({to:P,transformResult:W,applyBranch:Ve,wouldWriteBindings:Ye,masterAction:Gt}),b.push({source:P.source,recordType:P.recordType,masterTable:`<${P.recordType} master, dry-run>`,masterRowId:`<dry-run target ${E+1}>`,externalId:null})}let $=h[0];return{fixtureName:o,conduit:i,guards:s,whenPassed:p,atlasResolutions:c,transformResult:$.transformResult,applyBranch:$.applyBranch,wouldWriteBindings:$.wouldWriteBindings,masterAction:$.masterAction,targets:h,logs:f}}catch(l){return{fixtureName:o,conduit:i,guards:s,whenPassed:!1,atlasResolutions:c,wouldWriteBindings:[],targets:[],logs:[],error:l instanceof Error?l.message:String(l)}}}function CR(t,e,r,n){return r==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${n.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:n.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:e.source,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${e.recordType} master (source_system='${e.source}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:e.source,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:n.externalId,role:"replica",why:"firing source bound onto the created master (supplementary lineage; best-effort, may collide in a 1\u2192N fan)"}]}}function NR(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",targets:[],cycleBudget:xy}}async function $y(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 Sy(t){let e=await _y.readFile(t,"utf8");return JSON.parse(e)}function Ty(t){return _y.readFile(t,"utf8")}function Ey(t,e){let r=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;let n=t.targets.length>1;if(!e){if(!t.whenPassed)return`replay ${t.fixtureName} [${r.id}]: WHEN-FAILED (conduit short-circuited)`;if(n){let a=t.targets.reduce((c,l)=>c+l.wouldWriteBindings.length,0);return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.targets.length} targets in sequence (${a} binding(s) would be written)`}return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`}let o=[];o.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),o.push(`conduit: ${r.id}`);let s=(r.targets.length>0?r.targets:[{source:r.toSource,recordType:r.toRecordType}]).map(a=>`${a.source}.${a.recordType}`).join(" \u2192 ");o.push(`route: ${r.fromSource}.${r.fromRecordType} \u2192 ${s}${r.on?` on=${r.on}`:""}`),o.push(""),o.push("guards (dispatch order):");for(let a of t.guards){let c=a.status==="passed"?"\u2713":a.status==="failed"?"\u2717":"\u2298";o.push(` ${c} ${a.name} [${a.status}] \u2014 ${a.detail}`)}if(o.push(""),o.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)o.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let a of t.atlasResolutions)o.push(` ${a.key} \u2192 ${a.resolved===null?"null (no Atlas link \u2014 noted)":a.resolved}`);if(!t.whenPassed)return o.push(""),o.push("transform: SKIPPED (from.when gate did not fire)."),o.join(`
2052
+ `);let i=t.targets.length>0?t.targets:[{to:{source:r.toSource,recordType:r.toRecordType},transformResult:t.transformResult??{patch:{}},applyBranch:t.applyBranch??"different-type-mint",wouldWriteBindings:t.wouldWriteBindings,masterAction:t.masterAction??""}];if(i.forEach((a,c)=>{let l=n?` (target ${c+1}/${i.length}: ${a.to.source}.${a.to.recordType})`:"";o.push(""),o.push(`transform${l} \u2192 patch:`),o.push(zR(JSON.stringify(a.transformResult.patch??{},null,2)," ")),a.transformResult.createdFrom&&o.push(` createdFrom: ${JSON.stringify(a.transformResult.createdFrom)}`),o.push(""),o.push(`apply-branch${l}: ${a.applyBranch}`),o.push(` ${a.masterAction}`),o.push(""),o.push(`bindings that WOULD be written (txn_source_link)${l}:`);for(let u of a.wouldWriteBindings)o.push(` ${u.source} role=${u.role} external_id=${u.externalId??"null"} \u2014 ${u.why}`)}),t.logs.length>0){o.push(""),o.push("conduit logs:");for(let a of t.logs)o.push(` [${a.level}] ${a.message}${a.meta?` ${JSON.stringify(a.meta)}`:""}`)}return o.join(`
2053
+ `)}function zR(t,e){return t.split(`
2047
2054
  `).map(r=>e+r).join(`
2048
- `)}var AR="2026-01-01",Sy="2026-01-01T00:00:00.000Z";function IR(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"?AR:r.startsWith("timestamp")?Sy: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:Sy}:{}:r==="uuid"?"00000000-0000-0000-0000-000000000000":r==="array"||r.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function OR(t){let e={};for(let r of t.columns)e[r.name]=IR(r.pgType,r.name);return e}function CR(t,e={}){let r=e.event??"before_save";return{name:`${t.recordType} ${r} (generated)`,context:{recordType:t.recordType,event:r,source:t.source,payload:OR(t)},expect:e.expect??"pass"}}function Ty(t,e={}){return t.map(r=>({recordType:r.recordType,fixture:CR(r,e)}))}import{promises as Ey}from"node:fs";import{join as Ry,relative as NR,sep as zR}from"node:path";var jR=67324752,LR=33639248,DR=101010256,MR=(()=>{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 UR(t){let e=4294967295;for(let r=0;r<t.length;r++)e=MR[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}async function qR(t){let e=[];async function r(n){let o=await Ey.readdir(n,{withFileTypes:!0});for(let s of o){let i=Ry(n,s.name);s.isDirectory()?await r(i):s.isFile()&&e.push(NR(t,i).split(zR).join("/"))}}return await r(t),e.sort(),e}async function Py(t){let e=await qR(t),r=[],n=[],o=0;for(let a of e){let c=Buffer.from(a,"utf8"),l=await Ey.readFile(Ry(t,a)),u=UR(l),p=Buffer.alloc(30+c.length);p.writeUInt32LE(jR,0),p.writeUInt16LE(20,4),p.writeUInt16LE(0,6),p.writeUInt16LE(0,8),p.writeUInt32LE(u,14),p.writeUInt32LE(l.length,18),p.writeUInt32LE(l.length,22),p.writeUInt16LE(c.length,26),c.copy(p,30),r.push(p,l);let w=Buffer.alloc(46+c.length);w.writeUInt32LE(LR,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+=p.length+l.length}let s=Buffer.concat(n),i=Buffer.alloc(22);return i.writeUInt32LE(DR,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}}tu();function BR(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":/\bdefineProcess\s*[<(]/.test(t)?"process":"hook"}function ea(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function ZR(t){let e=FR(t,"from"),n=Ay(t,"to").map(o=>({source:ea(o,"source"),recordType:ea(o,"recordType")}));return{fromSource:e?ea(e,"source"):void 0,fromRecordType:e?ea(e,"recordType"):void 0,toSource:n[0]?.source,toRecordType:n[0]?.recordType,targets:n}}function FR(t,e){return Ay(t,e)[0]??null}function Ay(t,e){let r=[],n=new RegExp(`\\b${e}\\s*:\\s*\\{`,"g"),o;for(;(o=n.exec(t))!==null;){let s=0,i=o.index+o[0].length-1;for(let a=i;a<t.length;a+=1){let c=t[a];if(c==="{")s+=1;else if(c==="}"&&(s-=1,s===0)){r.push(t.slice(i+1,a)),n.lastIndex=a+1;break}}}return r}function HR(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 VR(t,e){let r=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return r?Number(r[1]):void 0}function KR(t){return/\bcreatedFrom\b/.test(t)}function Iy(t){let e=BR(t),r=[];if(e==="hook")return{kind:e,warnings:r};let{fromSource:n,fromRecordType:o,toRecordType:s,targets:i}=ZR(t);for(let u of i)if(n&&u.source&&n===u.source){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 ${o??"<type>"}\`) \u2014 a same-source transform belongs on the write path, not the cross-source bridge.`});break}let a=HR(t);if(a!==null){let u=/\bexternalId\b/.test(a),p=/\bfromSource\b/.test(a);!u&&!p&&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}``."})}let c=i.find(u=>u.recordType&&o&&u.recordType!==o)?.recordType??(o!==s?s:void 0);o&&c&&!KR(t)&&r.push({rule:"missing-created-from",message:`this conduit bridges '${o}' \u2192 '${c}' (different record types) but its transform never returns 'createdFrom' \u2014 the created ${c} 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 l=VR(t,"cycleBudget");return l!==void 0&&(l<1?r.push({rule:"cycle-budget-too-low",message:`cycleBudget=${l} 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)."}):l>20&&r.push({rule:"cycle-budget-too-high",message:`cycleBudget=${l} 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 Oy(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(`
2055
+ `)}var jR="2026-01-01",Ry="2026-01-01T00:00:00.000Z";function LR(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"?jR:r.startsWith("timestamp")?Ry: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:Ry}:{}:r==="uuid"?"00000000-0000-0000-0000-000000000000":r==="array"||r.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function DR(t){let e={};for(let r of t.columns)e[r.name]=LR(r.pgType,r.name);return e}function MR(t,e={}){let r=e.event??"before_save";return{name:`${t.recordType} ${r} (generated)`,context:{recordType:t.recordType,event:r,source:t.source,payload:DR(t)},expect:e.expect??"pass"}}function Py(t,e={}){return t.map(r=>({recordType:r.recordType,fixture:MR(r,e)}))}import{promises as Ay}from"node:fs";import{join as Iy,relative as UR,sep as qR}from"node:path";var BR=67324752,ZR=33639248,FR=101010256,HR=(()=>{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 VR(t){let e=4294967295;for(let r=0;r<t.length;r++)e=HR[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}async function KR(t){let e=[];async function r(n){let o=await Ay.readdir(n,{withFileTypes:!0});for(let s of o){let i=Iy(n,s.name);s.isDirectory()?await r(i):s.isFile()&&e.push(UR(t,i).split(qR).join("/"))}}return await r(t),e.sort(),e}async function Oy(t){let e=await KR(t),r=[],n=[],o=0;for(let a of e){let c=Buffer.from(a,"utf8"),l=await Ay.readFile(Iy(t,a)),u=VR(l),p=Buffer.alloc(30+c.length);p.writeUInt32LE(BR,0),p.writeUInt16LE(20,4),p.writeUInt16LE(0,6),p.writeUInt16LE(0,8),p.writeUInt32LE(u,14),p.writeUInt32LE(l.length,18),p.writeUInt32LE(l.length,22),p.writeUInt16LE(c.length,26),c.copy(p,30),r.push(p,l);let w=Buffer.alloc(46+c.length);w.writeUInt32LE(ZR,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+=p.length+l.length}let s=Buffer.concat(n),i=Buffer.alloc(22);return i.writeUInt32LE(FR,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}}nu();function WR(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":/\bdefineProcess\s*[<(]/.test(t)?"process":"hook"}function ra(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function GR(t){let e=JR(t,"from"),n=Cy(t,"to").map(o=>({source:ra(o,"source"),recordType:ra(o,"recordType")}));return{fromSource:e?ra(e,"source"):void 0,fromRecordType:e?ra(e,"recordType"):void 0,toSource:n[0]?.source,toRecordType:n[0]?.recordType,targets:n}}function JR(t,e){return Cy(t,e)[0]??null}function Cy(t,e){let r=[],n=new RegExp(`\\b${e}\\s*:\\s*\\{`,"g"),o;for(;(o=n.exec(t))!==null;){let s=0,i=o.index+o[0].length-1;for(let a=i;a<t.length;a+=1){let c=t[a];if(c==="{")s+=1;else if(c==="}"&&(s-=1,s===0)){r.push(t.slice(i+1,a)),n.lastIndex=a+1;break}}}return r}function YR(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 XR(t,e){let r=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return r?Number(r[1]):void 0}function QR(t){return/\bcreatedFrom\b/.test(t)}function Ny(t){let e=WR(t),r=[];if(e==="hook")return{kind:e,warnings:r};let{fromSource:n,fromRecordType:o,toRecordType:s,targets:i}=GR(t);for(let u of i)if(n&&u.source&&n===u.source){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 ${o??"<type>"}\`) \u2014 a same-source transform belongs on the write path, not the cross-source bridge.`});break}let a=YR(t);if(a!==null){let u=/\bexternalId\b/.test(a),p=/\bfromSource\b/.test(a);!u&&!p&&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}``."})}let c=i.find(u=>u.recordType&&o&&u.recordType!==o)?.recordType??(o!==s?s:void 0);o&&c&&!QR(t)&&r.push({rule:"missing-created-from",message:`this conduit bridges '${o}' \u2192 '${c}' (different record types) but its transform never returns 'createdFrom' \u2014 the created ${c} 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 l=XR(t,"cycleBudget");return l!==void 0&&(l<1?r.push({rule:"cycle-budget-too-low",message:`cycleBudget=${l} 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)."}):l>20&&r.push({rule:"cycle-budget-too-high",message:`cycleBudget=${l} 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 zy(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(`
2049
2056
  `);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(`
2050
2057
  lint: ${n(`${e.warnings.length} warning(s).`)}`),i.join(`
2051
- `)}function Cy(t){return t.cases.filter(e=>e.status==="failed").length}function us(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function WR(t){let e=Cy(t),r=[];r.push('<?xml version="1.0" encoding="UTF-8"?>'),r.push(`<testsuite name="${us(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let n of t.cases){let o=` <testcase name="${us(n.name)}"`;if(n.status==="passed"){r.push(`${o} />`);continue}r.push(`${o}>`);let s=n.detail??"failed",i=n.type?` type="${us(n.type)}"`:"";r.push(` <failure${i} message="${us(s)}">${us(s)}</failure>`),r.push(" </testcase>")}return r.push("</testsuite>"),`${r.join(`
2058
+ `)}function jy(t){return t.cases.filter(e=>e.status==="failed").length}function us(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function e0(t){let e=jy(t),r=[];r.push('<?xml version="1.0" encoding="UTF-8"?>'),r.push(`<testsuite name="${us(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let n of t.cases){let o=` <testcase name="${us(n.name)}"`;if(n.status==="passed"){r.push(`${o} />`);continue}r.push(`${o}>`);let s=n.detail??"failed",i=n.type?` type="${us(n.type)}"`:"";r.push(` <failure${i} message="${us(s)}">${us(s)}</failure>`),r.push(" </testcase>")}return r.push("</testsuite>"),`${r.join(`
2052
2059
  `)}
2053
- `}function GR(t){let e={suite:t.name,tests:t.cases.length,failures:Cy(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
2054
- `}function ta(t,e){return e==="junit"?WR(t):GR(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"},Ge={hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",clearLine:"\x1B[2K",clearToEnd:"\x1B[0J",col0:"\r",cursorUp:t=>`\x1B[${t}A`},po=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Mt={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},Ny=/\x1b\[[0-9;]*m/g;function Ar(t){return t.replace(Ny,"").length}function cu(t,e){return e<=0?1:Math.max(1,Math.ceil(Ar(t)/e))}function JR(){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 lu=JR();function tt(){return lu}function uu(t){lu=t}function ft(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function Ut(t,e){return lu?`${t}${e}${$t.reset}`:e}var g={bold:t=>Ut($t.bold,t),dim:t=>Ut($t.dim,t),red:t=>Ut($t.red,t),green:t=>Ut($t.green,t),yellow:t=>Ut($t.yellow,t),blue:t=>Ut($t.blue,t),magenta:t=>Ut($t.magenta,t),cyan:t=>Ut($t.cyan,t),grey:t=>Ut($t.grey,t)};var Ke={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}`},Hr={add:t=>g.green(`+ ${t}`),change:t=>g.yellow(`~ ${t}`),destroy:t=>g.red(`- ${t}`)},YR=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),XR=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),QR=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function ho(t){let e=t.toLowerCase();return YR.has(e)?g.green(t):XR.has(e)?g.red(t):QR.has(e)?g.yellow(t):t}function Vr(t,e=[]){let r=Math.max(Ar(t),...e.map(Ar),0),n=r+2,o=g.cyan(Mt.v),s=a=>` ${a}${" ".repeat(r-Ar(a))} `,i=[g.cyan(`${Mt.tl}${Mt.h.repeat(n)}${Mt.tr}`),`${o}${g.bold(s(t))}${o}`];if(e.length){i.push(`${g.cyan(Mt.ml)}${g.dim(Mt.h.repeat(n))}${g.cyan(Mt.mr)}`);for(let a of e)i.push(`${o}${s(a)}${o}`)}return i.push(g.cyan(`${Mt.bl}${Mt.h.repeat(n)}${Mt.br}`)),i.join(`
2060
+ `}function t0(t){let e={suite:t.name,tests:t.cases.length,failures:jy(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
2061
+ `}function na(t,e){return e==="junit"?e0(t):t0(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"},Ge={hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",clearLine:"\x1B[2K",clearToEnd:"\x1B[0J",col0:"\r",cursorUp:t=>`\x1B[${t}A`},po=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Mt={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},Ly=/\x1b\[[0-9;]*m/g;function Ar(t){return t.replace(Ly,"").length}function uu(t,e){return e<=0?1:Math.max(1,Math.ceil(Ar(t)/e))}function r0(){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 du=r0();function tt(){return du}function pu(t){du=t}function ft(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function Ut(t,e){return du?`${t}${e}${$t.reset}`:e}var g={bold:t=>Ut($t.bold,t),dim:t=>Ut($t.dim,t),red:t=>Ut($t.red,t),green:t=>Ut($t.green,t),yellow:t=>Ut($t.yellow,t),blue:t=>Ut($t.blue,t),magenta:t=>Ut($t.magenta,t),cyan:t=>Ut($t.cyan,t),grey:t=>Ut($t.grey,t)};var Ke={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}`},Hr={add:t=>g.green(`+ ${t}`),change:t=>g.yellow(`~ ${t}`),destroy:t=>g.red(`- ${t}`)},n0=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),o0=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),s0=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function ho(t){let e=t.toLowerCase();return n0.has(e)?g.green(t):o0.has(e)?g.red(t):s0.has(e)?g.yellow(t):t}function Vr(t,e=[]){let r=Math.max(Ar(t),...e.map(Ar),0),n=r+2,o=g.cyan(Mt.v),s=a=>` ${a}${" ".repeat(r-Ar(a))} `,i=[g.cyan(`${Mt.tl}${Mt.h.repeat(n)}${Mt.tr}`),`${o}${g.bold(s(t))}${o}`];if(e.length){i.push(`${g.cyan(Mt.ml)}${g.dim(Mt.h.repeat(n))}${g.cyan(Mt.mr)}`);for(let a of e)i.push(`${o}${s(a)}${o}`)}return i.push(g.cyan(`${Mt.bl}${Mt.h.repeat(n)}${Mt.br}`)),i.join(`
2055
2062
  `)}function Qt(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=>Ar(u[l]??"")));let a=l=>{let u=l.map((p,w)=>{let f=p??"";return w===l.length-1?f:f+" ".repeat(Math.max(0,i[w]-Ar(f)))});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]??Ar(l)))))));for(let l of t)c.push(a(l));return c.join(`
2056
- `)}function du(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`${tt()?e.map(n=>Ut($t.cyan,n)).join(`
2063
+ `)}function hu(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`${tt()?e.map(n=>Ut($t.cyan,n)).join(`
2057
2064
  `):e.join(`
2058
2065
  `)}
2059
- ${g.dim(` ${t}`)}`}var qt=t=>{process.stderr.write(t)};function ra(){return tt()&&process.stderr.isTTY===!0}function zy(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 ae(t,e){let r=ra(),n=0,o;r&&(qt(Ge.hideCursor),o=setInterval(()=>{qt(`${Ge.col0}${Ge.clearLine}${g.magenta(po[n++%po.length])} ${t}`)},80));let s=()=>{o&&clearInterval(o),r&&qt(`${Ge.col0}${Ge.clearLine}${Ge.showCursor}`)};try{let i=await e();return s(),r&&qt(`${Ke.success(t)}
2066
+ ${g.dim(` ${t}`)}`}var qt=t=>{process.stderr.write(t)};function oa(){return tt()&&process.stderr.isTTY===!0}function Dy(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 ae(t,e){let r=oa(),n=0,o;r&&(qt(Ge.hideCursor),o=setInterval(()=>{qt(`${Ge.col0}${Ge.clearLine}${g.magenta(po[n++%po.length])} ${t}`)},80));let s=()=>{o&&clearInterval(o),r&&qt(`${Ge.col0}${Ge.clearLine}${Ge.showCursor}`)};try{let i=await e();return s(),r&&qt(`${Ke.success(t)}
2060
2067
  `),i}catch(i){throw s(),r&&qt(`${Ke.error(t)}
2061
- `),i}}function pu(t){let e=0,r={stage:"queued"},n=!1,o=()=>{let c=g.magenta(po[e%po.length]),l=g.cyan(r.stage),u=r.runStatus?` ${g.dim(`(${r.runStatus})`)}`:"",p=`${String(Math.round(r.percent??0)).padStart(3)}%`;return`${c} ${t} ${g.dim("\u25B8")} ${l}${u} ${zy(r.percent)} ${p}`},s=()=>{qt(`${Ge.col0}${Ge.clearLine}${o()}`),n=!0},i=()=>{n&&qt(`${Ge.col0}${Ge.clearLine}`),n=!1};qt(Ge.hideCursor);let a=setInterval(()=>{e+=1,s()},80);return{log(c){i(),qt(`${c}
2062
- `),s()},status(c){r=c,s()},done(c){clearInterval(a),i(),qt(Ge.showCursor);let l=c.stage!=="failed",u=`${t} ${g.dim("\u25B8")} ${e0(c.stage)}${c.runStatus?` (${c.runStatus})`:""}`;qt(`${l?Ke.success(u):Ke.error(u)}
2063
- `)},stop(){clearInterval(a),i(),qt(Ge.showCursor)}}}function e0(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)}
2068
+ `),i}}function fu(t){let e=0,r={stage:"queued"},n=!1,o=()=>{let c=g.magenta(po[e%po.length]),l=g.cyan(r.stage),u=r.runStatus?` ${g.dim(`(${r.runStatus})`)}`:"",p=`${String(Math.round(r.percent??0)).padStart(3)}%`;return`${c} ${t} ${g.dim("\u25B8")} ${l}${u} ${Dy(r.percent)} ${p}`},s=()=>{qt(`${Ge.col0}${Ge.clearLine}${o()}`),n=!0},i=()=>{n&&qt(`${Ge.col0}${Ge.clearLine}`),n=!1};qt(Ge.hideCursor);let a=setInterval(()=>{e+=1,s()},80);return{log(c){i(),qt(`${c}
2069
+ `),s()},status(c){r=c,s()},done(c){clearInterval(a),i(),qt(Ge.showCursor);let l=c.stage!=="failed",u=`${t} ${g.dim("\u25B8")} ${i0(c.stage)}${c.runStatus?` (${c.runStatus})`:""}`;qt(`${l?Ke.success(u):Ke.error(u)}
2070
+ `)},stop(){clearInterval(a),i(),qt(Ge.showCursor)}}}function i0(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)}
2064
2071
  `),a(`${g.dim(" (\u2191/\u2193 to move, enter to select, ctrl+c to abort)")}
2065
2072
  `),a(Ge.hideCursor);let u=0,p=()=>{let b=process.stderr.columns??process.stdout.columns??80;u>0&&(a(Ge.cursorUp(u)),a(Ge.clearToEnd));let $=0;for(let E=0;E<e.length;E+=1){let P=e[E],z=E===i,B=z?g.cyan("\u25B6"):" ",W=P.disabled?g.grey(P.label):z?g.bold(g.cyan(P.label)):P.label,Ve=P.description?` ${g.dim(P.description)}`:"",Ye=` ${B} ${W}${Ve}`;a(`\r${Ye}
2066
- `),$+=cu(Ye,b)}u=$},w=()=>{c.removeListener("data",h),c.setRawMode?.(l??!1),c.pause(),a(Ge.showCursor)},f=b=>{let $=i;for(let E=0;E<e.length;E+=1)if($=($+b+e.length)%e.length,!e[$].disabled){i=$;return}},h=b=>{let $=b.toString("utf8");if($===""||$==="q"){w(),a(`
2073
+ `),$+=uu(Ye,b)}u=$},w=()=>{c.removeListener("data",h),c.setRawMode?.(l??!1),c.pause(),a(Ge.showCursor)},f=b=>{let $=i;for(let E=0;E<e.length;E+=1)if($=($+b+e.length)%e.length,!e[$].disabled){i=$;return}},h=b=>{let $=b.toString("utf8");if($===""||$==="q"){w(),a(`
2067
2074
  `),o(new Error("aborted"));return}if($==="\r"||$===`
2068
- `){let P=e[i];if(P.disabled)return;w(),n(P.value);return}if($==="\x1B[A"||$==="k"){f(-1),p();return}if($==="\x1B[B"||$==="j"){f(1),p();return}let E=Number($);Number.isFinite(E)&&E>=1&&E<=e.length&&!e[E-1].disabled&&(i=E-1,p())};c.on("data",h),p()})}function na(t,e){return`${ho(t)}${" ".repeat(Math.max(0,e-t.length))}`}var Ly=t=>new Promise(e=>setTimeout(e,t));function jy(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}] ${na(t.state,9)} ${t.conduitId} \u2192 ${e}${n} hop=${t.hop}${o}${r}`}async function Dy(t,e,r={}){let n=r.sink??(u=>{process.stdout.write(`${u}
2069
- `)}),o=r.sleep??Ly,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(jy(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 p=await t.conduitEvents(e,{since:c||void 0,limit:200});for(let w of[...p].reverse())n(jy(w)),a+=1,w.updatedAt>c&&(c=w.updatedAt)}return a}function t0(t){let e=t.externalId??"\u2014",r=t.createdByConduit?` via=${t.createdByConduit}`:"",n=t.lastError?` last_error="${t.lastError}"`:"";return`${t.id} ${na(t.writeStatus,9)} ${t.sourceSystem}/${e} role=${t.role} master=${t.masterTable}/${t.masterRowId}${r}${n}`}async function My(t,e={}){let r=e.sink??(o=>{process.stdout.write(`${o}
2070
- `)});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(t0(o));return r(`
2071
- binding: ${n.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:n.length}}function r0(t){let e=Object.entries(t.detail??{}).map(([i,a])=>`${i}=${typeof a=="string"?JSON.stringify(a):String(a)}`).join(" "),r=[t.sourceSystem,t.recordType,t.subjectId].filter(Boolean).join("/"),n=t.occurrences>1?` x${t.occurrences}`:"",o=t.redaction?.length?` redacted=[${t.redaction.join(",")}]`:"",s=t.correlationId?` corr=${t.correlationId}`:"";return`[${t.ts}] ${na(t.severity,5)} ${na(t.outcome,8)} ${t.code}${n}${r?` ${r}`:""}${s}${e?` ${e}`:""}${o}`}async function Uy(t,e={}){let r=e.sink??(E=>{process.stdout.write(`${E}
2072
- `)}),n=e.sleep??Ly,o=e.intervalMs??2e3,{follow:s,maxPolls:i,json:a,sink:c,sleep:l,intervalMs:u,...p}=e,w=E=>{r(a?JSON.stringify(E):r0(E))},f=await t.platformEvents({...p,limit:p.limit??100});if(f.length===0&&!s)return r("logs: no events matched."),0;let h=0,b="";for(let E of[...f].reverse())w(E),h+=1,E.ts>b&&(b=E.ts);if(!s)return h;let $=i??Number.POSITIVE_INFINITY;for(let E=0;E<$;E+=1){await n(o);let P=await t.platformEvents({...p,...b?{after:b,since:void 0}:{},limit:200});for(let z of[...P].reverse())w(z),h+=1,z.ts>b&&(b=z.ts)}return h}oa();Xi();function By(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 hu=".github/workflows/turbobase-release-deploy.yml",a0=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2075
+ `){let P=e[i];if(P.disabled)return;w(),n(P.value);return}if($==="\x1B[A"||$==="k"){f(-1),p();return}if($==="\x1B[B"||$==="j"){f(1),p();return}let E=Number($);Number.isFinite(E)&&E>=1&&E<=e.length&&!e[E-1].disabled&&(i=E-1,p())};c.on("data",h),p()})}function sa(t,e){return`${ho(t)}${" ".repeat(Math.max(0,e-t.length))}`}var Uy=t=>new Promise(e=>setTimeout(e,t));function My(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}] ${sa(t.state,9)} ${t.conduitId} \u2192 ${e}${n} hop=${t.hop}${o}${r}`}async function qy(t,e,r={}){let n=r.sink??(u=>{process.stdout.write(`${u}
2076
+ `)}),o=r.sleep??Uy,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(My(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 p=await t.conduitEvents(e,{since:c||void 0,limit:200});for(let w of[...p].reverse())n(My(w)),a+=1,w.updatedAt>c&&(c=w.updatedAt)}return a}function a0(t){let e=t.externalId??"\u2014",r=t.createdByConduit?` via=${t.createdByConduit}`:"",n=t.lastError?` last_error="${t.lastError}"`:"";return`${t.id} ${sa(t.writeStatus,9)} ${t.sourceSystem}/${e} role=${t.role} master=${t.masterTable}/${t.masterRowId}${r}${n}`}async function By(t,e={}){let r=e.sink??(o=>{process.stdout.write(`${o}
2077
+ `)});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(a0(o));return r(`
2078
+ binding: ${n.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:n.length}}function c0(t){let e=Object.entries(t.detail??{}).map(([i,a])=>`${i}=${typeof a=="string"?JSON.stringify(a):String(a)}`).join(" "),r=[t.sourceSystem,t.recordType,t.subjectId].filter(Boolean).join("/"),n=t.occurrences>1?` x${t.occurrences}`:"",o=t.redaction?.length?` redacted=[${t.redaction.join(",")}]`:"",s=t.correlationId?` corr=${t.correlationId}`:"";return`[${t.ts}] ${sa(t.severity,5)} ${sa(t.outcome,8)} ${t.code}${n}${r?` ${r}`:""}${s}${e?` ${e}`:""}${o}`}async function Zy(t,e={}){let r=e.sink??(E=>{process.stdout.write(`${E}
2079
+ `)}),n=e.sleep??Uy,o=e.intervalMs??2e3,{follow:s,maxPolls:i,json:a,sink:c,sleep:l,intervalMs:u,...p}=e,w=E=>{r(a?JSON.stringify(E):c0(E))},f=await t.platformEvents({...p,limit:p.limit??100});if(f.length===0&&!s)return r("logs: no events matched."),0;let h=0,b="";for(let E of[...f].reverse())w(E),h+=1,E.ts>b&&(b=E.ts);if(!s)return h;let $=i??Number.POSITIVE_INFINITY;for(let E=0;E<$;E+=1){await n(o);let P=await t.platformEvents({...p,...b?{after:b,since:void 0}:{},limit:200});for(let z of[...P].reverse())w(z),h+=1,z.ts>b&&(b=z.ts)}return h}ia();ea();function Hy(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 mu=".github/workflows/turbobase-release-deploy.yml",h0=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2073
2080
  # Turbobase release deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR repo)
2074
2081
  #
2075
2082
  # Epic #775 "GitHub is just a link": Turbobase hosts nothing and clones nothing.
@@ -2171,7 +2178,7 @@ jobs:
2171
2178
  --ref "\${{ github.sha }}" \\
2172
2179
  --project . \\
2173
2180
  --follow
2174
- `,c0=".github/workflows/turbobase-app-deploy.yml",l0=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2181
+ `,f0=".github/workflows/turbobase-app-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
2175
2182
  # Turbobase app deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR app repo)
2176
2183
  #
2177
2184
  # What ships from this repo, and when:
@@ -2389,14 +2396,14 @@ jobs:
2389
2396
  else
2390
2397
  echo "no preview labelled \\"$PR_LABEL\\" \u2014 nothing to discard."
2391
2398
  fi
2392
- `;function Zy(){return[{path:hu,content:a0}]}function Fy(){return[{path:c0,content:l0}]}oa();var u0=[".mcp.json"];function Ky(t,e=u0){let r=i=>i.replace(/^\//,""),n=new Set(t.split(`
2399
+ `;function Vy(){return[{path:mu,content:h0}]}function Ky(){return[{path:f0,content:m0}]}ia();var g0=[".mcp.json"];function Jy(t,e=g0){let r=i=>i.replace(/^\//,""),n=new Set(t.split(`
2393
2400
  `).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(`
2394
2401
  `)?t:`${t}
2395
2402
  `}
2396
2403
  # Added by the Turbobase scaffold.
2397
2404
  ${o.join(`
2398
2405
  `)}
2399
- `}var d0=`# Turbobase Extensions \u2014 extension project
2406
+ `}var y0=`# Turbobase Extensions \u2014 extension project
2400
2407
 
2401
2408
  This directory authors **Turbobase extensions** (hooks today; conduits later)
2402
2409
  against a live instance. The \`turbobase\` CLI is the engine; Claude Code drives it
@@ -2465,8 +2472,8 @@ order is the signal, and it is the part the product team reads first.
2465
2472
 
2466
2473
  Do this WITHOUT being asked \u2014 treat it as part of finishing a task, like
2467
2474
  updating a test. It is checked into the repo so the whole team sees it.
2468
- `,p0=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)+`
2469
- `;function h0(t){return`---
2475
+ `,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)+`
2476
+ `;function w0(t){return`---
2470
2477
  name: generate-types
2471
2478
  description: Regenerate ${t} from the signed-in instance's catalog. Use before authoring or whenever the schema may have changed.
2472
2479
  ---
@@ -2477,7 +2484,7 @@ write \`${t}\`. Import the generated record interfaces for typed rows.
2477
2484
 
2478
2485
  The OpenAPI half is cookie-session-gated, so a headless run with a stored token
2479
2486
  degrades to record shapes only and says so \u2014 that is expected, not a failure.
2480
- `}var f0=`---
2487
+ `}var v0=`---
2481
2488
  name: mock-test
2482
2489
  description: Dry-run a hook against samples/ fixtures using the production sandbox. Use after editing a hook, before deploy.
2483
2490
  ---
@@ -2486,7 +2493,7 @@ Run \`turbobase ext test hooks/<file>.ts\`. It bundles the hook through the same
2486
2493
  self-contained-fence esbuild + isolated-vm the live runtime uses, then runs it
2487
2494
  against every \`samples/*.json\` fixture and reports pass/reject per sample. Add a
2488
2495
  fixture for each branch (a passing record and a rejecting record).
2489
- `,m0=`---
2496
+ `,_0=`---
2490
2497
  name: deploy
2491
2498
  description: Deploy a hook to your instance. Use only after mock-test is green.
2492
2499
  ---
@@ -2494,7 +2501,7 @@ description: Deploy a hook to your instance. Use only after mock-test is green.
2494
2501
  Run \`turbobase ext deploy hooks/<file>.ts\`. It POSTs the hook source to
2495
2502
  /v1/extensions with the stored admin PAT; the hook lands **active**. Re-deploying
2496
2503
  the same id overwrites it (idempotent). Tail with \`turbobase ext logs <id>\`.
2497
- `;function g0(t){return`# ${t} \u2014 Turbobase app
2504
+ `;function x0(t){return`# ${t} \u2014 Turbobase app
2498
2505
 
2499
2506
  This directory is a **hosted Turbobase app**: a Vite + React + TS SPA served
2500
2507
  same-origin by the instance at \`/a/${t}\`. The \`turbobase\` CLI ships it; you
@@ -2833,7 +2840,7 @@ a test. \`turbobase apps deploy\` reads both files and queues what it finds for
2833
2840
  review, so what you write reaches the knowledge base and the product team instead
2834
2841
  of evaporating at the end of the session. Keep the section headings exactly as
2835
2842
  they are \u2014 the ingest finds entries by heading, not by filename.
2836
- `}var fo="customer",On="email",y0="^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$",b0=`// EXAMPLE \u2014 a business rule that holds for EVERY writer, not just this app.
2843
+ `}var fo="customer",On="email",k0="^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$",$0=`// EXAMPLE \u2014 a business rule that holds for EVERY writer, not just this app.
2837
2844
  //
2838
2845
  // It runs inside \`POST /v1/data\`, which is the only way an app can write at all:
2839
2846
  // the \`authenticated\` role holds no INSERT/UPDATE/DELETE on the mirror, so a
@@ -2852,8 +2859,8 @@ they are \u2014 the ingest finds entries by heading, not by filename.
2852
2859
  // Pure and credentials-free: no secrets, no network, no Node builtins, one
2853
2860
  // concern per file, nothing factored into a shared module (the sandbox fences
2854
2861
  // every import except the SDK).
2855
- `;function w0(){let t=fr("hook",{recordType:fo,event:"before_save",template:"enforce-format",field:On,regex:y0,id:`app:${fo}:${On}-format`,description:`Reject a ${fo} write whose ${On} is not an address.`}),e=(r,n,o)=>JSON.stringify({name:o,context:{recordType:fo,event:"before_save",payload:r},expect:n},null,2)+`
2856
- `;return[{path:t.relativePath,content:`${b0}${t.content}`},{path:`samples/${fo}.${On}-ok.json`,content:e({company_name:"Acme Supply",[On]:"ada@example.com"},"pass","a well-formed address passes")},{path:`samples/${fo}.${On}-malformed.json`,content:e({company_name:"Acme Supply",[On]:"ada-at-example"},"reject","a malformed address is rejected")}]}var v0="---\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",_0=`---
2862
+ `;function S0(){let t=fr("hook",{recordType:fo,event:"before_save",template:"enforce-format",field:On,regex:k0,id:`app:${fo}:${On}-format`,description:`Reject a ${fo} write whose ${On} is not an address.`}),e=(r,n,o)=>JSON.stringify({name:o,context:{recordType:fo,event:"before_save",payload:r},expect:n},null,2)+`
2863
+ `;return[{path:t.relativePath,content:`${$0}${t.content}`},{path:`samples/${fo}.${On}-ok.json`,content:e({company_name:"Acme Supply",[On]:"ada@example.com"},"pass","a well-formed address passes")},{path:`samples/${fo}.${On}-malformed.json`,content:e({company_name:"Acme Supply",[On]:"ada-at-example"},"reject","a malformed address is rejected")}]}var T0="---\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",E0=`---
2857
2864
  name: ship-app
2858
2865
  description: Push the app's source to the instance and deploy it live. Use once the app has been previewed and works.
2859
2866
  ---
@@ -2896,7 +2903,7 @@ Text files only \u2014 \`push\` skips \`node_modules/\`, \`dist/\`, \`build/\`,
2896
2903
  non-text, so images and fonts belong in the build pipeline or object storage, not
2897
2904
  the source tree. \`INSTANCE-LEARNINGS.md\` and \`TURBOBASE-FEEDBACK.md\` sit at the
2898
2905
  project root and DO travel \u2014 deploy reads them.
2899
- `,x0=`---
2906
+ `,R0=`---
2900
2907
  name: business-rule-to-hook
2901
2908
  description: Decide where a rule belongs \u2014 a hook on the instance (enforced for every writer, reusable by every app) or the app's UI. Use whenever you are about to write a validation, threshold, or "you can't do that" check.
2902
2909
  ---
@@ -2964,7 +2971,7 @@ subsidiary as headquarters"), also record it in \`INSTANCE-LEARNINGS.md\` under
2964
2971
  standing rules for every agent on the instance \u2014 see the record-learning skill.
2965
2972
  A rule enforced in code and nowhere written down gets re-litigated by the next
2966
2973
  person.
2967
- `;function k0(t){return`---
2974
+ `;function P0(t){return`---
2968
2975
  name: record-learning
2969
2976
  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.
2970
2977
  ---
@@ -3019,7 +3026,7 @@ earlier claim" and still publish.
3019
3026
 
3020
3027
  Do not reword the three headings. The deploy-side ingest recognises entries by
3021
3028
  heading, not by filename, so a renamed section is a finding nobody receives.
3022
- `}function $0(t){return`# What this instance's source system actually does
3029
+ `}function A0(t){return`# What this instance's source system actually does
3023
3030
 
3024
3031
  Findings from ${t?`building the ${t.slug} app against the live mirror`:"authoring extensions against the live instance"}.
3025
3032
  Written for the knowledge base, and **everything here is verified against real
@@ -3150,7 +3157,7 @@ finding has not been handed to the knowledge base yet.
3150
3157
  and then \`turbobase skills release\`. \`turbobase skills list\` shows what is
3151
3158
  already live, which is worth reading before adding another rule. -->
3152
3159
 
3153
- `}function S0(t){return`# Feedback for the Turbobase team \u2014 what ${t?`building the ${t.slug} app`:"authoring extensions here"} actually hit
3160
+ `}function I0(t){return`# Feedback for the Turbobase team \u2014 what ${t?`building the ${t.slug} app`:"authoring extensions here"} actually hit
3154
3161
 
3155
3162
  Everything below cost time or produced a wrong result. Not speculation, and not
3156
3163
  a wishlist. This file is about the PLATFORM \u2014 scaffold, catalog, CLI, MCP, API.
@@ -3230,7 +3237,7 @@ Expected / happened / cost / fix.
3230
3237
  and what it would replace. These are the highest-signal entries in the file:
3231
3238
  each one is a page downloading rows to fold that it could have asked for
3232
3239
  folded. -->
3233
- `}function T0(t,e){let r=e?`
3240
+ `}function O0(t,e){let r=e?`
3234
3241
  # INSTANCE.md \u2014 the instance's grounding brief (see CLAUDE.md). Reuse the
3235
3242
  # --records focus a previous run stamped into the file, so a refresh never
3236
3243
  # narrows what an agent deliberately widened.
@@ -3261,8 +3268,8 @@ ${r}
3261
3268
  # surface unticked items at the start of a session.
3262
3269
  turbobase project adopt -o ADOPT.md >/dev/null \\
3263
3270
  || echo "turbobase: \\\`turbobase project adopt\\\` failed (its error is above) \u2014 ADOPT.md was NOT refreshed." >&2
3264
- `}var Wy="Turbobase consultant",E0="turbobase-consultant",R0=`---
3265
- name: ${Wy}
3271
+ `}var Yy="Turbobase consultant",C0="turbobase-consultant",N0=`---
3272
+ name: ${Yy}
3266
3273
  description: For ERP consultants, NetSuite admins and business analysts \u2014 business-outcome framing, short answers, no unrequested code tours.
3267
3274
  keep-coding-instructions: true
3268
3275
  ---
@@ -3335,8 +3342,8 @@ exists on purpose.
3335
3342
  - Do not show a stack trace. Say what broke and what you are doing about it.
3336
3343
  - Do not apologise repeatedly or pad with "great question".
3337
3344
  - Do not use a table when a sentence works.
3338
- `,P0=JSON.stringify({outputStyle:Wy,hooks:{SessionStart:[{hooks:[{type:"command",command:"bash .claude/hooks/session-start-refresh-types.sh"}]}],PostToolUse:[{matcher:"Edit|Write",hooks:[{type:"command",command:"bash .claude/hooks/check-rule-placement.sh"}]}]}},null,2)+`
3339
- `,A0=`#!/usr/bin/env bash
3345
+ `,z0=JSON.stringify({outputStyle:Yy,hooks:{SessionStart:[{hooks:[{type:"command",command:"bash .claude/hooks/session-start-refresh-types.sh"}]}],PostToolUse:[{matcher:"Edit|Write",hooks:[{type:"command",command:"bash .claude/hooks/check-rule-placement.sh"}]}]}},null,2)+`
3346
+ `,j0=`#!/usr/bin/env bash
3340
3347
  # PostToolUse (Edit|Write) \u2014 is this a business rule that belongs in hooks/?
3341
3348
  #
3342
3349
  # Advisory only: exits 0 always, and adds a note for the agent when the edited
@@ -3353,7 +3360,7 @@ set -uo pipefail
3353
3360
  command -v node >/dev/null 2>&1 || exit 0
3354
3361
 
3355
3362
  exec node "$(dirname "$0")/check-rule-placement.mjs"
3356
- `,I0=String.raw`/**
3363
+ `,L0=String.raw`/**
3357
3364
  * Is the file that was just edited enforcing a business rule inside the SPA?
3358
3365
  *
3359
3366
  * Reads the PostToolUse payload on stdin, and when BOTH signals are present —
@@ -3422,7 +3429,7 @@ process.stdout.write(
3422
3429
  },
3423
3430
  }),
3424
3431
  );
3425
- `,O0=`---
3432
+ `,D0=`---
3426
3433
  name: roles-and-permissions
3427
3434
  description: Decide who can open a screen and who can change a record \u2014 declare roles in public/turbobase.json, gate the UI on capabilities, and turn a denial into a message that names the role to ask for. Use when adding a screen, a nav item, a write button, a role, or answering "who can see/do X".
3428
3435
  ---
@@ -3573,7 +3580,7 @@ a denial look like emptiness.
3573
3580
  - Does every write catch \`TurbobasePermissionError\`?
3574
3581
  - Did you run \`turbobase apps plan\`?
3575
3582
  - Did you tell the user their administrator still has to ASSIGN the role?
3576
- `,C0=`---
3583
+ `,M0=`---
3577
3584
  name: app-design
3578
3585
  description: How a Turbobase app should look and behave. Read the published design system first, then the display rules here that stop a working build showing wrong data. Use before building any screen.
3579
3586
  ---
@@ -3666,7 +3673,7 @@ The design system covers the look. Two rules it does not:
3666
3673
  Load it in the browser and check: does it render with ZERO rows, with ONE row,
3667
3674
  and with several hundred? Does it survive the query failing? Does tab reach every
3668
3675
  control, with a visible focus ring? A green \`npm run build\` proves none of these.
3669
- `,sa="",Hy=String.raw`{
3676
+ `,aa="",Wy=String.raw`{
3670
3677
  "_comment": [
3671
3678
  "Declarative sync config — part of this repo's desired state.",
3672
3679
  " turbobase ext plan --to prod shows the diff against your instance (writes nothing)",
@@ -3688,7 +3695,7 @@ control, with a visible focus ring? A green \`npm run build\` proves none of the
3688
3695
  "fields": [],
3689
3696
  "tables": []
3690
3697
  }
3691
- `,Vy=String.raw`{
3698
+ `,Gy=String.raw`{
3692
3699
  "_comment": [
3693
3700
  "Scheduled jobs, as desired state. Applied by: turbobase ext deploy --to prod",
3694
3701
  "Removing an entry does NOT remove the schedule unless you pass --prune.",
@@ -3704,51 +3711,51 @@ control, with a visible focus ring? A green \`npm run build\` proves none of the
3704
3711
  ],
3705
3712
  "schedules": []
3706
3713
  }
3707
- `,N0=t=>`node_modules/
3714
+ `,U0=t=>`node_modules/
3708
3715
 
3709
3716
  # Holds a live personal access token (written by \`turbobase ${t?"apps":"project"} init\`).
3710
3717
  .mcp.json
3711
3718
 
3712
3719
  .DS_Store
3713
- `;function fu(t={}){let e=p0.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:N0(r)},{path:"INSTANCE-LEARNINGS.md",content:$0(o)},{path:"TURBOBASE-FEEDBACK.md",content:S0(o)},{path:".claude/settings.json",content:P0},{path:`.claude/output-styles/${E0}.md`,content:R0},{path:".claude/skills/generate-types/SKILL.md",content:h0(n)},{path:".claude/skills/record-learning/SKILL.md",content:k0(o)},{path:".claude/skills/business-rule-to-hook/SKILL.md",content:x0},{path:".claude/hooks/session-start-refresh-types.sh",content:T0(n,o),executable:!0},{path:".claude/hooks/check-rule-placement.sh",content:A0,executable:!0},{path:".claude/hooks/check-rule-placement.mjs",content:I0}];return r?[{path:"CLAUDE.md",content:g0(t.appSlug)},...s,{path:".claude/skills/preview-app/SKILL.md",content:v0},{path:".claude/skills/ship-app/SKILL.md",content:_0},{path:".claude/skills/app-design/SKILL.md",content:C0},{path:".claude/skills/roles-and-permissions/SKILL.md",content:O0},...w0(),{path:"conduits/.gitkeep",content:sa},{path:"turbobase/sync.json",content:Hy},{path:"turbobase/schedules.json",content:Vy},...Fy()]:[{path:"CLAUDE.md",content:d0},...s,{path:".claude/skills/mock-test/SKILL.md",content:f0},{path:".claude/skills/deploy/SKILL.md",content:m0},{path:"hooks/.gitkeep",content:sa},{path:"conduits/.gitkeep",content:sa},{path:"samples/.gitkeep",content:sa},{path:"turbobase/sync.json",content:Hy},{path:"turbobase/schedules.json",content:Vy}]}import{promises as gu}from"node:fs";import{dirname as z0,join as er,resolve as Qy}from"node:path";function Jy(t){return{version:1,...t?{tenant:t}:{},hooks:[],conduits:[],sync:{fields:[],tables:[]},guardrails:{validationHooks:[],fieldRules:[],conduits:[]},schedules:[]}}var ds="bundle.json",ia="turbobase";function Yy(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 mu(a)}function mu(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(Gy)),tables:[...t.sync.tables].sort(e(r=>r.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(Gy)),conduits:[...t.guardrails.conduits].sort(e(r=>r.conduitId))},schedules:[...t.schedules].sort(e(r=>r.name))}}function Gy(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function Xy(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}")`}}var ca="hooks",la="conduits",eb="processes",Kr="turbobase/sync.json",Wr="turbobase/schedules.json";function yu(t){let e=l=>{let u=new RegExp(`${l}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return u?u[2]:void 0},r=/\bdefineConduit\s*[<(]/.test(t),n=/\bdefineProcess\s*[<(]/.test(t),o=/\bdefineHook\s*[<(]/.test(t);if(!r&&!o&&!n)return null;let s=e("id"),i=e("recordType");if(n){let l=e("source")??"standalone";return!s||!i?null:{id:s,recordType:i,event:"invoke",source:l,extensionKind:"process"}}if(r){let l=e("on"),u=e("source");return!s||!i||!l||!u?null:{id:s,recordType:i,event:l,source:u,extensionKind:"conduit"}}let a=e("event"),c=e("source")??"standalone";return!s||!i||!a?null:{id:s,recordType:i,event:a,source:c,extensionKind:"hook"}}async function ps(t){let e;try{e=await gu.readdir(t,{withFileTypes:!0})}catch{return[]}let r=[];for(let n of e){if(n.isDirectory()){if(n.name.startsWith(".")||n.name==="node_modules")continue;for(let o of await ps(er(t,n.name)))r.push(`${n.name}/${o}`);continue}n.name.endsWith(".ts")&&(n.name.endsWith(".test.ts")||n.name.endsWith(".d.ts")||r.push(n.name))}return r.sort()}async function aa(t,e){let r;try{r=await gu.readFile(t,"utf8")}catch{return}try{return JSON.parse(r)}catch(n){throw new Error(`${e} is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}}function j0(t){return{sourceSystem:String(t.sourceSystem??""),recordType:String(t.recordType??""),fieldName:String(t.fieldName??""),owningSide:t.owningSide==="pg"?"pg":"source",caseSensitive:!!t.caseSensitive}}function L0(t){return{sourceRecordType:String(t.sourceRecordType??""),kind:String(t.kind??""),sourceSystem:String(t.sourceSystem??"")}}function D0(t){let e={name:String(t.name??""),scheduleKind:String(t.scheduleKind??"cron"),scheduleExpr:String(t.scheduleExpr??""),scheduleTz:String(t.scheduleTz??"UTC"),body:t.body??{}};return typeof t.status=="string"&&(e.status=t.status),e}async function tb(t=process.cwd()){let e=Qy(t),[r,n,o]=await Promise.all([ps(er(e,ca)),ps(er(e,la)),ps(er(e,eb))]);if(r.length>0||n.length>0||o.length>0)return!0;let[s,i]=await Promise.all([aa(er(e,Kr),Kr).catch(()=>{}),aa(er(e,Wr),Wr).catch(()=>{})]);return s!==void 0||i!==void 0}async function rb(t=process.cwd(),e={}){let r=Qy(t),n=Jy(e.tenant),o=[],s=[];for(let c of[ca,la,eb])for(let l of await ps(er(r,c))){let u=`${c}/${l}`,p=await gu.readFile(er(r,c,l),"utf8"),w=e.inline?await e.inline(p,z0(er(r,c,l))):p,f=yu(w);if(!f){/\bdefine(Hook|Conduit|Process)\s*[<(]/.test(w)&&s.push({file:u,reason:"could not read id / recordType / event"});continue}let h={id:f.id,kind:f.extensionKind,recordType:f.recordType,event:f.event,source:f.source,sourceCode:w};f.extensionKind==="conduit"?n.conduits.push(h):n.hooks.push(h),o.push(u)}let i=await aa(er(r,Kr),Kr);if(i!==void 0){if(typeof i!="object"||i===null||Array.isArray(i))throw new Error(`${Kr} must be a JSON object with "fields" and/or "tables".`);let c=i;for(let l of Array.isArray(c.fields)?c.fields:[])n.sync.fields.push(j0(l));for(let l of Array.isArray(c.tables)?c.tables:[])n.sync.tables.push(L0(l));o.push(Kr)}let a=await aa(er(r,Wr),Wr);if(a!==void 0){let c=Array.isArray(a)?a:Array.isArray(a.schedules)?a.schedules:null;if(c===null)throw new Error(`${Wr} must be a JSON array, or an object with a "schedules" array.`);for(let l of c)n.schedules.push(D0(l));o.push(Wr)}return n.guardrails.fieldRules=[...n.sync.fields],n.guardrails.validationHooks=n.hooks.filter(c=>c.event==="before_save").map(c=>c.id).sort(),{manifest:mu(n),contributed:o,unparsed:s}}import{promises as vu}from"node:fs";import{resolve as F0}from"node:path";var M0="For app developers \u2014 adopt these";function nb(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 ob(t,e){let r=nb(t),n=nb(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 OB=U0(M0);ss();Pr();var q0=t=>new Promise(e=>setTimeout(e,t));function sb(t){return t.stage==="completed"||t.stage==="failed"}function B0(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function Z0(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(`
3714
- `))r(i)}return n}async function bu(t,e={}){let r=e.sink??(w=>{process.stdout.write(`${w}
3715
- `)}),n=e.sleep??q0,o=e.intervalMs??2e3,s=e.maxPolls??Number.POSITIVE_INFINITY,i=e.onStage??(w=>r(B0(w))),a=e.onPoll,c="",l="",u=w=>{a?.(w),w.stage!==l&&i(w),c=Z0(w,c,r),l=w.stage},p=await t();if(u(p),sb(p))return p;for(let w=0;w<s;w+=1)if(await n(o),p=await t(),u(p),sb(p))return p;return p}var v=t=>{process.stdout.write(`${t}
3720
+ `;function gu(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:U0(r)},{path:"INSTANCE-LEARNINGS.md",content:A0(o)},{path:"TURBOBASE-FEEDBACK.md",content:I0(o)},{path:".claude/settings.json",content:z0},{path:`.claude/output-styles/${C0}.md`,content:N0},{path:".claude/skills/generate-types/SKILL.md",content:w0(n)},{path:".claude/skills/record-learning/SKILL.md",content:P0(o)},{path:".claude/skills/business-rule-to-hook/SKILL.md",content:R0},{path:".claude/hooks/session-start-refresh-types.sh",content:O0(n,o),executable:!0},{path:".claude/hooks/check-rule-placement.sh",content:j0,executable:!0},{path:".claude/hooks/check-rule-placement.mjs",content:L0}];return r?[{path:"CLAUDE.md",content:x0(t.appSlug)},...s,{path:".claude/skills/preview-app/SKILL.md",content:T0},{path:".claude/skills/ship-app/SKILL.md",content:E0},{path:".claude/skills/app-design/SKILL.md",content:M0},{path:".claude/skills/roles-and-permissions/SKILL.md",content:D0},...S0(),{path:"conduits/.gitkeep",content:aa},{path:"turbobase/sync.json",content:Wy},{path:"turbobase/schedules.json",content:Gy},...Ky()]:[{path:"CLAUDE.md",content:y0},...s,{path:".claude/skills/mock-test/SKILL.md",content:v0},{path:".claude/skills/deploy/SKILL.md",content:_0},{path:"hooks/.gitkeep",content:aa},{path:"conduits/.gitkeep",content:aa},{path:"samples/.gitkeep",content:aa},{path:"turbobase/sync.json",content:Wy},{path:"turbobase/schedules.json",content:Gy}]}import{promises as bu}from"node:fs";import{dirname as q0,join as er,resolve as rb}from"node:path";function Qy(t){return{version:1,...t?{tenant:t}:{},hooks:[],conduits:[],sync:{fields:[],tables:[]},guardrails:{validationHooks:[],fieldRules:[],conduits:[]},schedules:[]}}var ds="bundle.json",ca="turbobase";function eb(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 yu(a)}function yu(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(Xy)),tables:[...t.sync.tables].sort(e(r=>r.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(Xy)),conduits:[...t.guardrails.conduits].sort(e(r=>r.conduitId))},schedules:[...t.schedules].sort(e(r=>r.name))}}function Xy(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function tb(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}")`}}var ua="hooks",da="conduits",nb="processes",Kr="turbobase/sync.json",Wr="turbobase/schedules.json";function wu(t){let e=l=>{let u=new RegExp(`${l}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return u?u[2]:void 0},r=/\bdefineConduit\s*[<(]/.test(t),n=/\bdefineProcess\s*[<(]/.test(t),o=/\bdefineHook\s*[<(]/.test(t);if(!r&&!o&&!n)return null;let s=e("id"),i=e("recordType");if(n){let l=e("source")??"standalone";return!s||!i?null:{id:s,recordType:i,event:"invoke",source:l,extensionKind:"process"}}if(r){let l=e("on"),u=e("source");return!s||!i||!l||!u?null:{id:s,recordType:i,event:l,source:u,extensionKind:"conduit"}}let a=e("event"),c=e("source")??"standalone";return!s||!i||!a?null:{id:s,recordType:i,event:a,source:c,extensionKind:"hook"}}async function ps(t){let e;try{e=await bu.readdir(t,{withFileTypes:!0})}catch{return[]}let r=[];for(let n of e){if(n.isDirectory()){if(n.name.startsWith(".")||n.name==="node_modules")continue;for(let o of await ps(er(t,n.name)))r.push(`${n.name}/${o}`);continue}n.name.endsWith(".ts")&&(n.name.endsWith(".test.ts")||n.name.endsWith(".d.ts")||r.push(n.name))}return r.sort()}async function la(t,e){let r;try{r=await bu.readFile(t,"utf8")}catch{return}try{return JSON.parse(r)}catch(n){throw new Error(`${e} is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}}function B0(t){return{sourceSystem:String(t.sourceSystem??""),recordType:String(t.recordType??""),fieldName:String(t.fieldName??""),owningSide:t.owningSide==="pg"?"pg":"source",caseSensitive:!!t.caseSensitive}}function Z0(t){return{sourceRecordType:String(t.sourceRecordType??""),kind:String(t.kind??""),sourceSystem:String(t.sourceSystem??"")}}function F0(t){let e={name:String(t.name??""),scheduleKind:String(t.scheduleKind??"cron"),scheduleExpr:String(t.scheduleExpr??""),scheduleTz:String(t.scheduleTz??"UTC"),body:t.body??{}};return typeof t.status=="string"&&(e.status=t.status),e}async function ob(t=process.cwd()){let e=rb(t),[r,n,o]=await Promise.all([ps(er(e,ua)),ps(er(e,da)),ps(er(e,nb))]);if(r.length>0||n.length>0||o.length>0)return!0;let[s,i]=await Promise.all([la(er(e,Kr),Kr).catch(()=>{}),la(er(e,Wr),Wr).catch(()=>{})]);return s!==void 0||i!==void 0}async function sb(t=process.cwd(),e={}){let r=rb(t),n=Qy(e.tenant),o=[],s=[];for(let c of[ua,da,nb])for(let l of await ps(er(r,c))){let u=`${c}/${l}`,p=await bu.readFile(er(r,c,l),"utf8"),w=e.inline?await e.inline(p,q0(er(r,c,l))):p,f=wu(w);if(!f){/\bdefine(Hook|Conduit|Process)\s*[<(]/.test(w)&&s.push({file:u,reason:"could not read id / recordType / event"});continue}let h={id:f.id,kind:f.extensionKind,recordType:f.recordType,event:f.event,source:f.source,sourceCode:w};f.extensionKind==="conduit"?n.conduits.push(h):n.hooks.push(h),o.push(u)}let i=await la(er(r,Kr),Kr);if(i!==void 0){if(typeof i!="object"||i===null||Array.isArray(i))throw new Error(`${Kr} must be a JSON object with "fields" and/or "tables".`);let c=i;for(let l of Array.isArray(c.fields)?c.fields:[])n.sync.fields.push(B0(l));for(let l of Array.isArray(c.tables)?c.tables:[])n.sync.tables.push(Z0(l));o.push(Kr)}let a=await la(er(r,Wr),Wr);if(a!==void 0){let c=Array.isArray(a)?a:Array.isArray(a.schedules)?a.schedules:null;if(c===null)throw new Error(`${Wr} must be a JSON array, or an object with a "schedules" array.`);for(let l of c)n.schedules.push(F0(l));o.push(Wr)}return n.guardrails.fieldRules=[...n.sync.fields],n.guardrails.validationHooks=n.hooks.filter(c=>c.event==="before_save").map(c=>c.id).sort(),{manifest:yu(n),contributed:o,unparsed:s}}import{promises as xu}from"node:fs";import{resolve as J0}from"node:path";var H0="For app developers \u2014 adopt these";function ib(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 ab(t,e){let r=ib(t),n=ib(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 V0(t){return t.replace(/[‐-―]/g,"-").toLowerCase().replace(/\s+/g," ").trim()}var DB=V0(H0);ss();Pr();var K0=t=>new Promise(e=>setTimeout(e,t));function cb(t){return t.stage==="completed"||t.stage==="failed"}function W0(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function G0(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(`
3721
+ `))r(i)}return n}async function vu(t,e={}){let r=e.sink??(w=>{process.stdout.write(`${w}
3722
+ `)}),n=e.sleep??K0,o=e.intervalMs??2e3,s=e.maxPolls??Number.POSITIVE_INFINITY,i=e.onStage??(w=>r(W0(w))),a=e.onPoll,c="",l="",u=w=>{a?.(w),w.stage!==l&&i(w),c=G0(w,c,r),l=w.stage},p=await t();if(u(p),cb(p))return p;for(let w=0;w<s;w+=1)if(await n(o),p=await t(),u(p),cb(p))return p;return p}var v=t=>{process.stdout.write(`${t}
3716
3723
  `)},q=t=>{process.stderr.write(`${t}
3717
- `)};function k(t){q(g.red(`turbobase: ${t}`)),process.exit(1)}var hs=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function ib(t,e){let r=e.json===!0||typeof e.reporter=="string";(t.color===!1||r)&&uu(!1)}async function ne(t){let e=await Xt(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let r=await Rr();if(t){let n=r.length?` Stored instances: ${r.map(o=>o.baseUrl).join(", ")}.`:"";k(`not signed in to ${Dt(t)}.${n} Run \`turbobase auth login --base-url ${Dt(t)} --token tb_pat_\u2026\`.`)}if(r.length===0&&k("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),ft())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 Hi(n);let o=await Xt();if(o)return{baseUrl:o.baseUrl,token:o.token}}catch{}k(`multiple instances stored (${r.map(n=>n.baseUrl).join(", ")}) and no active default. Run \`turbobase auth use <base-url>\` to pick one, or pass --base-url.`)}function se(t,e,r){if(!(t instanceof le)||t.status!==403)return;t.body?.error==="approval_required"&&k(`${r} denied (403): an approval-gated deploy needs a recorded approval \u2014 pass --approved-by <email>.`),k(`${r} forbidden (403) \u2014 the stored PAT lacks the '${e}' scope. Re-run \`turbobase auth login\` with a token that has it.`)}async function wu(t,e,r){let n=r?Number(r):void 0;if(ra()){let s=pu(e),i;try{i=await bu(t,{intervalMs:n,sink:a=>s.log(a),onStage:()=>{},onPoll:a=>s.status({stage:a.stage,percent:a.percent??void 0,runStatus:a.runStatus??void 0})})}catch(a){s.stop(),k(`${e} --follow failed: ${a instanceof Error?a.message:String(a)}`)}s.done({stage:i.stage,percent:i.percent??void 0,runStatus:i.runStatus??void 0}),i.stage==="failed"&&process.exit(1);return}let o;try{o=await bu(t,{sink:v,intervalMs:n})}catch(s){k(`${e} --follow failed: ${s instanceof Error?s.message:String(s)}`)}o.stage==="failed"&&k(`${e} failed${o.runStatus?` (${o.runStatus})`:""}.`),v(`${e} ${o.stage}.`)}var H0=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function V0(t){try{let e=await vu.readFile(t,"utf8");return H0.exec(e)?.[1]??null}catch{return null}}var K0=/GENERATED by `turbobase project adopt`/,cb=/^##[ \t]+v?(\d+(?:\.\d+){0,2}(?:-[0-9A-Za-z.-]+)?)[ \t]*$/,W0=/^[ \t]*[-*][ \t]+\[([ xX])\][ \t]+(.*)$/;function ab(t){let e=[],r=null;for(let n of t.split(`
3718
- `)){let o=cb.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=W0.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 G0(t){let e=t.items.map(r=>[`- [${r.done?"x":" "}] ${r.text}`,...r.extra].join(`
3724
+ `)};function k(t){q(g.red(`turbobase: ${t}`)),process.exit(1)}var hs=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function lb(t,e){let r=e.json===!0||typeof e.reporter=="string";(t.color===!1||r)&&pu(!1)}async function ne(t){let e=await Xt(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let r=await Rr();if(t){let n=r.length?` Stored instances: ${r.map(o=>o.baseUrl).join(", ")}.`:"";k(`not signed in to ${Dt(t)}.${n} Run \`turbobase auth login --base-url ${Dt(t)} --token tb_pat_\u2026\`.`)}if(r.length===0&&k("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),ft())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 Ki(n);let o=await Xt();if(o)return{baseUrl:o.baseUrl,token:o.token}}catch{}k(`multiple instances stored (${r.map(n=>n.baseUrl).join(", ")}) and no active default. Run \`turbobase auth use <base-url>\` to pick one, or pass --base-url.`)}function se(t,e,r){if(!(t instanceof le)||t.status!==403)return;t.body?.error==="approval_required"&&k(`${r} denied (403): an approval-gated deploy needs a recorded approval \u2014 pass --approved-by <email>.`),k(`${r} forbidden (403) \u2014 the stored PAT lacks the '${e}' scope. Re-run \`turbobase auth login\` with a token that has it.`)}async function _u(t,e,r){let n=r?Number(r):void 0;if(oa()){let s=fu(e),i;try{i=await vu(t,{intervalMs:n,sink:a=>s.log(a),onStage:()=>{},onPoll:a=>s.status({stage:a.stage,percent:a.percent??void 0,runStatus:a.runStatus??void 0})})}catch(a){s.stop(),k(`${e} --follow failed: ${a instanceof Error?a.message:String(a)}`)}s.done({stage:i.stage,percent:i.percent??void 0,runStatus:i.runStatus??void 0}),i.stage==="failed"&&process.exit(1);return}let o;try{o=await vu(t,{sink:v,intervalMs:n})}catch(s){k(`${e} --follow failed: ${s instanceof Error?s.message:String(s)}`)}o.stage==="failed"&&k(`${e} failed${o.runStatus?` (${o.runStatus})`:""}.`),v(`${e} ${o.stage}.`)}var Y0=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function X0(t){try{let e=await xu.readFile(t,"utf8");return Y0.exec(e)?.[1]??null}catch{return null}}var Q0=/GENERATED by `turbobase project adopt`/,db=/^##[ \t]+v?(\d+(?:\.\d+){0,2}(?:-[0-9A-Za-z.-]+)?)[ \t]*$/,eP=/^[ \t]*[-*][ \t]+\[([ xX])\][ \t]+(.*)$/;function ub(t){let e=[],r=null;for(let n of t.split(`
3725
+ `)){let o=db.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=eP.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 tP(t){let e=t.items.map(r=>[`- [${r.done?"x":" "}] ${r.text}`,...r.extra].join(`
3719
3726
  `)).join(`
3720
3727
  `);return`## v${t.version}
3721
3728
 
3722
- ${e}`}function J0(t,e){let r=ab(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 ab(e)){let p=n.get(u.version);n.delete(u.version);let w=new Set(u.items.map(h=>h.key)),f=u.items.map(h=>{let b=p?.items.find($=>$.key===h.key);return b?{...h,done:b.done,extra:b.extra}:h});for(let h of p?.items??[])w.has(h.key)||h.done||(f.push(h),s+=1);o.push({version:u.version,items:f})}for(let u of n.values()){let p=u.items.filter(w=>!w.done);p.length!==0&&(s+=p.length,o.push({version:u.version,items:p}))}o.sort((u,p)=>ob(p.version,u.version));let i=e.split(`
3723
- `),a=i.findIndex(u=>cb.test(u)),c=(a===-1?i:i.slice(0,a)).join(`
3729
+ ${e}`}function rP(t,e){let r=ub(t);if(r.length===0&&!Q0.test(t))return null;let n=new Map(r.map(u=>[u.version,u])),o=[],s=0;for(let u of ub(e)){let p=n.get(u.version);n.delete(u.version);let w=new Set(u.items.map(h=>h.key)),f=u.items.map(h=>{let b=p?.items.find($=>$.key===h.key);return b?{...h,done:b.done,extra:b.extra}:h});for(let h of p?.items??[])w.has(h.key)||h.done||(f.push(h),s+=1);o.push({version:u.version,items:f})}for(let u of n.values()){let p=u.items.filter(w=>!w.done);p.length!==0&&(s+=p.length,o.push({version:u.version,items:p}))}o.sort((u,p)=>ab(p.version,u.version));let i=e.split(`
3730
+ `),a=i.findIndex(u=>db.test(u)),c=(a===-1?i:i.slice(0,a)).join(`
3724
3731
  `).replace(/\s+$/,"");return{markdown:o.length===0?`${c}
3725
3732
  `:`${c}
3726
3733
 
3727
- ${o.map(G0).join(`
3734
+ ${o.map(tP).join(`
3728
3735
 
3729
3736
  `)}
3730
- `,carried:s}}function lb(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=F0(process.cwd(),e.out),s=e.since?.trim()||await V0(o),i=new URLSearchParams;s&&i.set("since",s);let a=i.toString(),c=await fetch(`${r}/v1/catalog/adopt-notes${a?`?${a}`:""}`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/json"}});c.ok||k(`adopt fetch failed: GET /v1/catalog/adopt-notes \u2192 ${c.status}`);let l=await c.json();if(!l.available){v(`${r} ships no release notes to adopt from (nothing written).`);return}let u=l.releases.reduce(($,E)=>$+E.items.length,0);if(u===0){v(`up to date${s?` since v${s.replace(/^v/,"")}`:""}${l.currentVersion?` (instance is on v${l.currentVersion})`:""} \u2014 ${o} left untouched.`);return}let p=l.currentVersion??l.releases[0]?.version??"",w=`<!-- GENERATED by \`turbobase project adopt\` against ${r} \u2014 adopted-through=${p}. Re-run to refresh; delete this file once every line is done. -->
3731
-
3732
- `,f=await vu.readFile(o,"utf8").catch(()=>null),h=l.markdown,b=0;if(f!==null&&f.trim()!==""){let $=J0(f,l.markdown);$||k(`${o} was not written by \`turbobase project adopt\` (no generated header, no \`## v<version>\` section) \u2014 refusing to overwrite it. Move it aside, or write elsewhere with \`-o <file>\`.`),h=$.markdown,b=$.carried}await vu.writeFile(o,w+h,"utf8"),v(`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`:""}.`)})}Pr();var fs=["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:"Platform asks",section:"platform_feedback",ranked:!1},{heading:"Requested rollups",section:"platform_feedback",ranked:!1},{heading:"Agent rules",section:"agent_rule",ranked:!1}];function X0(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var HB=new Map(Y0.map(t=>[X0(t.heading),t]));var VB=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 eP={update_page:"append to the existing page",new_page:"create a NEW page"},Ir=(t,e)=>` ${g.dim(t.padEnd(11))}${e}`,pb=t=>t.ownerEmail??t.ownerId;function mo(t){return!t.needsPageRef&&!t.blockedBy}var ua=t=>g.green(t?` + ${t}`:" +"),tP=t=>g.red(t?` - ${t}`:" -"),Cn=t=>g.dim(` ${t}`),rP=` ${g.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,_u=80;function nP(t){let e=[rP];t.target?(e.push(Cn(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(tP(`visibility: ${t.target.visibility}`)),e.push(ua("visibility: admin"))):e.push(Cn(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(Cn("title, slug, evidence: untouched")),e.push(Cn("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(Cn("turbobase.document \xB7 new")),e.push(ua(`title: ${t.pageTitle}`)),e.push(ua("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(Cn('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(Cn('appended under "## From app developers":'));let r=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
3733
- `);for(let n of r.slice(0,_u))e.push(ua(n?` ${n}`:""));return r.length>_u&&e.push(g.yellow(` \u2026 ${r.length-_u} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function oP(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(Ir("page",s?`${s.title} (${s.slug}) [${s.visibility}]`:g.dim("new \u2014 no existing page matches"))),r.push(Ir("action",mo(n)?eP[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(Ir("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(Ir("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(Ir("confidence",n.withdraws?g.red("WITHDRAWN from readers (text untouched)"):g.dim("untouched"))),n.supersedes&&r.push(Ir("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(Ir("blocked",g.red(`unpublished work on this page belongs to ${pb(n.blockedBy)} \u2014 this page will be SKIPPED`))),n.alsoMatched.length>0&&r.push(Ir("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(p=>p.key===c),u=l>=0?t[l]:void 0;return u?`#${l+1} "${u.pageTitle}"`:c});r.push(Ir("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&&mo(n)&&r.push(...nP(n)),r.push("")}),r}function sP(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(mo)} page(s)`,`${e(l=>l.action==="update_page"&&mo(l))} appended`,`${e(l=>l.action==="new_page"&&mo(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 iP(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?pb(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 ub(t){if(t instanceof le){let e=t.body;t.status===403&&e?.reason==="admin_required"&&k("learnings push-kb is admin-only \u2014 the stored token belongs to a non-admin user. Ask an instance administrator to run it, or to grant the role."),t.status===404&&k("this instance does not serve /v1/learnings \u2014 it predates the app-developer learning loop. Ask for an instance upgrade.")}se(t,"extensions:deploy","learnings push-kb")}async function ms(t,e){let r;try{r=await ae("re-reading pushed markdown",()=>t.learningsIngest(e))}catch(o){return o instanceof le&&o.status===404?q(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`.")):uy(o)?q(g.yellow(db(o))):q(g.yellow(`could not re-read the pushed markdown: ${db(o)} \u2014 planning anyway.`)),null}if(r.filesScanned===0)return q(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`)),q(g.dim(n.join(" \xB7 "))),r}function db(t){return t instanceof Error?t.message:String(t)}async function hb(t,e=r=>new ee(r)){t.section&&!fs.includes(t.section.trim())&&k(`unknown --section "${t.section}" \u2014 expected one of ${fs.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&k("--limit must be a positive integer.");let r=await ne(t.baseUrl),n=e(r),o={...t.app?{app:t.app}:{},...t.section?{section:t.section.trim()}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{}},s=await ms(n,t.app),i;try{i=await ae("reading the pending queue",()=>n.learningsPending(o))}catch(l){ub(l),k(`could not read the pending queue: ${l instanceof Error?l.message:String(l)}`)}if(i.items.length===0){if(i.pendingTotal===0&&s&&s.entriesDuplicate>0){q(`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}q(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(v(oP(i.items,{diff:Q0(t)}).join(`
3734
- `)),v(sP(i.items)),t.dryRun){q(g.dim("dry run \u2014 nothing was written."));return}let a=i.items.filter(mo);if(a.length===0){q(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(!ft()){q(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"){q("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{let l=await ae("writing pages",()=>n.learningsPushKb(i.planToken,o));v(iP(l.applied,i.items).join(`
3735
- `))}catch(l){if(l instanceof le&&l.status===409){q(g.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),q(`re-run \`${hs} kb push\` to review the current plan.`),process.exitCode=2;return}ub(l),q(g.red(`turbobase: ${l instanceof Error?l.message:String(l)}`)),process.exitCode=2}}Pr();var go=t=>new ee(t);async function yo(t,e){let r=await ne(t.baseUrl);return e(r)}async function da(t,e,r,n){return n.yes?!0:ft()?await mt(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(q("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(q(g.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function aP(t){return t.visibility!=="published"?g.dim("draft"):t.in_current_release?g.green("live"):g.yellow("unreleased")}function fb(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function cP(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(`${fb(g.bold(s.slug),e)} ${fb(aP(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 mb(t,e=go){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&k(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await yo(t,e),o;try{o=await ae("reading the knowledge base",()=>n.docsList(r))}catch(s){se(s,"docs:publish","read the knowledge base"),k(`could not read the knowledge base: ${s instanceof Error?s.message:String(s)}`)}v(cP(o).join(`
3736
- `))}async function gb(t,e,r=go){let n=[...new Set(t.map(c=>c.trim()).filter(Boolean))];n.length===0&&k("name at least one page slug. `turbobase kb list` shows them.");let o=await yo(e,r);if(!await da(`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 ae("publishing",()=>o.docsPublish(n))}catch(c){se(c,"docs:publish","publish a page"),k(`publish failed: ${c instanceof Error?c.message:String(c)}`)}let a=i.published.map(c=>c.slug);v(g.green(`published ${a.length} page(s) \u2014 readable now.`)),i.missing.length>0&&(q(g.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1),q(g.dim(`undo with: turbobase kb unpublish ${a.join(" ")}`))}async function yb(t,e,r=go){let n=[...new Set(t.map(c=>c.trim()).filter(Boolean))];n.length===0&&k("name at least one page slug. `turbobase kb list` shows them.");let o=await yo(e,r);if(!await da(`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 ae("unpublishing",()=>o.docsUnpublish(n))}catch(c){se(c,"docs:publish","unpublish a page"),k(`unpublish failed: ${c instanceof Error?c.message:String(c)}`)}let a=i.unpublished.map(c=>c.slug);v(g.green(`unpublished ${a.length} page(s) \u2014 retracted now.`)),q(g.dim(`re-publish with: turbobase kb publish ${a.join(" ")}`)),i.missing.length>0&&(q(g.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1)}async function bb(t,e=go){let r=await yo(t,e),n;try{n=await ae("reading the releases",()=>r.docsVersions())}catch(o){se(o,"docs:publish","read the knowledge-base releases"),k(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){v("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(" ");v(`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&&v(` ${g.dim(o.release_note)}`)}}async function wb(t,e,r=go){let n=Number(t);(!Number.isInteger(n)||n<1)&&k(`version must be a release number (got '${t}'). \`turbobase kb versions\` lists them.`);let o=await yo(e,r);if(await da(`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 ae("rolling back",()=>o.docsRollback(n));v(g.green(`rolled back \u2014 release v${i.version.version_no} is current.`))}catch(i){se(i,"docs:publish","roll the knowledge base back"),k(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function vb(t,e,r=go){let n=(t??"").trim();n||k("name the page slug to delete. `turbobase kb list` shows them.");let o=await yo(e,r);if(await da(`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 ae("deleting",()=>o.docsDelete(n));v(g.green(`deleted ${i.deleted} \u2014 restorable from the knowledge-base trash.`))}catch(i){se(i,"docs:publish","delete a page"),k(`delete failed: ${i instanceof Error?i.message:String(i)}`)}}Pr();function lP(t){return t.diff??!!t.dryRun}function uP(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(`
3737
- `))r.push(` ${g.dim("|")} ${a}`)}r.push("")}),r}function dP(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 _b(t,e=r=>new ee(r)){t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&k("--limit must be a positive integer.");let r=await ne(t.baseUrl),n=e(r),o={...t.app?{app:t.app}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{},...t.reapply?{reapply:!0}:{}},s=await ms(n,t.app),i;try{i=await ae("reading the pending rules",()=>n.rulesPending(o))}catch(c){se(c,"extensions:deploy","read the pending rules"),k(`could not read the pending queue: ${c instanceof Error?c.message:String(c)}`)}if(i.items.length===0){if(i.pendingTotal===0&&!t.reapply&&s&&s.entriesDuplicate>0){q(`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}q(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(v(uP(i.items,{diff:lP(t)}).join(`
3738
- `)),v(dP(i.items)),t.dryRun){q(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(!ft()){q(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"){q("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{await ae("writing the rules",()=>n.rulesPush(i.planToken,o))}catch(c){c instanceof le&&c.status===409&&k("the pending queue changed while you were reading the plan \u2014 nothing was written. Re-run to see the new plan."),k(`push failed: ${c instanceof Error?c.message:String(c)}`)}v(g.green(`wrote ${i.items.length} draft rule(s).`)),q(g.dim("They are DRAFT \u2014 nothing is injected yet. An admin reviews and publishes them under Settings \u203A Skills."))}Pr();var pP=["proposed","active","rejected"],hP=["mechanic","operator","learning","code-baseline"],pa=t=>new ee(t);async function ha(t,e){let r=await ne(t.baseUrl);return e(r)}function xb(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)||k(`${r}: unknown value '${o}' \u2014 expected one of ${e.join(", ")}.`);return n}}function fP(t){if(t===void 0)return;let e=Number(t);return(!Number.isFinite(e)||e<=0)&&k("--limit must be a positive number."),Math.floor(e)}function Sb(t){let e=xb(t.status,pP,"--status"),r=xb(t.provenance,hP,"--provenance"),n=fP(t.limit);return{...e?{status:e}:{},...r?{provenance:r}:{},...t.recordType?{recordType:t.recordType}:{},...t.source?{source:t.source}:{},...n?{limit:n}:{}}}function kb(t){return!!(t.provenance?.length||t.recordType||t.source)}var Tb=["ID","STATUS","PROVENANCE","RECORD","EVENT","SOURCE","EVIDENCE","ENFORCES"];function mP(t){return t.status==="active"?g.green("active"):t.status==="rejected"?g.dim("rejected"):g.yellow("proposed")}function gP(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 Eb(t){return[t.hookId,mP(t),t.provenance==="learning"?g.yellow(t.provenance):t.provenance,t.recordType,t.event,t.source,String(t.taughtBy.length),gP(t)]}async function Rb(t={},e=pa){let r=await ha(t,e),n=Sb(t),o;try{o=await r.proposals(n)}catch(i){se(i,"extensions:deploy","list hook proposals"),k(`list hook proposals failed: ${i instanceof Error?i.message:String(i)}`)}if(t.json)return v(JSON.stringify(o,null,2));if(o.length===0){let i=n.status?.length?n.status.join("/"):"proposed";return v(`no ${i} hook proposals.
3739
- `+g.dim(" the Mechanic stages one when a sync failure teaches a repeatable invariant."))}v(Qt(o.map(Eb),{head:Tb})),v(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&&v(g.dim(` ${s.length} learning-provenance row(s) shown \u2014 those are armed through sign-off in the console, not from here.`))}async function yP(t,e,r){return r.yes?!0:ft()?await mt(t,[{value:"yes",label:e},{value:"no",label:"No \u2014 leave them alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(q("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(q(g.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function bP(t){return!(t instanceof le)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function xu(t,e){bP(t)&&se(t,"extensions:deploy",e)}function ku(t,e){let r=e instanceof le?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);q(Ke.error(`${g.bold(t)} \u2014 ${s}`))}async function $b(t,e){try{let r=await t.proposalPromote(e);return v(Ke.success(`${g.bold(e)} ${g.dim(`${r.previousStatus} \u2192`)} ${g.green(r.status)}`)),!0}catch(r){return xu(r,"promote a hook proposal"),ku(e,r),!1}}async function Pb(t,e={},r=pa){!e.auto&&t.length===0&&k("promote: name at least one proposal id, or pass --auto with a filter."),e.auto&&t.length>0&&k("promote: pass ids OR --auto, not both \u2014 --auto selects by filter."),!e.auto&&(e.apply||e.all)&&k("promote: --apply / --all only mean something with --auto.");let n=await ha(e,r);if(!e.auto){let u=0;for(let p of t)await $b(n,p)&&(u+=1);u>0&&v(g.dim(` ${u} hook(s) armed \u2014 the loader compiles them on its next reload.`)),u<t.length&&(process.exitCode=1);return}let o=Sb({...e,status:e.status??"proposed"});o.provenance?.includes("learning")&&k("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")&&k("promote --auto: only `--status proposed` rows can be armed in bulk.");let s;try{s=await n.proposals(o)}catch(u){se(u,"extensions:deploy","list hook proposals"),k(`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&&(v(JSON.stringify({apply:!!e.apply,plan:a,skipped:i},null,2)),!e.apply))return;if(a.length===0){e.json||(v(`nothing to promote${kb(o)?" for that filter":""}.`),i.length>0&&v(g.dim(` ${i.length} learning-provenance row(s) skipped \u2014 they need sign-off.`)));return}if(e.json||(v(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):`),v(Qt(a.map(Eb),{head:Tb})),i.length>0&&v(g.dim(` ${i.length} learning-provenance row(s) skipped \u2014 armed through sign-off in the console.`))),!e.apply){v(""),v(Ke.info("nothing was changed. Re-run with --apply to arm these."));return}if(!kb(o)&&!e.all&&k(`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 yP(`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 $b(n,u.hookId)&&(l+=1);v(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 Ab(t,e={},r=pa){t.length===0&&k("retract: name at least one proposal id.");let n=await ha(e,r),o=0;for(let s of t)try{let i=await n.proposalRetract(s);v(Ke.success(`${g.bold(s)} ${g.dim(`${i.previousStatus} \u2192`)} ${g.yellow(i.status)}`)),o+=1}catch(i){xu(i,"retract a hook proposal"),ku(s,i)}o>0&&v(g.dim(" source kept \u2014 re-arm with `turbobase ext proposals promote <id>`.")),o<t.length&&(process.exitCode=1)}async function Ib(t,e={},r=pa){t.length===0&&k("reject: name at least one proposal id.");let n=await ha(e,r),o=0;for(let s of t)try{let i=await n.proposalReject(s,e.reason);v(Ke.success(`${g.bold(s)} ${g.dim(`${i.previousStatus} \u2192`)} ${g.dim(i.status)}`)),o+=1}catch(i){xu(i,"reject a hook proposal"),ku(s,i)}o<t.length&&(process.exitCode=1)}Pr();var bo=t=>new ee(t);async function wo(t,e){let r=await ne(t.baseUrl);return e(r)}async function fa(t,e,r,n){return n.yes?!0:ft()?await mt(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(q("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(q(g.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function wP(t){return t.visibility!=="published"?g.dim("draft"):t.in_current_release?g.green("live"):g.yellow("unreleased")}function Ob(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function vP(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(`${Ob(g.bold(s.slug),e)} ${Ob(wP(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 Cb(t,e=bo){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&k(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await wo(t,e),o;try{o=await ae("reading the skills",()=>n.skillsList(r))}catch(s){se(s,"skills:publish","read the instance skills"),k(`could not read the skills: ${s instanceof Error?s.message:String(s)}`)}v(vP(o).join(`
3740
- `))}async function Nb(t,e,r=bo){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&k("name at least one skill slug. `turbobase skills list` shows them.");let o=await wo(e,r);if(!await fa(`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 ae("publishing",()=>o.skillsPublish(n))}catch(a){se(a,"skills:publish","publish a skill"),k(`publish failed: ${a instanceof Error?a.message:String(a)}`)}v(g.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(q(g.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),q(g.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function zb(t,e,r=bo){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&k("name at least one skill slug. `turbobase skills list` shows them.");let o=await wo(e,r);if(!await fa(`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 ae("unpublishing",()=>o.skillsUnpublish(n))}catch(a){se(a,"skills:publish","unpublish a skill"),k(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}v(g.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),q(g.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(q(g.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function jb(t,e,r=bo){let n=Number(t);(!Number.isInteger(n)||n<1)&&k(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let o=await wo(e,r);if(await fa(`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 ae("rolling back",()=>o.skillsRollback(n));v(g.green(`rolled back to v${i.version.version_no}.`))}catch(i){se(i,"skills:publish","roll back a skills release"),k(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function Lb(t,e=bo){let r=await wo(t,e),n;try{n=await ae("reading the releases",()=>r.skillsReleases())}catch(o){se(o,"skills:publish","read the skills releases"),k(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){q("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}`:"";v(`${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 Db(t,e,r=bo){let n=[...new Set((t??[]).map(l=>l.trim()).filter(Boolean))];n.length===0&&k("name at least one skill to delete. `turbobase skills list` shows the slugs.");let o=await wo(e,r);if(!await fa(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
3737
+ `,carried:s}}function pb(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=J0(process.cwd(),e.out),s=e.since?.trim()||await X0(o),i=new URLSearchParams;s&&i.set("since",s);let a=i.toString(),c=await fetch(`${r}/v1/catalog/adopt-notes${a?`?${a}`:""}`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/json"}});c.ok||k(`adopt fetch failed: GET /v1/catalog/adopt-notes \u2192 ${c.status}`);let l=await c.json();if(!l.available){v(`${r} ships no release notes to adopt from (nothing written).`);return}let u=l.releases.reduce(($,E)=>$+E.items.length,0);if(u===0){v(`up to date${s?` since v${s.replace(/^v/,"")}`:""}${l.currentVersion?` (instance is on v${l.currentVersion})`:""} \u2014 ${o} left untouched.`);return}let p=l.currentVersion??l.releases[0]?.version??"",w=`<!-- GENERATED by \`turbobase project adopt\` against ${r} \u2014 adopted-through=${p}. Re-run to refresh; delete this file once every line is done. -->
3738
+
3739
+ `,f=await xu.readFile(o,"utf8").catch(()=>null),h=l.markdown,b=0;if(f!==null&&f.trim()!==""){let $=rP(f,l.markdown);$||k(`${o} was not written by \`turbobase project adopt\` (no generated header, no \`## v<version>\` section) \u2014 refusing to overwrite it. Move it aside, or write elsewhere with \`-o <file>\`.`),h=$.markdown,b=$.carried}await xu.writeFile(o,w+h,"utf8"),v(`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`:""}.`)})}Pr();var fs=["suggested_kb_edit","kb_correction"];var nP=[{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:"Platform asks",section:"platform_feedback",ranked:!1},{heading:"Requested rollups",section:"platform_feedback",ranked:!1},{heading:"Agent rules",section:"agent_rule",ranked:!1}];function oP(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var YB=new Map(nP.map(t=>[oP(t.heading),t]));var XB=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 sP(t){return t.diff??!!t.dryRun}var iP={update_page:"append to the existing page",new_page:"create a NEW page"},Ir=(t,e)=>` ${g.dim(t.padEnd(11))}${e}`,mb=t=>t.ownerEmail??t.ownerId;function mo(t){return!t.needsPageRef&&!t.blockedBy}var pa=t=>g.green(t?` + ${t}`:" +"),aP=t=>g.red(t?` - ${t}`:" -"),Cn=t=>g.dim(` ${t}`),cP=` ${g.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,ku=80;function lP(t){let e=[cP];t.target?(e.push(Cn(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(aP(`visibility: ${t.target.visibility}`)),e.push(pa("visibility: admin"))):e.push(Cn(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(Cn("title, slug, evidence: untouched")),e.push(Cn("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(Cn("turbobase.document \xB7 new")),e.push(pa(`title: ${t.pageTitle}`)),e.push(pa("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(Cn('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(Cn('appended under "## From app developers":'));let r=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
3740
+ `);for(let n of r.slice(0,ku))e.push(pa(n?` ${n}`:""));return r.length>ku&&e.push(g.yellow(` \u2026 ${r.length-ku} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function uP(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(Ir("page",s?`${s.title} (${s.slug}) [${s.visibility}]`:g.dim("new \u2014 no existing page matches"))),r.push(Ir("action",mo(n)?iP[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(Ir("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(Ir("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(Ir("confidence",n.withdraws?g.red("WITHDRAWN from readers (text untouched)"):g.dim("untouched"))),n.supersedes&&r.push(Ir("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(Ir("blocked",g.red(`unpublished work on this page belongs to ${mb(n.blockedBy)} \u2014 this page will be SKIPPED`))),n.alsoMatched.length>0&&r.push(Ir("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(p=>p.key===c),u=l>=0?t[l]:void 0;return u?`#${l+1} "${u.pageTitle}"`:c});r.push(Ir("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&&mo(n)&&r.push(...lP(n)),r.push("")}),r}function dP(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(mo)} page(s)`,`${e(l=>l.action==="update_page"&&mo(l))} appended`,`${e(l=>l.action==="new_page"&&mo(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 pP(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?mb(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 hb(t){if(t instanceof le){let e=t.body;t.status===403&&e?.reason==="admin_required"&&k("learnings push-kb is admin-only \u2014 the stored token belongs to a non-admin user. Ask an instance administrator to run it, or to grant the role."),t.status===404&&k("this instance does not serve /v1/learnings \u2014 it predates the app-developer learning loop. Ask for an instance upgrade.")}se(t,"extensions:deploy","learnings push-kb")}async function ms(t,e){let r;try{r=await ae("re-reading pushed markdown",()=>t.learningsIngest(e))}catch(o){return o instanceof le&&o.status===404?q(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`.")):hy(o)?q(g.yellow(fb(o))):q(g.yellow(`could not re-read the pushed markdown: ${fb(o)} \u2014 planning anyway.`)),null}if(r.filesScanned===0)return q(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`)),q(g.dim(n.join(" \xB7 "))),r}function fb(t){return t instanceof Error?t.message:String(t)}async function gb(t,e=r=>new ee(r)){t.section&&!fs.includes(t.section.trim())&&k(`unknown --section "${t.section}" \u2014 expected one of ${fs.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&k("--limit must be a positive integer.");let r=await ne(t.baseUrl),n=e(r),o={...t.app?{app:t.app}:{},...t.section?{section:t.section.trim()}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{}},s=await ms(n,t.app),i;try{i=await ae("reading the pending queue",()=>n.learningsPending(o))}catch(l){hb(l),k(`could not read the pending queue: ${l instanceof Error?l.message:String(l)}`)}if(i.items.length===0){if(i.pendingTotal===0&&s&&s.entriesDuplicate>0){q(`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}q(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(v(uP(i.items,{diff:sP(t)}).join(`
3741
+ `)),v(dP(i.items)),t.dryRun){q(g.dim("dry run \u2014 nothing was written."));return}let a=i.items.filter(mo);if(a.length===0){q(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(!ft()){q(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"){q("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{let l=await ae("writing pages",()=>n.learningsPushKb(i.planToken,o));v(pP(l.applied,i.items).join(`
3742
+ `))}catch(l){if(l instanceof le&&l.status===409){q(g.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),q(`re-run \`${hs} kb push\` to review the current plan.`),process.exitCode=2;return}hb(l),q(g.red(`turbobase: ${l instanceof Error?l.message:String(l)}`)),process.exitCode=2}}Pr();var go=t=>new ee(t);async function yo(t,e){let r=await ne(t.baseUrl);return e(r)}async function ha(t,e,r,n){return n.yes?!0:ft()?await mt(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(q("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(q(g.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function hP(t){return t.visibility!=="published"?g.dim("draft"):t.in_current_release?g.green("live"):g.yellow("unreleased")}function yb(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function fP(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(`${yb(g.bold(s.slug),e)} ${yb(hP(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 bb(t,e=go){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&k(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await yo(t,e),o;try{o=await ae("reading the knowledge base",()=>n.docsList(r))}catch(s){se(s,"docs:publish","read the knowledge base"),k(`could not read the knowledge base: ${s instanceof Error?s.message:String(s)}`)}v(fP(o).join(`
3743
+ `))}async function wb(t,e,r=go){let n=[...new Set(t.map(c=>c.trim()).filter(Boolean))];n.length===0&&k("name at least one page slug. `turbobase kb list` shows them.");let o=await yo(e,r);if(!await ha(`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 ae("publishing",()=>o.docsPublish(n))}catch(c){se(c,"docs:publish","publish a page"),k(`publish failed: ${c instanceof Error?c.message:String(c)}`)}let a=i.published.map(c=>c.slug);v(g.green(`published ${a.length} page(s) \u2014 readable now.`)),i.missing.length>0&&(q(g.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1),q(g.dim(`undo with: turbobase kb unpublish ${a.join(" ")}`))}async function vb(t,e,r=go){let n=[...new Set(t.map(c=>c.trim()).filter(Boolean))];n.length===0&&k("name at least one page slug. `turbobase kb list` shows them.");let o=await yo(e,r);if(!await ha(`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 ae("unpublishing",()=>o.docsUnpublish(n))}catch(c){se(c,"docs:publish","unpublish a page"),k(`unpublish failed: ${c instanceof Error?c.message:String(c)}`)}let a=i.unpublished.map(c=>c.slug);v(g.green(`unpublished ${a.length} page(s) \u2014 retracted now.`)),q(g.dim(`re-publish with: turbobase kb publish ${a.join(" ")}`)),i.missing.length>0&&(q(g.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1)}async function _b(t,e=go){let r=await yo(t,e),n;try{n=await ae("reading the releases",()=>r.docsVersions())}catch(o){se(o,"docs:publish","read the knowledge-base releases"),k(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){v("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(" ");v(`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&&v(` ${g.dim(o.release_note)}`)}}async function xb(t,e,r=go){let n=Number(t);(!Number.isInteger(n)||n<1)&&k(`version must be a release number (got '${t}'). \`turbobase kb versions\` lists them.`);let o=await yo(e,r);if(await ha(`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 ae("rolling back",()=>o.docsRollback(n));v(g.green(`rolled back \u2014 release v${i.version.version_no} is current.`))}catch(i){se(i,"docs:publish","roll the knowledge base back"),k(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function kb(t,e,r=go){let n=(t??"").trim();n||k("name the page slug to delete. `turbobase kb list` shows them.");let o=await yo(e,r);if(await ha(`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 ae("deleting",()=>o.docsDelete(n));v(g.green(`deleted ${i.deleted} \u2014 restorable from the knowledge-base trash.`))}catch(i){se(i,"docs:publish","delete a page"),k(`delete failed: ${i instanceof Error?i.message:String(i)}`)}}Pr();function mP(t){return t.diff??!!t.dryRun}function gP(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(`
3744
+ `))r.push(` ${g.dim("|")} ${a}`)}r.push("")}),r}function yP(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 $b(t,e=r=>new ee(r)){t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&k("--limit must be a positive integer.");let r=await ne(t.baseUrl),n=e(r),o={...t.app?{app:t.app}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{},...t.reapply?{reapply:!0}:{}},s=await ms(n,t.app),i;try{i=await ae("reading the pending rules",()=>n.rulesPending(o))}catch(c){se(c,"extensions:deploy","read the pending rules"),k(`could not read the pending queue: ${c instanceof Error?c.message:String(c)}`)}if(i.items.length===0){if(i.pendingTotal===0&&!t.reapply&&s&&s.entriesDuplicate>0){q(`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}q(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(v(gP(i.items,{diff:mP(t)}).join(`
3745
+ `)),v(yP(i.items)),t.dryRun){q(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(!ft()){q(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"){q("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{await ae("writing the rules",()=>n.rulesPush(i.planToken,o))}catch(c){c instanceof le&&c.status===409&&k("the pending queue changed while you were reading the plan \u2014 nothing was written. Re-run to see the new plan."),k(`push failed: ${c instanceof Error?c.message:String(c)}`)}v(g.green(`wrote ${i.items.length} draft rule(s).`)),q(g.dim("They are DRAFT \u2014 nothing is injected yet. An admin reviews and publishes them under Settings \u203A Skills."))}Pr();var bP=["proposed","active","rejected"],wP=["mechanic","operator","learning","code-baseline"],fa=t=>new ee(t);async function ma(t,e){let r=await ne(t.baseUrl);return e(r)}function Sb(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)||k(`${r}: unknown value '${o}' \u2014 expected one of ${e.join(", ")}.`);return n}}function vP(t){if(t===void 0)return;let e=Number(t);return(!Number.isFinite(e)||e<=0)&&k("--limit must be a positive number."),Math.floor(e)}function Rb(t){let e=Sb(t.status,bP,"--status"),r=Sb(t.provenance,wP,"--provenance"),n=vP(t.limit);return{...e?{status:e}:{},...r?{provenance:r}:{},...t.recordType?{recordType:t.recordType}:{},...t.source?{source:t.source}:{},...n?{limit:n}:{}}}function Tb(t){return!!(t.provenance?.length||t.recordType||t.source)}var Pb=["ID","STATUS","PROVENANCE","RECORD","EVENT","SOURCE","EVIDENCE","ENFORCES"];function _P(t){return t.status==="active"?g.green("active"):t.status==="rejected"?g.dim("rejected"):g.yellow("proposed")}function xP(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 Ab(t){return[t.hookId,_P(t),t.provenance==="learning"?g.yellow(t.provenance):t.provenance,t.recordType,t.event,t.source,String(t.taughtBy.length),xP(t)]}async function Ib(t={},e=fa){let r=await ma(t,e),n=Rb(t),o;try{o=await r.proposals(n)}catch(i){se(i,"extensions:deploy","list hook proposals"),k(`list hook proposals failed: ${i instanceof Error?i.message:String(i)}`)}if(t.json)return v(JSON.stringify(o,null,2));if(o.length===0){let i=n.status?.length?n.status.join("/"):"proposed";return v(`no ${i} hook proposals.
3746
+ `+g.dim(" the Mechanic stages one when a sync failure teaches a repeatable invariant."))}v(Qt(o.map(Ab),{head:Pb})),v(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&&v(g.dim(` ${s.length} learning-provenance row(s) shown \u2014 those are armed through sign-off in the console, not from here.`))}async function kP(t,e,r){return r.yes?!0:ft()?await mt(t,[{value:"yes",label:e},{value:"no",label:"No \u2014 leave them alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(q("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(q(g.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function $P(t){return!(t instanceof le)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function $u(t,e){$P(t)&&se(t,"extensions:deploy",e)}function Su(t,e){let r=e instanceof le?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);q(Ke.error(`${g.bold(t)} \u2014 ${s}`))}async function Eb(t,e){try{let r=await t.proposalPromote(e);return v(Ke.success(`${g.bold(e)} ${g.dim(`${r.previousStatus} \u2192`)} ${g.green(r.status)}`)),!0}catch(r){return $u(r,"promote a hook proposal"),Su(e,r),!1}}async function Ob(t,e={},r=fa){!e.auto&&t.length===0&&k("promote: name at least one proposal id, or pass --auto with a filter."),e.auto&&t.length>0&&k("promote: pass ids OR --auto, not both \u2014 --auto selects by filter."),!e.auto&&(e.apply||e.all)&&k("promote: --apply / --all only mean something with --auto.");let n=await ma(e,r);if(!e.auto){let u=0;for(let p of t)await Eb(n,p)&&(u+=1);u>0&&v(g.dim(` ${u} hook(s) armed \u2014 the loader compiles them on its next reload.`)),u<t.length&&(process.exitCode=1);return}let o=Rb({...e,status:e.status??"proposed"});o.provenance?.includes("learning")&&k("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")&&k("promote --auto: only `--status proposed` rows can be armed in bulk.");let s;try{s=await n.proposals(o)}catch(u){se(u,"extensions:deploy","list hook proposals"),k(`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&&(v(JSON.stringify({apply:!!e.apply,plan:a,skipped:i},null,2)),!e.apply))return;if(a.length===0){e.json||(v(`nothing to promote${Tb(o)?" for that filter":""}.`),i.length>0&&v(g.dim(` ${i.length} learning-provenance row(s) skipped \u2014 they need sign-off.`)));return}if(e.json||(v(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):`),v(Qt(a.map(Ab),{head:Pb})),i.length>0&&v(g.dim(` ${i.length} learning-provenance row(s) skipped \u2014 armed through sign-off in the console.`))),!e.apply){v(""),v(Ke.info("nothing was changed. Re-run with --apply to arm these."));return}if(!Tb(o)&&!e.all&&k(`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 kP(`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 Eb(n,u.hookId)&&(l+=1);v(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 Cb(t,e={},r=fa){t.length===0&&k("retract: name at least one proposal id.");let n=await ma(e,r),o=0;for(let s of t)try{let i=await n.proposalRetract(s);v(Ke.success(`${g.bold(s)} ${g.dim(`${i.previousStatus} \u2192`)} ${g.yellow(i.status)}`)),o+=1}catch(i){$u(i,"retract a hook proposal"),Su(s,i)}o>0&&v(g.dim(" source kept \u2014 re-arm with `turbobase ext proposals promote <id>`.")),o<t.length&&(process.exitCode=1)}async function Nb(t,e={},r=fa){t.length===0&&k("reject: name at least one proposal id.");let n=await ma(e,r),o=0;for(let s of t)try{let i=await n.proposalReject(s,e.reason);v(Ke.success(`${g.bold(s)} ${g.dim(`${i.previousStatus} \u2192`)} ${g.dim(i.status)}`)),o+=1}catch(i){$u(i,"reject a hook proposal"),Su(s,i)}o<t.length&&(process.exitCode=1)}Pr();var bo=t=>new ee(t);async function wo(t,e){let r=await ne(t.baseUrl);return e(r)}async function ga(t,e,r,n){return n.yes?!0:ft()?await mt(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(q("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(q(g.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function SP(t){return t.visibility!=="published"?g.dim("draft"):t.in_current_release?g.green("live"):g.yellow("unreleased")}function zb(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function TP(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(`${zb(g.bold(s.slug),e)} ${zb(SP(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 jb(t,e=bo){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&k(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await wo(t,e),o;try{o=await ae("reading the skills",()=>n.skillsList(r))}catch(s){se(s,"skills:publish","read the instance skills"),k(`could not read the skills: ${s instanceof Error?s.message:String(s)}`)}v(TP(o).join(`
3747
+ `))}async function Lb(t,e,r=bo){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&k("name at least one skill slug. `turbobase skills list` shows them.");let o=await wo(e,r);if(!await ga(`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 ae("publishing",()=>o.skillsPublish(n))}catch(a){se(a,"skills:publish","publish a skill"),k(`publish failed: ${a instanceof Error?a.message:String(a)}`)}v(g.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(q(g.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),q(g.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function Db(t,e,r=bo){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&k("name at least one skill slug. `turbobase skills list` shows them.");let o=await wo(e,r);if(!await ga(`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 ae("unpublishing",()=>o.skillsUnpublish(n))}catch(a){se(a,"skills:publish","unpublish a skill"),k(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}v(g.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),q(g.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(q(g.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function Mb(t,e,r=bo){let n=Number(t);(!Number.isInteger(n)||n<1)&&k(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let o=await wo(e,r);if(await ga(`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 ae("rolling back",()=>o.skillsRollback(n));v(g.green(`rolled back to v${i.version.version_no}.`))}catch(i){se(i,"skills:publish","roll back a skills release"),k(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function Ub(t,e=bo){let r=await wo(t,e),n;try{n=await ae("reading the releases",()=>r.skillsReleases())}catch(o){se(o,"skills:publish","read the skills releases"),k(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){q("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}`:"";v(`${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 qb(t,e,r=bo){let n=[...new Set((t??[]).map(l=>l.trim()).filter(Boolean))];n.length===0&&k("name at least one skill to delete. `turbobase skills list` shows the slugs.");let o=await wo(e,r);if(!await ga(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
3741
3748
  ${n.join(`
3742
- `)}`,"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 ae(`deleting ${l}`,()=>o.skillsDelete(l)))}catch(u){if(u instanceof le&&u.status===404){a.push(l);continue}i.length>0&&q(g.dim(`deleted before the error: ${i.map(p=>p.slug).join(", ")}`)),se(u,"skills:publish","delete a skill"),k(`delete failed on '${l}': ${u instanceof Error?u.message:String(u)}`)}i.length>0&&v(g.green(`deleted ${i.length} skill(s).`));let c=i.filter(l=>l.wasPublished).map(l=>l.slug);c.length>0&&q(g.yellow(`Published until now, so no longer injected: ${c.join(", ")}`)),a.length>0&&(q(g.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as Mb}from"node:fs";import{join as _P,relative as xP,resolve as kP,sep as $P}from"node:path";var SP=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),TP=new Set([".mcp.json",".env"]);function EP(t){return TP.has(t)||t.startsWith(".env.")&&t!==".env.example"}function RP(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function PP(t){return t.includes(0)}async function Ub(t){let e=kP(t),r={},n=[],o=[],s=[];async function i(a){let c=await Mb.readdir(a,{withFileTypes:!0});for(let l of c){let u=_P(a,l.name);if(SP.has(l.name))continue;if(l.isDirectory()){await i(u);continue}if(!l.isFile())continue;let p=xP(e,u).split($P).join("/");if(EP(l.name)){o.push(p);continue}let w=await Mb.readFile(u);if(!RP(w)){n.push(p);continue}PP(w)&&s.push(p),r[p]=w.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as AP}from"node:crypto";var IP="/_tb/app-assets",OP=16,CP=/^[0-9a-f]{32}$/;function qb(){return AP(OP).toString("hex")}function NP(t){return CP.test(t)}function Bb(t){if(!NP(t))throw new Error(`not a build id: ${t}`);return`${IP}/${t}/`}var Zb=7;Su();var Tu=50*1024*1024;import ma from"node:fs/promises";import gs from"node:path";var Eu={esbuild:"0.28.1","isolated-vm":"6.1.2"},Ru="@turbobase/isolated-vm-prebuilds";function Pu(t,e){return`${t}-${e}`}function Au(t=process.versions){return`abi${t.modules}`}var Fb=["darwin-x64","win32-arm64"];async function Hb(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=Pu(e,r),o=gs.join(t.home,"node_modules"),s=gs.join(o,...Ru.split("/"),"prebuilds",n),i=gs.join(o,"isolated-vm","prebuilds",n),a;try{a=await ma.readdir(s)}catch{return[]}let c=[];await ma.mkdir(i,{recursive:!0});for(let l of a){if(!l.endsWith(".node"))continue;let u=gs.join(i,l);try{await ma.copyFile(gs.join(s,l),u,ma.constants?.COPYFILE_EXCL??1),c.push(l)}catch{}}return c}import{homedir as zP}from"node:os";import{join as Vb}from"node:path";import{promises as Iu}from"node:fs";function Wb(){let t=process.env.TURBOBASE_HOME??Vb(zP(),".turbobase");return{dir:t,file:Vb(t,"sandboxes.json")}}var jP={s:1e3,m:6e4,h:36e5,d:864e5};function LP(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*jP[e[2]]}function DP(t,e=Date.now()){return new Date(e+LP(t)).toISOString()}function MP(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function UP(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 qP(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 BP="[REDACTED]",ys=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 ZP(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:BP:n[o]=s}return n}function FP(t,e,r){return e.map(n=>ZP(t,n,r))}var Kb=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),HP=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function VP(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 Cu(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 HP)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=VP(t);if(!Kb.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...Kb].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function KP(t,e=WP){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function WP(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function GP(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function JP(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function Nu(){let{file:t}=Wb();try{let e=await Iu.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function Gb(t){let{dir:e,file:r}=Wb();await Iu.mkdir(e,{recursive:!0}),await Iu.writeFile(r,`${JSON.stringify(t,null,2)}
3743
- `,{mode:384})}async function YP(t){let e=await Nu();e.push(t),await Gb(e)}async function Jb(t){let e=await Nu(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Gb(e),n??null}async function ga(){return Nu()}function zu(t,e=Date.now()){let r=[],n=[];for(let o of t)MP(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function Yb(t,e){Cu(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new ys(r);let n=UP(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>KP(l)))(e.fromTenant),i=GP(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=qP(l.rows,n),p=FP(l.table,u,l.classification);p.length>0&&await t.copyRows(i,l.table,p)}let c={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:DP(e.ttl,o),sampleFraction:n,url:JP(s,e.baseUrl)};return await YP(c),c}async function Xb(t,e){Cu(t.target());let n=(await ga()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await Jb(e),n):null}async function ju(t,e=Date.now()){Cu(t.target());let r=await ga(),{expired:n}=zu(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await Jb(s.name),o.push(s)}return o}var bs={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","mcp:data","mcp:write"],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"}},DZ=Object.keys(bs).filter(t=>bs[t].mintable);var qZ=bs.pat.prefix,XP=Object.entries(bs).map(([t,e])=>[e.prefix,t]),QP=/^[A-Za-z0-9_-]{20,}$/;function eA(t){if(typeof t!="string")return null;for(let[e,r]of XP)if(t.startsWith(e)&&QP.test(t.slice(e.length)))return r;return null}function Qb(t){return eA(t)==="pat"}ss();var tA=8e3,rA={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 nA(t){return rA[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function oA(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(tA)})}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 ew(t){return t.state==="accepted"?tt()?g.green("accepted"):"accepted":t.state==="rejected"?tt()?g.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:tt()?g.yellow("unreachable"):"unreachable"}async function tw(t={},e=fetch){let r=await Rr(),{file:n}=Fi();if(r.length===0){v("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),q(g.dim(`no sign-ins stored in ${n}.`));return}let o=await Xt(),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 oA(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)v(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(tt())v(Qt(s.map(i=>[i.active?g.green("*"):" ",g.bold(i.baseUrl),ew(i.check),g.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)v(`${i.active?"* ":" "}${i.baseUrl} ${ew(i.check)} (updated ${i.updatedAt})`);q(g.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(q(g.red(`${i.baseUrl}: ${nA(i.check.reason)}.`)),q(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"&&q(g.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||q("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function CM(t){let e=await Rr();e.length===0&&k("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),ft()||k("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{k("cancelled.")}}async function NM(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 zM(t){q(""),q("Sharing is ON. Two things reach the Turbobase product team from this instance:"),q(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),q(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),q(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),q(" about OUR platform, with instance name, user names and ids masked before they leave."),q(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),q("")}async function jM(t,e,r){let n=await sy({baseUrl:t,token:e}),o=(await Rr()).length-1;if(v(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),zM(n.baseUrl),!r)return;let s=await NM(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(q(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),q(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),q(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?q(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):q(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function LM(t){let e=await ou(await ls(t),Lr(t)),r=yu(e);if(!r){let n=/\bdefineConduit\s*[<(]/.test(e);k(n?`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`:`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`)}return{...r,sourceCode:e}}async function Xn(t,e,r,n){try{return await be.access(t),"skipped"}catch{}return await be.mkdir(Lr(t),{recursive:!0}),await be.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await be.chmod(t,n),"wrote"}async function QS(t,e){if(tT(t)!==".gitignore")return Xn(t,e.content,e.executable,e.mode);let r=await be.readFile(t,"utf8").catch(()=>null);if(r===null)return Xn(t,e.content,e.executable,e.mode);let n=Ky(r);return n===null?"skipped":(await be.writeFile(t,n,"utf8"),"merged")}function Xm(t){if(t!==void 0){if(t==="junit"||t==="json")return t;k(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function ul(t){process.exit(t)}function DM(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 MM(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 UM(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 eT(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function og({includeInternal:t=!0}={}){let e=new kg;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.23.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${du()}
3744
- `),e.hook("preAction",(d,m)=>{ib(e.opts(),m.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 d=>{let m=Dt(d.baseUrl);d.token||k(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
3745
- ${hs} auth login --base-url ${m} --token tb_pat_\u2026`),Qb(d.token)||k("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await jM(m,d.token,d.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 d=>tw({probe:d.probe})),r.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async d=>{let m=d??await CM("Pick the active instance:"),_=await Hi(m);if(!_){let T=await Rr();k(`no stored sign-in for ${Dt(m)}.`+(T.length?` Stored: ${T.map(x=>x.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${Dt(m)} --token tb_pat_\u2026\`.`)}v(`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 d=>{if(d.all){let T=await Rr();for(let x of T)await Xl(x.baseUrl);v(`removed ${T.length} stored sign-in${T.length===1?"":"s"}.`);return}let m=await Xl(d.baseUrl);m||k(d.baseUrl?`no stored sign-in for ${Dt(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let _=await Xt();v(`signed out of ${m}.`+(_?` 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 d=>{let{baseUrl:m,token:_}=await ne(d.baseUrl),T;try{T=await In({baseUrl:m,token:_,recordsOnly:d.recordsOnly})}catch(y){let S=y instanceof Error?y.message:String(y);if(!d.recordsOnly&&/openapi\.json failed \(401/.test(S)){q("types-gen: /v1/catalog/openapi.json needs a browser session \u2014 emitting record shapes only. The record shapes are the half apps generate against; for the OpenAPI half, run it from a signed-in browser session.");try{T=await In({baseUrl:m,token:_,recordsOnly:!0})}catch(R){k(`types generation failed: ${R instanceof Error?R.message:String(R)}`)}}else k(`types generation failed: ${S}`)}let x=ge(process.cwd(),d.out);await be.writeFile(x,T,"utf8"),v(`wrote ${x} (${T.split(`
3746
- `).length} lines).`)}),lb(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 d=>{let{baseUrl:m,token:_}=await ne(d.baseUrl),T=new URLSearchParams;d.records&&T.set("records",d.records),d.query&&T.set("query",d.query);let x=T.toString(),y=await fetch(`${m}/v1/catalog/grounding${x?`?${x}`:""}`,{headers:{Authorization:`Bearer ${_}`,Accept:"application/json"}});y.ok||k(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${y.status}`);let R=((await y.json()).markdown??"").trim(),N=ge(process.cwd(),d.out),L=d.records?` records=${d.records}`:"",D=`<!-- GENERATED by \`turbobase project grounding\` against ${m}${L} \u2014 do not edit; re-run to refresh. -->
3749
+ `)}`,"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 ae(`deleting ${l}`,()=>o.skillsDelete(l)))}catch(u){if(u instanceof le&&u.status===404){a.push(l);continue}i.length>0&&q(g.dim(`deleted before the error: ${i.map(p=>p.slug).join(", ")}`)),se(u,"skills:publish","delete a skill"),k(`delete failed on '${l}': ${u instanceof Error?u.message:String(u)}`)}i.length>0&&v(g.green(`deleted ${i.length} skill(s).`));let c=i.filter(l=>l.wasPublished).map(l=>l.slug);c.length>0&&q(g.yellow(`Published until now, so no longer injected: ${c.join(", ")}`)),a.length>0&&(q(g.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as Bb}from"node:fs";import{join as EP,relative as RP,resolve as PP,sep as AP}from"node:path";var IP=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),OP=new Set([".mcp.json",".env"]);function CP(t){return OP.has(t)||t.startsWith(".env.")&&t!==".env.example"}function NP(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function zP(t){return t.includes(0)}async function Zb(t){let e=PP(t),r={},n=[],o=[],s=[];async function i(a){let c=await Bb.readdir(a,{withFileTypes:!0});for(let l of c){let u=EP(a,l.name);if(IP.has(l.name))continue;if(l.isDirectory()){await i(u);continue}if(!l.isFile())continue;let p=RP(e,u).split(AP).join("/");if(CP(l.name)){o.push(p);continue}let w=await Bb.readFile(u);if(!NP(w)){n.push(p);continue}zP(w)&&s.push(p),r[p]=w.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as jP}from"node:crypto";var LP="/_tb/app-assets",DP=16,MP=/^[0-9a-f]{32}$/;function Fb(){return jP(DP).toString("hex")}function UP(t){return MP.test(t)}function Hb(t){if(!UP(t))throw new Error(`not a build id: ${t}`);return`${LP}/${t}/`}var Vb=7;Eu();var Ru=50*1024*1024;import ya from"node:fs/promises";import gs from"node:path";var Pu={esbuild:"0.28.1","isolated-vm":"6.1.2"},Au="@turbobase/isolated-vm-prebuilds";function Iu(t,e){return`${t}-${e}`}function Ou(t=process.versions){return`abi${t.modules}`}var Kb=["darwin-x64","win32-arm64"];async function Wb(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=Iu(e,r),o=gs.join(t.home,"node_modules"),s=gs.join(o,...Au.split("/"),"prebuilds",n),i=gs.join(o,"isolated-vm","prebuilds",n),a;try{a=await ya.readdir(s)}catch{return[]}let c=[];await ya.mkdir(i,{recursive:!0});for(let l of a){if(!l.endsWith(".node"))continue;let u=gs.join(i,l);try{await ya.copyFile(gs.join(s,l),u,ya.constants?.COPYFILE_EXCL??1),c.push(l)}catch{}}return c}import{homedir as qP}from"node:os";import{join as Gb}from"node:path";import{promises as Cu}from"node:fs";function Yb(){let t=process.env.TURBOBASE_HOME??Gb(qP(),".turbobase");return{dir:t,file:Gb(t,"sandboxes.json")}}var BP={s:1e3,m:6e4,h:36e5,d:864e5};function ZP(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*BP[e[2]]}function FP(t,e=Date.now()){return new Date(e+ZP(t)).toISOString()}function HP(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function VP(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 KP(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 WP="[REDACTED]",ys=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},Nu=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 GP(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new Nu(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:WP:n[o]=s}return n}function JP(t,e,r){return e.map(n=>GP(t,n,r))}var Jb=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),YP=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function XP(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 zu(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 YP)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=XP(t);if(!Jb.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...Jb].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function QP(t,e=eA){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function eA(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function tA(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function rA(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function ju(){let{file:t}=Yb();try{let e=await Cu.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function Xb(t){let{dir:e,file:r}=Yb();await Cu.mkdir(e,{recursive:!0}),await Cu.writeFile(r,`${JSON.stringify(t,null,2)}
3750
+ `,{mode:384})}async function nA(t){let e=await ju();e.push(t),await Xb(e)}async function Qb(t){let e=await ju(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Xb(e),n??null}async function ba(){return ju()}function Lu(t,e=Date.now()){let r=[],n=[];for(let o of t)HP(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function ew(t,e){zu(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new ys(r);let n=VP(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>QP(l)))(e.fromTenant),i=tA(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=KP(l.rows,n),p=JP(l.table,u,l.classification);p.length>0&&await t.copyRows(i,l.table,p)}let c={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:FP(e.ttl,o),sampleFraction:n,url:rA(s,e.baseUrl)};return await nA(c),c}async function tw(t,e){zu(t.target());let n=(await ba()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await Qb(e),n):null}async function Du(t,e=Date.now()){zu(t.target());let r=await ba(),{expired:n}=Lu(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await Qb(s.name),o.push(s)}return o}var bs={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","mcp:data","mcp:write"],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"}},FZ=Object.keys(bs).filter(t=>bs[t].mintable);var KZ=bs.pat.prefix,oA=Object.entries(bs).map(([t,e])=>[e.prefix,t]),sA=/^[A-Za-z0-9_-]{20,}$/;function iA(t){if(typeof t!="string")return null;for(let[e,r]of oA)if(t.startsWith(e)&&sA.test(t.slice(e.length)))return r;return null}function rw(t){return iA(t)==="pat"}ss();var aA=8e3,cA={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 lA(t){return cA[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function uA(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(aA)})}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 nw(t){return t.state==="accepted"?tt()?g.green("accepted"):"accepted":t.state==="rejected"?tt()?g.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:tt()?g.yellow("unreachable"):"unreachable"}async function ow(t={},e=fetch){let r=await Rr(),{file:n}=Vi();if(r.length===0){v("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),q(g.dim(`no sign-ins stored in ${n}.`));return}let o=await Xt(),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 uA(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)v(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(tt())v(Qt(s.map(i=>[i.active?g.green("*"):" ",g.bold(i.baseUrl),nw(i.check),g.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)v(`${i.active?"* ":" "}${i.baseUrl} ${nw(i.check)} (updated ${i.updatedAt})`);q(g.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(q(g.red(`${i.baseUrl}: ${lA(i.check.reason)}.`)),q(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"&&q(g.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||q("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function MM(t){let e=await Rr();e.length===0&&k("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),ft()||k("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{k("cancelled.")}}async function UM(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 qM(t){q(""),q("Sharing is ON. Two things reach the Turbobase product team from this instance:"),q(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),q(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),q(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),q(" about OUR platform, with instance name, user names and ids masked before they leave."),q(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),q("")}async function BM(t,e,r){let n=await cy({baseUrl:t,token:e}),o=(await Rr()).length-1;if(v(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),qM(n.baseUrl),!r)return;let s=await UM(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(q(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),q(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),q(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?q(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):q(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function ZM(t){let e=await iu(await ls(t),Lr(t)),r=wu(e);if(!r){let n=/\bdefineConduit\s*[<(]/.test(e);k(n?`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`:`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`)}return{...r,sourceCode:e}}async function Xn(t,e,r,n){try{return await be.access(t),"skipped"}catch{}return await be.mkdir(Lr(t),{recursive:!0}),await be.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await be.chmod(t,n),"wrote"}async function rT(t,e){if(oT(t)!==".gitignore")return Xn(t,e.content,e.executable,e.mode);let r=await be.readFile(t,"utf8").catch(()=>null);if(r===null)return Xn(t,e.content,e.executable,e.mode);let n=Jy(r);return n===null?"skipped":(await be.writeFile(t,n,"utf8"),"merged")}function eg(t){if(t!==void 0){if(t==="junit"||t==="json")return t;k(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function pl(t){process.exit(t)}function FM(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 HM(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 VM(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 nT(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function ig({includeInternal:t=!0}={}){let e=new Sg;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.24.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${hu()}
3751
+ `),e.hook("preAction",(d,m)=>{lb(e.opts(),m.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 d=>{let m=Dt(d.baseUrl);d.token||k(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
3752
+ ${hs} auth login --base-url ${m} --token tb_pat_\u2026`),rw(d.token)||k("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await BM(m,d.token,d.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 d=>ow({probe:d.probe})),r.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async d=>{let m=d??await MM("Pick the active instance:"),_=await Ki(m);if(!_){let T=await Rr();k(`no stored sign-in for ${Dt(m)}.`+(T.length?` Stored: ${T.map(x=>x.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${Dt(m)} --token tb_pat_\u2026\`.`)}v(`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 d=>{if(d.all){let T=await Rr();for(let x of T)await eu(x.baseUrl);v(`removed ${T.length} stored sign-in${T.length===1?"":"s"}.`);return}let m=await eu(d.baseUrl);m||k(d.baseUrl?`no stored sign-in for ${Dt(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let _=await Xt();v(`signed out of ${m}.`+(_?` 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 d=>{let{baseUrl:m,token:_}=await ne(d.baseUrl),T;try{T=await In({baseUrl:m,token:_,recordsOnly:d.recordsOnly})}catch(y){let S=y instanceof Error?y.message:String(y);if(!d.recordsOnly&&/openapi\.json failed \(401/.test(S)){q("types-gen: /v1/catalog/openapi.json needs a browser session \u2014 emitting record shapes only. The record shapes are the half apps generate against; for the OpenAPI half, run it from a signed-in browser session.");try{T=await In({baseUrl:m,token:_,recordsOnly:!0})}catch(R){k(`types generation failed: ${R instanceof Error?R.message:String(R)}`)}}else k(`types generation failed: ${S}`)}let x=ge(process.cwd(),d.out);await be.writeFile(x,T,"utf8"),v(`wrote ${x} (${T.split(`
3753
+ `).length} lines).`)}),pb(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 d=>{let{baseUrl:m,token:_}=await ne(d.baseUrl),T=new URLSearchParams;d.records&&T.set("records",d.records),d.query&&T.set("query",d.query);let x=T.toString(),y=await fetch(`${m}/v1/catalog/grounding${x?`?${x}`:""}`,{headers:{Authorization:`Bearer ${_}`,Accept:"application/json"}});y.ok||k(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${y.status}`);let R=((await y.json()).markdown??"").trim(),N=ge(process.cwd(),d.out),L=d.records?` records=${d.records}`:"",D=`<!-- GENERATED by \`turbobase project grounding\` against ${m}${L} \u2014 do not edit; re-run to refresh. -->
3747
3754
 
3748
3755
  `;await be.writeFile(N,D+(R?`${R}
3749
3756
  `:`(no grounding available yet)
3750
- `),"utf8"),v(`wrote ${N}${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 (${fs.join(" | ")}).`).option("--limit <n>","Cap how many findings to act on.",d=>Number.parseInt(d,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(d=>hb(d)),s.command("list").description("List the knowledge base\u2019s pages and whether each is actually readable. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only pages in this state.").action(d=>mb(d)),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((d,m)=>gb(d,m)),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((d,m)=>yb(d,m)),s.command("versions").description("List knowledge-base releases, newest first, marking the current one. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>bb(d)),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((d,m)=>wb(d,m)),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((d,m)=>vb(d,m)),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.",d=>Number.parseInt(d,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(d=>_b(d)),i.command("list").description("List the instance\u2019s agent skills and whether each is actually injected. Needs `skills:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only skills in this state.").action(d=>Cb(d)),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((d,m)=>Nb(d,m)),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((d,m)=>zb(d,m)),i.command("releases").description("List the skill releases, newest first \u2014 the rollback targets. Needs `skills:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>Lb(d)),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((d,m)=>jb(d,m)),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((d,m)=>Db(d,m));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 d=>{let m;try{m=fr("hook",{recordType:d.record,event:d.event,template:d.template,field:d.field,regex:d.regex,source:d.source,id:d.id})}catch(x){k(x instanceof Error?x.message:String(x))}let _=ge(process.cwd(),m.relativePath);await Xn(_,m.content)==="skipped"&&k(`refusing to overwrite existing file: ${_}`),v(`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 d=>{let m;try{m=fr("conduit",{recordType:d.record,source:d.source,to:d.to,toRecordType:d.toRecord,event:d.event,id:d.id})}catch(x){k(x instanceof Error?x.message:String(x))}let _=ge(process.cwd(),m.relativePath);await Xn(_,m.content)==="skipped"&&k(`refusing to overwrite existing file: ${_}`),v(`wrote ${_}`)}),a.command("process").description("Scaffold a process file under processes/ (an invoked multi-record sequence).").requiredOption("--record <type>","Record type the first step writes, e.g. purchaseOrder").option("--then <type>","Record type of a second step that waits for the first, e.g. vendorBill").option("--on-failure <mode>","stop | rollback","stop").option("--id <id>","Override the generated process id").action(async d=>{let m;try{m=fr("process",{recordType:d.record,then:d.then,onFailure:d.onFailure,id:d.id})}catch(x){k(x instanceof Error?x.message:String(x))}let _=ge(process.cwd(),m.relativePath);await Xn(_,m.content)==="skipped"&&k(`refusing to overwrite existing file: ${_}`),v(`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(d,m)=>{let _=Xm(m.reporter),T=await ls(ge(process.cwd(),d)),x=ge(process.cwd(),m.samples),y=await cs(x);y.length===0&&!_&&v(`no samples found under ${x} \u2014 add JSON fixtures to dry-run against.`);let S;try{S=await Qi(T,y.map(L=>L.fixture),{resolveDir:Lr(ge(process.cwd(),d))})}catch(L){k(`bundle failed: ${L instanceof Error?L.message:String(L)}`)}if(_){let L=DM(S);v(ta(L,_)),ul(L.cases.some(D=>D.status==="failed")?1:0)}let R=0;for(let L of S){let D=L.pass?g.green("PASS"):g.red("FAIL");L.pass||(R+=1);let H=L.error?` (error: ${L.error})`:L.observed!==L.expected?` (expected ${L.expected}, observed ${L.observed})`:L.rejection?` (rejected: ${L.rejection.code??"rejected"})`:"";v(` ${D} ${L.name}${H}`)}let N=`${S.length-R}/${S.length} sample(s) passed.`;v(`
3751
- ${R===0?g.green(N):g.yellow(N)}`),ul(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 project config (hooks/, conduits/, turbobase/) to this env (sandbox|prod).").option("--prune","Also REMOVE anything on the instance this project no longer declares. Off by default \u2014 see `ext plan` for what it would take.").action(async(d,m)=>{if(m.to){let S=await Qm(),{baseUrl:R,token:N}=await ne(m.baseUrl),L=new ee({baseUrl:R,token:N});try{let D=await ae(`applying bundle to ${m.to}`,()=>L.configApply(S,{prune:m.prune}));v(`applied bundle to ${m.to}: +${D.applied.add} ~${D.applied.change} -${D.applied.destroy}`+(D.backfillsQueued.length?` (${D.backfillsQueued.length} backfill(s) queued)`:""));let H=D.skippedDestroys??[];if(H.length>0){q(`${H.length} resource(s) exist on ${m.to} but are not declared by this project \u2014 NOT removed:`);for(let j of H)q(` ${j.kind} ${j.id}`);q("Add them to this repo (`turbobase ext export` pulls them down), or re-run with --prune to remove them.")}}catch(D){D instanceof le&&D.status===403&&k("apply forbidden (403) \u2014 the stored PAT is not for an admin."),k(`bundle apply failed: ${D instanceof Error?D.message:String(D)}`)}return}d||k("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:_,token:T}=await ne(m.baseUrl),x=await LM(ge(process.cwd(),d)),y=new ee({baseUrl:_,token:T});try{let S=await ae(`deploying ${tT(d)}`,()=>y.deploy(x));tt()?v(Vr("Deployed",[`${g.bold(S.id)} ${ho(S.status)} ${g.dim(S.outcome)}`])):v(`deployed ${S.id} \u2192 status=${S.status} (${S.outcome}).`)}catch(S){S instanceof le&&S.status===403&&k("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),k(`deploy failed: ${S instanceof Error?S.message:String(S)}`)}});let c=e.command("apps").description("Manage hosted apps served in your Turbobase app.");c.command("deploy").description("Build the app (if needed) and deploy it \u2014 cuts a new live version at /a/<slug>.").argument("<app>","App slug or id.").argument("[dir]","Source or built directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--no-build","Upload the directory as-is; it is already a built bundle.").option("--no-install","Skip `npm install` (assume deps are present).").option("--no-pull","Do not pull generated source even when the dir has no package.json.").option("--entry <file>","SPA entrypoint served for unknown routes.","index.html").option("--create","Create the app first if it does not exist yet.").option("--proposal <id>","Widget proposal this ship realizes (defaults to .turbobase/proposal.json).").option("--preview","Deploy to a preview URL instead of going live. Nothing about /a/<slug> changes until you `apps promote` it.").option("--label <text>","Label for the preview, so several open previews are tellable apart.").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.").option("--replace-label <text>","Re-deploy onto the open preview carrying this exact --label, opening one if there is none. The idempotent form for CI: one preview per pull request, updated in place. Implies --preview.").action(async(d,m,_)=>{let T=!!(_.preview||_.replace||_.replaceLabel);_.replace&&_.replaceLabel&&k("--replace and --replace-label both name the preview to re-deploy onto; pass one.");let x=ge(process.cwd(),m??".");await be.mkdir(x,{recursive:!0});let y=_.proposal??await $(x),{baseUrl:S,token:R}=await ne(_.baseUrl),N=new ee({baseUrl:S,token:R}),L=!1;try{L=(await N.appsList()).some($e=>$e.slug===d||$e.id===d)}catch($e){se($e,"extensions:deploy","deploy"),k(`could not reach ${S}: ${$e instanceof Error?$e.message:String($e)}`)}if(!L){_.create||k(`no app "${d}" on ${S} \u2014 create it with \`turbobase apps create ${d}\`, or pass --create.`);let $e=await ae(`creating app ${d}`,()=>p(S,R,{slug:d},{tolerateExisting:!0}));$e.existed||v(`created ${$e.slug??d}.`)}let D;if(_.replace)if(typeof _.replace=="string")D=_.replace;else{let{previews:$e}=await W(S,R,d);if($e.length===0&&k(`no open preview on ${d} to replace \u2014 drop --replace to open the first one, or name a handle from \`turbobase apps preview list\`.`),$e.length>1){for(let et of $e)v(` ${et.previewId} v${et.version}${et.label?` ${et.label}`:""} ${et.url}`);k(`${d} has ${$e.length} open previews \u2014 pass the one to replace, e.g. \`--replace ${$e[0].previewId}\`.`)}D=$e[0].previewId}let H;if(_.replaceLabel){let $e=_.replaceLabel,{previews:et}=await W(S,R,d),ur=et.filter(fl=>fl.label===$e);ur.length>0?(D=ur[0].previewId,ur.length>1&&q(`${ur.length} open previews carry the label "${$e}"; replacing the newest (${D}). Close the others with \`turbobase apps preview discard\`.`)):v(`no open preview labelled "${$e}" \u2014 opening one.`),H=$e}let j=$e=>be.stat(Ot(x,$e)).then(()=>!0).catch(()=>!1),Q=d,ve=x,Pe=_.build!==!1;if(Pe&&!await j("package.json"))if(await j("index.html"))v("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),Pe=!1;else if(_.pull===!1)k(`${x} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let $e=await ae(`pulling ${d}`,()=>w(S,R,d));Q=$e.slug??d,await f(x,$e.files,!0),v(`pulled generated source (rev ${$e.rev}).`)}let eo;if(Pe){let $e=qb();if(eo={buildId:$e,assetBase:Bb($e)},_.install!==!1&&!await j("node_modules")){v("installing dependencies\u2026");try{await P(["install"],x)}catch(et){k(`npm install failed: ${et instanceof Error?et.message:String(et)}`)}}v("building\u2026");try{await P(["run","build"],x,{TURBOBASE_ASSET_BASE:eo.assetBase})}catch(et){k(`build failed: ${et instanceof Error?et.message:String(et)}`)}await j("dist")||k(`no dist/ after build in ${x} \u2014 check the app's build script.`),ve=Ot(x,"dist")}T&&!eo&&k(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${Q}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let lt=await Ve(S,R,Q,ve,_.entry,y,eo,T?{label:_.label??H,replacePreviewId:D}:void 0);if(T){let $e=lt.previewUrl??"(no url returned)",et=lt.expiresAt?new Date(lt.expiresAt).toLocaleDateString():`${Zb} days`,ur=lt.replacedVersion==null?null:`replaced v${lt.replacedVersion} \u2014 same URL`;if(tt())v(Vr(ur?"Preview replaced":"Preview deployed",[`${g.bold(Q)} ${g.green(`v${lt.version??"?"}`)} ${g.dim("not live")}`,`${g.bold($e)}`,...ur?[g.dim(ur)]:[],g.dim(`expires ${et}`)]));else{let fl=ur?`; ${ur}`:"";v(`preview ${Q} v${lt.version??"?"} \u2192 ${$e} (expires ${et}; /a/${Q} unchanged${fl}).`)}v(`next: turbobase apps promote ${Q} ${lt.previewId??"<preview-id>"} # make it live`),v(` turbobase apps preview discard ${lt.previewId??"<preview-id>"}`);return}tt()?v(Vr("Deployed",[`${g.bold(Q)} ${g.green(`v${lt.version??"?"}`)} ${g.dim(lt.url??`/a/${Q}`)}`])):v(`deployed ${Q} \u2192 v${lt.version??"?"} (${lt.url??`/a/${Q}`}).`),Ye(lt),Gt(lt),await Dr(lt,x)}),c.command("plan").description("Preflight this app's manifest against the instance \u2014 table conflicts, guardrail-blocked writes, and declared roles. Writes nothing.").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 tables as `cli` or `app:<slug>`.").action(async(d,m)=>{let _=await BM(d??".");_||k(`no public/turbobase.json under ${ge(process.cwd(),d??".")}.`);let T=Array.isArray(_.manifest.tables)?_.manifest.tables:[],x=Array.isArray(_.manifest.writes)?_.manifest.writes:[],y=Array.isArray(_.manifest.roles)?_.manifest.roles:[],S=Array.isArray(_.manifest.labels)?_.manifest.labels:[];if(T.length===0&&x.length===0&&y.length===0&&S.length===0)return v(`${_.manifestPath} declares no tables, writes, roles or labels \u2014 nothing to plan.`);let{baseUrl:R,token:N}=await ne(m.baseUrl),L=new ee({baseUrl:R,token:N});if(T.length>0){let D;try{D=await ae("planning tables",()=>L.tablesPlan({claimedBy:m.as,tables:T}))}catch(H){se(H,"extensions:deploy","plan tables"),Ti(H)}v(`claiming as ${g.bold(D.claimedBy)}`);for(let H of D.tables)Si(H,{showClaimants:!0})}if(x.length>0||y.length>0||S.length>0){let D;try{D=await ae("checking declared writes, roles and labels",()=>L.appsPlan({writes:x,roles:y,labels:S}))}catch(H){se(H,"extensions:deploy","plan writes"),k(`plan writes failed: ${H instanceof Error?H.message:String(H)}`)}if(D.roles&&D.roles.verdicts.length>0){v(""),v(g.bold("roles"));let H=Math.max(...D.roles.verdicts.map(j=>j.name.length));for(let j of D.roles.verdicts){let Q=j.name.padEnd(H);if(j.action==="error")q(` ${g.bold("ERROR")} ${Q} \u2014 ${j.message??"cannot be created"}`);else if(j.action==="create"){let ve=j.addCapabilities?.length??0;v(` create ${Q} ${g.dim(`${ve} capabilit${ve===1?"y":"ies"}`)}`)}else if(j.action==="add_capabilities"){let ve=(j.addCapabilities??[]).map(Pe=>`+${Pe}`).join(", ");v(` add ${Q} ${g.dim(ve)}`)}else v(` ${g.dim("ok")} ${Q} ${g.dim("already up to date")}`)}D.roles.verdicts.some(j=>j.action!=="error")&&v(g.dim(" roles are created at deploy \u2014 a declared role has no holders until an admin assigns it in Admin \u2192 Users."))}if(D.labels&&D.labels.verdicts.length>0){v(""),v(g.bold("labels"));let H=Math.max(...D.labels.verdicts.map(j=>j.name.length));for(let j of D.labels.verdicts){let Q=j.name.padEnd(H);if(j.action==="create")v(` create ${Q} ${g.dim(j.color)}`);else{let ve=j.declaredColor?`${j.color} \u2014 declared ${j.declaredColor}, the instance's colour is kept`:j.color;v(` ${g.dim("ok")} ${Q} ${g.dim(ve)}`)}}v(g.dim(" labels are launcher navigation \u2014 a chip on the app card and a filter pill on /apps. They grant nothing."))}x.length>0&&v("");for(let H of D.verdicts){let j=`${H.source} ${H.recordType}.${H.op}`;H.allowed?H.heldForApproval?v(`${g.dim("HELD")} ${j} \u2014 allowed, but each write waits for operator approval.`):v(`${g.dim("ok")} ${j}`):q(`${g.bold("DENIED")} ${j}${H.rule?` \u2014 guardrail "${H.rule}"`:""} (${H.reason})`)}D.ok||(v(""),k(D.message??(D.roles&&!D.roles.ok?"one or more declared roles cannot be created.":"a guardrail refuses one or more declared writes \u2014 an admin must allow them, or the app must stop declaring them.")))}v(""),v(g.dim("nothing was applied \u2014 this is a preflight. `turbobase apps deploy` runs the same checks and enforces them."))}),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(d,m,_)=>{let{baseUrl:T,token:x}=await ne(_.baseUrl),y=await ae(`promoting ${m}`,()=>B(T,x,d,"promote",{previewId:m}));tt()?v(Vr("Promoted",[`${g.bold(d)} ${g.green(`v${y.version??"?"}`)} ${g.dim(y.url??`/a/${d}`)}`])):v(`promoted ${d} \u2192 v${y.version??"?"} is now live at ${y.url??`/a/${d}`}.`),Gt({labels:y.labels?{applied:!0,verdicts:y.labels}:null}),await Dr(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).").option("--json","Emit raw JSON instead of a line per preview.").action(async(d,m)=>{let{baseUrl:_,token:T}=await ne(m.baseUrl),x=await W(_,T,d);if(m.json)return v(JSON.stringify(x.previews,null,2));if(x.previews.length===0){v(`no open previews for ${d}.`);return}for(let y of x.previews){let S=y.label?` ${y.label}`:"",R=y.expiresAt?new Date(y.expiresAt).toLocaleDateString():"?";v(`v${y.version} ${y.previewId}${S} ${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(d,m,_)=>{let{baseUrl:T,token:x}=await ne(_.baseUrl);await ae(`discarding ${m}`,()=>B(T,x,d,"discard",{previewId:m})),v(`discarded ${m}.`)}),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(d,m)=>{let{baseUrl:_,token:T}=await ne(m.baseUrl),x=await ae(`creating ${d}`,()=>p(_,T,{slug:d,name:m.name,description:m.description})),y=x.slug??d;tt()?v(Vr("Created",[`${g.bold(y)} ${g.dim(x.url??`/a/${y}`)}`])):v(`created ${y} (${x.url??`/a/${y}`}).`),v(`next: turbobase apps push ${y} . # store the source`),v(` turbobase apps deploy ${y} # build + go live`)});let u=Vi(fetch);async function p(d,m,_,T={}){let x=`${d.replace(/\/+$/,"")}/v1/apps`,y;try{y=await u(x,{method:"POST",headers:{Authorization:`Bearer ${m}`,"content-type":"application/json"},body:JSON.stringify({slug:_.slug,name:_.name??_.slug,description:_.description})})}catch(S){k(`create request failed: ${S instanceof Error?S.message:String(S)}`)}if(y.status===401&&k("create unauthorized (401) \u2014 re-run `turbobase auth login`."),y.status===403&&k("create forbidden (403) \u2014 the PAT is not for an admin."),y.status===409){if(T.tolerateExisting)return{slug:_.slug,existed:!0};k(`an app with slug "${_.slug}" already exists.`)}return y.ok||k(`create failed: HTTP ${y.status} ${(await y.text().catch(()=>"")).slice(0,200)}`),await y.json().catch(()=>({}))}async function w(d,m,_){let T=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(_)}/pull`,x;try{x=await u(T,{headers:{Authorization:`Bearer ${m}`}})}catch(y){k(`pull request failed: ${y instanceof Error?y.message:String(y)}`)}return x.status===401&&k("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),x.status===403&&k("pull forbidden (403) \u2014 the PAT is not for an admin."),x.status===404&&k(`no generated source for "${_}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),x.ok||k(`pull failed: HTTP ${x.status} ${(await x.text().catch(()=>"")).slice(0,200)}`),await x.json()}async function f(d,m,_){let T=ge(d),x=0;for(let[y,S]of Object.entries(m)){let R=ge(T,y);R!==T&&!R.startsWith(T+rg)&&k(`refusing to write outside ${T}: ${y}`),_||await be.stat(R).then(()=>!0).catch(()=>!1)&&k(`${R} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await be.mkdir(Lr(R),{recursive:!0}),await be.writeFile(R,S,"utf8"),x+=1}return x}function h(d){let m=d.indexOf(","),_=d.startsWith("data:")?m>=0?d.slice(m+1):"":d;if(!_)return null;try{let T=Buffer.from(_,"base64");return T.length>0?new Uint8Array(T):null}catch{return null}}async function b(d,m,_){let T=ge(d),x=async(S,R)=>{let N=ge(T,S);N!==T&&!N.startsWith(T+rg)&&k(`refusing to write outside ${T}: ${S}`),_||await be.stat(N).then(()=>!0).catch(()=>!1)&&k(`${N} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await be.mkdir(Lr(N),{recursive:!0}),await be.writeFile(N,R)},y=`# ${m.title||"App change request"}
3757
+ `),"utf8"),v(`wrote ${N}${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 (${fs.join(" | ")}).`).option("--limit <n>","Cap how many findings to act on.",d=>Number.parseInt(d,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(d=>gb(d)),s.command("list").description("List the knowledge base\u2019s pages and whether each is actually readable. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only pages in this state.").action(d=>bb(d)),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((d,m)=>wb(d,m)),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((d,m)=>vb(d,m)),s.command("versions").description("List knowledge-base releases, newest first, marking the current one. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>_b(d)),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((d,m)=>xb(d,m)),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((d,m)=>kb(d,m)),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.",d=>Number.parseInt(d,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(d=>$b(d)),i.command("list").description("List the instance\u2019s agent skills and whether each is actually injected. Needs `skills:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only skills in this state.").action(d=>jb(d)),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((d,m)=>Lb(d,m)),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((d,m)=>Db(d,m)),i.command("releases").description("List the skill releases, newest first \u2014 the rollback targets. Needs `skills:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>Ub(d)),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((d,m)=>Mb(d,m)),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((d,m)=>qb(d,m));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 d=>{let m;try{m=fr("hook",{recordType:d.record,event:d.event,template:d.template,field:d.field,regex:d.regex,source:d.source,id:d.id})}catch(x){k(x instanceof Error?x.message:String(x))}let _=ge(process.cwd(),m.relativePath);await Xn(_,m.content)==="skipped"&&k(`refusing to overwrite existing file: ${_}`),v(`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 d=>{let m;try{m=fr("conduit",{recordType:d.record,source:d.source,to:d.to,toRecordType:d.toRecord,event:d.event,id:d.id})}catch(x){k(x instanceof Error?x.message:String(x))}let _=ge(process.cwd(),m.relativePath);await Xn(_,m.content)==="skipped"&&k(`refusing to overwrite existing file: ${_}`),v(`wrote ${_}`)}),a.command("process").description("Scaffold a process file under processes/ (an invoked multi-record sequence).").requiredOption("--record <type>","Record type the first step writes, e.g. purchaseOrder").option("--then <type>","Record type of a second step that waits for the first, e.g. vendorBill").option("--on-failure <mode>","stop | rollback","stop").option("--id <id>","Override the generated process id").action(async d=>{let m;try{m=fr("process",{recordType:d.record,then:d.then,onFailure:d.onFailure,id:d.id})}catch(x){k(x instanceof Error?x.message:String(x))}let _=ge(process.cwd(),m.relativePath);await Xn(_,m.content)==="skipped"&&k(`refusing to overwrite existing file: ${_}`),v(`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(d,m)=>{let _=eg(m.reporter),T=await ls(ge(process.cwd(),d)),x=ge(process.cwd(),m.samples),y=await cs(x);y.length===0&&!_&&v(`no samples found under ${x} \u2014 add JSON fixtures to dry-run against.`);let S;try{S=await ta(T,y.map(L=>L.fixture),{resolveDir:Lr(ge(process.cwd(),d))})}catch(L){k(`bundle failed: ${L instanceof Error?L.message:String(L)}`)}if(_){let L=FM(S);v(na(L,_)),pl(L.cases.some(D=>D.status==="failed")?1:0)}let R=0;for(let L of S){let D=L.pass?g.green("PASS"):g.red("FAIL");L.pass||(R+=1);let H=L.error?` (error: ${L.error})`:L.observed!==L.expected?` (expected ${L.expected}, observed ${L.observed})`:L.rejection?` (rejected: ${L.rejection.code??"rejected"})`:"";v(` ${D} ${L.name}${H}`)}let N=`${S.length-R}/${S.length} sample(s) passed.`;v(`
3758
+ ${R===0?g.green(N):g.yellow(N)}`),pl(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 project config (hooks/, conduits/, turbobase/) to this env (sandbox|prod).").option("--prune","Also REMOVE anything on the instance this project no longer declares. Off by default \u2014 see `ext plan` for what it would take.").action(async(d,m)=>{if(m.to){let S=await tg(),{baseUrl:R,token:N}=await ne(m.baseUrl),L=new ee({baseUrl:R,token:N});try{let D=await ae(`applying bundle to ${m.to}`,()=>L.configApply(S,{prune:m.prune}));v(`applied bundle to ${m.to}: +${D.applied.add} ~${D.applied.change} -${D.applied.destroy}`+(D.backfillsQueued.length?` (${D.backfillsQueued.length} backfill(s) queued)`:""));let H=D.skippedDestroys??[];if(H.length>0){q(`${H.length} resource(s) exist on ${m.to} but are not declared by this project \u2014 NOT removed:`);for(let j of H)q(` ${j.kind} ${j.id}`);q("Add them to this repo (`turbobase ext export` pulls them down), or re-run with --prune to remove them.")}}catch(D){D instanceof le&&D.status===403&&k("apply forbidden (403) \u2014 the stored PAT is not for an admin."),k(`bundle apply failed: ${D instanceof Error?D.message:String(D)}`)}return}d||k("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:_,token:T}=await ne(m.baseUrl),x=await ZM(ge(process.cwd(),d)),y=new ee({baseUrl:_,token:T});try{let S=await ae(`deploying ${oT(d)}`,()=>y.deploy(x));tt()?v(Vr("Deployed",[`${g.bold(S.id)} ${ho(S.status)} ${g.dim(S.outcome)}`])):v(`deployed ${S.id} \u2192 status=${S.status} (${S.outcome}).`)}catch(S){S instanceof le&&S.status===403&&k("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),k(`deploy failed: ${S instanceof Error?S.message:String(S)}`)}});let c=e.command("apps").description("Manage hosted apps served in your Turbobase app.");c.command("deploy").description("Build the app (if needed) and deploy it \u2014 cuts a new live version at /a/<slug>.").argument("<app>","App slug or id.").argument("[dir]","Source or built directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--no-build","Upload the directory as-is; it is already a built bundle.").option("--no-install","Skip `npm install` (assume deps are present).").option("--no-pull","Do not pull generated source even when the dir has no package.json.").option("--entry <file>","SPA entrypoint served for unknown routes.","index.html").option("--create","Create the app first if it does not exist yet.").option("--proposal <id>","Widget proposal this ship realizes (defaults to .turbobase/proposal.json).").option("--preview","Deploy to a preview URL instead of going live. Nothing about /a/<slug> changes until you `apps promote` it.").option("--label <text>","Label for the preview, so several open previews are tellable apart.").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.").option("--replace-label <text>","Re-deploy onto the open preview carrying this exact --label, opening one if there is none. The idempotent form for CI: one preview per pull request, updated in place. Implies --preview.").action(async(d,m,_)=>{let T=!!(_.preview||_.replace||_.replaceLabel);_.replace&&_.replaceLabel&&k("--replace and --replace-label both name the preview to re-deploy onto; pass one.");let x=ge(process.cwd(),m??".");await be.mkdir(x,{recursive:!0});let y=_.proposal??await $(x),{baseUrl:S,token:R}=await ne(_.baseUrl),N=new ee({baseUrl:S,token:R}),L=!1;try{L=(await N.appsList()).some($e=>$e.slug===d||$e.id===d)}catch($e){se($e,"extensions:deploy","deploy"),k(`could not reach ${S}: ${$e instanceof Error?$e.message:String($e)}`)}if(!L){_.create||k(`no app "${d}" on ${S} \u2014 create it with \`turbobase apps create ${d}\`, or pass --create.`);let $e=await ae(`creating app ${d}`,()=>p(S,R,{slug:d},{tolerateExisting:!0}));$e.existed||v(`created ${$e.slug??d}.`)}let D;if(_.replace)if(typeof _.replace=="string")D=_.replace;else{let{previews:$e}=await W(S,R,d);if($e.length===0&&k(`no open preview on ${d} to replace \u2014 drop --replace to open the first one, or name a handle from \`turbobase apps preview list\`.`),$e.length>1){for(let et of $e)v(` ${et.previewId} v${et.version}${et.label?` ${et.label}`:""} ${et.url}`);k(`${d} has ${$e.length} open previews \u2014 pass the one to replace, e.g. \`--replace ${$e[0].previewId}\`.`)}D=$e[0].previewId}let H;if(_.replaceLabel){let $e=_.replaceLabel,{previews:et}=await W(S,R,d),ur=et.filter(gl=>gl.label===$e);ur.length>0?(D=ur[0].previewId,ur.length>1&&q(`${ur.length} open previews carry the label "${$e}"; replacing the newest (${D}). Close the others with \`turbobase apps preview discard\`.`)):v(`no open preview labelled "${$e}" \u2014 opening one.`),H=$e}let j=$e=>be.stat(Ot(x,$e)).then(()=>!0).catch(()=>!1),Q=d,ve=x,Pe=_.build!==!1;if(Pe&&!await j("package.json"))if(await j("index.html"))v("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),Pe=!1;else if(_.pull===!1)k(`${x} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let $e=await ae(`pulling ${d}`,()=>w(S,R,d));Q=$e.slug??d,await f(x,$e.files,!0),v(`pulled generated source (rev ${$e.rev}).`)}let eo;if(Pe){let $e=Fb();if(eo={buildId:$e,assetBase:Hb($e)},_.install!==!1&&!await j("node_modules")){v("installing dependencies\u2026");try{await P(["install"],x)}catch(et){k(`npm install failed: ${et instanceof Error?et.message:String(et)}`)}}v("building\u2026");try{await P(["run","build"],x,{TURBOBASE_ASSET_BASE:eo.assetBase})}catch(et){k(`build failed: ${et instanceof Error?et.message:String(et)}`)}await j("dist")||k(`no dist/ after build in ${x} \u2014 check the app's build script.`),ve=Ot(x,"dist")}T&&!eo&&k(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${Q}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let lt=await Ve(S,R,Q,ve,_.entry,y,eo,T?{label:_.label??H,replacePreviewId:D}:void 0);if(T){let $e=lt.previewUrl??"(no url returned)",et=lt.expiresAt?new Date(lt.expiresAt).toLocaleDateString():`${Vb} days`,ur=lt.replacedVersion==null?null:`replaced v${lt.replacedVersion} \u2014 same URL`;if(tt())v(Vr(ur?"Preview replaced":"Preview deployed",[`${g.bold(Q)} ${g.green(`v${lt.version??"?"}`)} ${g.dim("not live")}`,`${g.bold($e)}`,...ur?[g.dim(ur)]:[],g.dim(`expires ${et}`)]));else{let gl=ur?`; ${ur}`:"";v(`preview ${Q} v${lt.version??"?"} \u2192 ${$e} (expires ${et}; /a/${Q} unchanged${gl}).`)}v(`next: turbobase apps promote ${Q} ${lt.previewId??"<preview-id>"} # make it live`),v(` turbobase apps preview discard ${lt.previewId??"<preview-id>"}`);return}tt()?v(Vr("Deployed",[`${g.bold(Q)} ${g.green(`v${lt.version??"?"}`)} ${g.dim(lt.url??`/a/${Q}`)}`])):v(`deployed ${Q} \u2192 v${lt.version??"?"} (${lt.url??`/a/${Q}`}).`),Ye(lt),Gt(lt),await Dr(lt,x)}),c.command("plan").description("Preflight this app's manifest against the instance \u2014 table conflicts, guardrail-blocked writes, and declared roles. Writes nothing.").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 tables as `cli` or `app:<slug>`.").action(async(d,m)=>{let _=await WM(d??".");_||k(`no public/turbobase.json under ${ge(process.cwd(),d??".")}.`);let T=Array.isArray(_.manifest.tables)?_.manifest.tables:[],x=Array.isArray(_.manifest.writes)?_.manifest.writes:[],y=Array.isArray(_.manifest.roles)?_.manifest.roles:[],S=Array.isArray(_.manifest.labels)?_.manifest.labels:[];if(T.length===0&&x.length===0&&y.length===0&&S.length===0)return v(`${_.manifestPath} declares no tables, writes, roles or labels \u2014 nothing to plan.`);let{baseUrl:R,token:N}=await ne(m.baseUrl),L=new ee({baseUrl:R,token:N});if(T.length>0){let D;try{D=await ae("planning tables",()=>L.tablesPlan({claimedBy:m.as,tables:T}))}catch(H){se(H,"extensions:deploy","plan tables"),Ti(H)}v(`claiming as ${g.bold(D.claimedBy)}`);for(let H of D.tables)Si(H,{showClaimants:!0})}if(x.length>0||y.length>0||S.length>0){let D;try{D=await ae("checking declared writes, roles and labels",()=>L.appsPlan({writes:x,roles:y,labels:S}))}catch(H){se(H,"extensions:deploy","plan writes"),k(`plan writes failed: ${H instanceof Error?H.message:String(H)}`)}if(D.roles&&D.roles.verdicts.length>0){v(""),v(g.bold("roles"));let H=Math.max(...D.roles.verdicts.map(j=>j.name.length));for(let j of D.roles.verdicts){let Q=j.name.padEnd(H);if(j.action==="error")q(` ${g.bold("ERROR")} ${Q} \u2014 ${j.message??"cannot be created"}`);else if(j.action==="create"){let ve=j.addCapabilities?.length??0;v(` create ${Q} ${g.dim(`${ve} capabilit${ve===1?"y":"ies"}`)}`)}else if(j.action==="add_capabilities"){let ve=(j.addCapabilities??[]).map(Pe=>`+${Pe}`).join(", ");v(` add ${Q} ${g.dim(ve)}`)}else v(` ${g.dim("ok")} ${Q} ${g.dim("already up to date")}`)}D.roles.verdicts.some(j=>j.action!=="error")&&v(g.dim(" roles are created at deploy \u2014 a declared role has no holders until an admin assigns it in Admin \u2192 Users."))}if(D.labels&&D.labels.verdicts.length>0){v(""),v(g.bold("labels"));let H=Math.max(...D.labels.verdicts.map(j=>j.name.length));for(let j of D.labels.verdicts){let Q=j.name.padEnd(H);if(j.action==="create")v(` create ${Q} ${g.dim(j.color)}`);else{let ve=j.declaredColor?`${j.color} \u2014 declared ${j.declaredColor}, the instance's colour is kept`:j.color;v(` ${g.dim("ok")} ${Q} ${g.dim(ve)}`)}}v(g.dim(" labels are launcher navigation \u2014 a chip on the app card and a filter pill on /apps. They grant nothing."))}x.length>0&&v("");for(let H of D.verdicts){let j=`${H.source} ${H.recordType}.${H.op}`;H.allowed?H.heldForApproval?v(`${g.dim("HELD")} ${j} \u2014 allowed, but each write waits for operator approval.`):v(`${g.dim("ok")} ${j}`):q(`${g.bold("DENIED")} ${j}${H.rule?` \u2014 guardrail "${H.rule}"`:""} (${H.reason})`)}D.ok||(v(""),k(D.message??(D.roles&&!D.roles.ok?"one or more declared roles cannot be created.":"a guardrail refuses one or more declared writes \u2014 an admin must allow them, or the app must stop declaring them.")))}v(""),v(g.dim("nothing was applied \u2014 this is a preflight. `turbobase apps deploy` runs the same checks and enforces them."))}),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(d,m,_)=>{let{baseUrl:T,token:x}=await ne(_.baseUrl),y=await ae(`promoting ${m}`,()=>B(T,x,d,"promote",{previewId:m}));tt()?v(Vr("Promoted",[`${g.bold(d)} ${g.green(`v${y.version??"?"}`)} ${g.dim(y.url??`/a/${d}`)}`])):v(`promoted ${d} \u2192 v${y.version??"?"} is now live at ${y.url??`/a/${d}`}.`),Gt({labels:y.labels?{applied:!0,verdicts:y.labels}:null}),await Dr(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).").option("--json","Emit raw JSON instead of a line per preview.").action(async(d,m)=>{let{baseUrl:_,token:T}=await ne(m.baseUrl),x=await W(_,T,d);if(m.json)return v(JSON.stringify(x.previews,null,2));if(x.previews.length===0){v(`no open previews for ${d}.`);return}for(let y of x.previews){let S=y.label?` ${y.label}`:"",R=y.expiresAt?new Date(y.expiresAt).toLocaleDateString():"?";v(`v${y.version} ${y.previewId}${S} ${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(d,m,_)=>{let{baseUrl:T,token:x}=await ne(_.baseUrl);await ae(`discarding ${m}`,()=>B(T,x,d,"discard",{previewId:m})),v(`discarded ${m}.`)}),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(d,m)=>{let{baseUrl:_,token:T}=await ne(m.baseUrl),x=await ae(`creating ${d}`,()=>p(_,T,{slug:d,name:m.name,description:m.description})),y=x.slug??d;tt()?v(Vr("Created",[`${g.bold(y)} ${g.dim(x.url??`/a/${y}`)}`])):v(`created ${y} (${x.url??`/a/${y}`}).`),v(`next: turbobase apps push ${y} . # store the source`),v(` turbobase apps deploy ${y} # build + go live`)});let u=Wi(fetch);async function p(d,m,_,T={}){let x=`${d.replace(/\/+$/,"")}/v1/apps`,y;try{y=await u(x,{method:"POST",headers:{Authorization:`Bearer ${m}`,"content-type":"application/json"},body:JSON.stringify({slug:_.slug,name:_.name??_.slug,description:_.description})})}catch(S){k(`create request failed: ${S instanceof Error?S.message:String(S)}`)}if(y.status===401&&k("create unauthorized (401) \u2014 re-run `turbobase auth login`."),y.status===403&&k("create forbidden (403) \u2014 the PAT is not for an admin."),y.status===409){if(T.tolerateExisting)return{slug:_.slug,existed:!0};k(`an app with slug "${_.slug}" already exists.`)}return y.ok||k(`create failed: HTTP ${y.status} ${(await y.text().catch(()=>"")).slice(0,200)}`),await y.json().catch(()=>({}))}async function w(d,m,_){let T=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(_)}/pull`,x;try{x=await u(T,{headers:{Authorization:`Bearer ${m}`}})}catch(y){k(`pull request failed: ${y instanceof Error?y.message:String(y)}`)}return x.status===401&&k("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),x.status===403&&k("pull forbidden (403) \u2014 the PAT is not for an admin."),x.status===404&&k(`no generated source for "${_}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),x.ok||k(`pull failed: HTTP ${x.status} ${(await x.text().catch(()=>"")).slice(0,200)}`),await x.json()}async function f(d,m,_){let T=ge(d),x=0;for(let[y,S]of Object.entries(m)){let R=ge(T,y);R!==T&&!R.startsWith(T+og)&&k(`refusing to write outside ${T}: ${y}`),_||await be.stat(R).then(()=>!0).catch(()=>!1)&&k(`${R} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await be.mkdir(Lr(R),{recursive:!0}),await be.writeFile(R,S,"utf8"),x+=1}return x}function h(d){let m=d.indexOf(","),_=d.startsWith("data:")?m>=0?d.slice(m+1):"":d;if(!_)return null;try{let T=Buffer.from(_,"base64");return T.length>0?new Uint8Array(T):null}catch{return null}}async function b(d,m,_){let T=ge(d),x=async(S,R)=>{let N=ge(T,S);N!==T&&!N.startsWith(T+og)&&k(`refusing to write outside ${T}: ${S}`),_||await be.stat(N).then(()=>!0).catch(()=>!1)&&k(`${N} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await be.mkdir(Lr(N),{recursive:!0}),await be.writeFile(N,R)},y=`# ${m.title||"App change request"}
3752
3759
 
3753
3760
  > Widget proposal \`${m.proposalId}\` \u2014 build this change, then ship it with
3754
3761
  > \`turbobase apps deploy ${m.appSlug}\`. The deploy stamps this proposal complete.
@@ -3759,21 +3766,21 @@ ${m.bodyMarkdown||"_No description provided._"}
3759
3766
 
3760
3767
  `+(m.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.
3761
3768
  `);if(await x("PROPOSAL.md",y),m.screenshot){let S=h(m.screenshot);S&&await x("proposal-screenshot.png",S)}await x(Ot(".turbobase","proposal.json"),`${JSON.stringify({proposalId:m.proposalId},null,2)}
3762
- `)}async function $(d){try{let m=await be.readFile(Ot(d,".turbobase","proposal.json"),"utf8"),_=JSON.parse(m);return typeof _.proposalId=="string"&&_.proposalId?_.proposalId:void 0}catch{return}}async function E(d,m,_,T,x,y){let S=new ee({baseUrl:d,token:m});try{return await S.appsPush(_,T,{note:x,proposalId:y})}catch(R){if(R instanceof le){let N=R.body;if(R.status===401&&k("push unauthorized (401) \u2014 re-run `turbobase auth login`."),R.status===403&&N?.error==="admin_required"&&k("push forbidden (403) \u2014 the PAT is not for an admin."),R.status===403&&se(R,"extensions:deploy","push app source"),R.status===404&&k(`no app "${_}" on this instance \u2014 create it with \`turbobase apps create ${_}\`.`),R.status===413&&(N?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&k("push rejected: the request body exceeded the instance limit."),k(`push rejected: ${N?.error??"too large"} (limit ${N?.limit??"?"}).`)),R.status===400){let L=N?.path?` in ${N.path}`:"",D=N?.reason?` (${N.reason})`:"";k(`push rejected: ${N?.error??"bad request"}${D}${L}.`)}}k(`push failed: ${R instanceof Error?R.message:String(R)}`)}}function P(d,m,_){return new Promise((T,x)=>{let y=ng("npm",d,{cwd:m,stdio:"inherit",..._?{env:{...process.env,..._}}:{}});y.on("error",x),y.on("exit",S=>S===0?T():x(new Error(`npm ${d.join(" ")} exited ${S??"?"}`)))})}async function z(d,m,_,T){let x=`${d.replace(/\/+$/,"")}${_}`,y;try{y=await u(x,{method:T.method,headers:{Authorization:`Bearer ${m}`,...T.body?{"content-type":"application/json"}:{}},...T.body?{body:JSON.stringify(T.body)}:{}})}catch(S){k(`request failed: ${S instanceof Error?S.message:String(S)}`)}if(y.status===401&&k("unauthorized (401) \u2014 re-run `turbobase auth login`."),y.status===403&&k("forbidden (403) \u2014 the PAT is not for an admin."),!y.ok){let S=await y.text().catch(()=>""),R=S.slice(0,300);try{let N=JSON.parse(S);R=N.message??N.error??R}catch{}k(`failed: HTTP ${y.status} ${R}`)}return await y.json().catch(()=>({}))}async function B(d,m,_,T,x){return await z(d,m,`/v1/apps/${encodeURIComponent(_)}/preview/${T}`,{method:"POST",body:x})}async function W(d,m,_){return{previews:(await z(d,m,`/v1/apps/${encodeURIComponent(_)}/previews`,{method:"GET"})).previews??[]}}async function Ve(d,m,_,T,x,y,S,R){let N;try{N=await ae(`zipping ${T}`,()=>Py(T))}catch(j){k(`could not zip ${T}: ${j instanceof Error?j.message:String(j)}`)}N.fileCount===0&&k(`${T} is empty \u2014 the build produced nothing.`),N.buffer.byteLength>Tu&&k(`${T} zips to ${eT(N.buffer.byteLength)} \u2014 over the ${eT(Tu)} deploy limit. Check the build output for node_modules, source maps or media that should not ship.`);let L={Authorization:`Bearer ${m}`,"Content-Type":"application/zip"};x&&(L["x-app-entry"]=x),y&&(L["x-proposal-id"]=y),S&&(L["x-app-build-id"]=S.buildId,L["x-app-asset-base"]=S.assetBase),R&&(L["x-app-channel"]="preview",R.label&&(L["x-app-preview-label"]=encodeURIComponent(R.label)),R.replacePreviewId&&(L["x-app-preview-replace"]=R.replacePreviewId));let D=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(_)}/deploy`,H;try{H=await ae(`deploying ${_} (${N.fileCount} file${N.fileCount===1?"":"s"})`,()=>u(D,{method:"POST",headers:L,body:new Uint8Array(N.buffer)}))}catch(j){k(`deploy request failed: ${j instanceof Error?j.message:String(j)}`)}if(H.status===401&&k("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),H.status===403&&k("deploy forbidden (403) \u2014 the PAT is not for an admin."),H.status===404){let j=await H.text().catch(()=>""),Q={};try{Q=JSON.parse(j)}catch{}Q.error==="no_preview"&&k(`${Q.message??`no open preview to replace on ${_}`} \u2014 list them with \`turbobase apps preview list ${_}\`.`),k(`no app "${_}" on ${d} \u2014 create it with \`turbobase apps create ${_}\`.`)}if(!H.ok){let j=await H.text().catch(()=>""),Q=j.slice(0,300);try{let ve=JSON.parse(j);Q=ve.message??ve.error??Q}catch{}k(`deploy failed: HTTP ${H.status} ${Q}`)}return await H.json().catch(()=>({}))}function Ye(d){let m=d.roles;if(!m||m.verdicts.length===0)return;let _=m.verdicts.filter(x=>x.action!=="noop");if(_.length===0)return;v(""),v(g.bold(m.applied?"roles":"roles (preview \u2014 not applied)"));let T=Math.max(..._.map(x=>x.name.length));for(let x of _){let y=x.name.padEnd(T);if(x.action==="create"){let S=x.addCapabilities?.length??0;v(` created ${y} ${g.dim(`${S} capabilit${S===1?"y":"ies"}`)}`)}else if(x.action==="add_capabilities"){let S=(x.addCapabilities??[]).map(N=>`+${N}`).join(", "),R=x.holdersRestamped?g.dim(` (${x.holdersRestamped} holder${x.holdersRestamped===1?"":"s"} re-stamped)`):"";v(` updated ${y} ${g.dim(S)}${R}`)}}v(g.dim(m.applied?" assign these in Admin \u2192 Users \u2014 a declared role has no holders until you do.":" nothing was created \u2014 promoting this preview applies them."))}function Gt(d){let m=d.labels;if(!m||m.verdicts.length===0)return;let _=m.verdicts.filter(x=>x.action!=="noop");if(_.length===0)return;v(""),v(g.bold(m.applied?"labels":"labels (preview \u2014 not applied)"));let T=Math.max(..._.map(x=>x.name.length));for(let x of _){let y=x.name.padEnd(T);if(x.action==="detach")v(` removed ${y} ${g.dim("no longer declared in the manifest")}`);else if(x.action==="create")v(` created ${y} ${g.dim(x.color)}`);else{let S=x.declaredColor?`${x.color} \u2014 declared ${x.declaredColor}, the instance's colour is kept`:x.color;v(` added ${y} ${g.dim(S)}`)}}v(g.dim(m.applied?" labels are launcher navigation only \u2014 they change nothing about who can open this app.":" nothing was changed \u2014 promoting this preview applies them."))}async function Dr(d,m){let _=By(d,{localDocsModifiedAt:await pn(m)});_&&v(_.level==="warn"?g.yellow(_.message):g.dim(_.message))}async function pn(d){if(!d)return null;let m=null;for(let _ of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let T=await be.stat(Ot(d,_));(m===null||T.mtimeMs>m)&&(m=T.mtimeMs)}catch{}return m===null?null:new Date(m)}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(d,m,_)=>{let{baseUrl:T,token:x}=await ne(_.baseUrl);if(_.proposal){let N=new ee({baseUrl:T,token:x}),L;try{L=await ae(`fetching proposal ${_.proposal}`,()=>N.appPullContext(_.proposal))}catch(ve){se(ve,"extensions:deploy","pull proposal"),ve instanceof le&&ve.status===404&&k(`no widget proposal "${_.proposal}" on ${T}.`),k(`could not fetch proposal ${_.proposal}: ${ve instanceof Error?ve.message:String(ve)}`)}let D=await ae(`pulling ${L.appSlug}`,()=>w(T,x,L.appSlug)),H=m??d,j=ge(process.cwd(),H??L.appSlug);await be.mkdir(j,{recursive:!0});let Q=await f(j,D.files,!!_.force);await b(j,L,!!_.force),v(`pulled ${Q} file${Q===1?"":"s"} \u2192 ${j} (rev ${D.rev}), linked to proposal ${L.proposalId}.`),v(`next: cd ${dl(process.cwd(),j)||"."} && turbobase apps deploy ${L.appSlug}`);return}d||k("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let y=await ae(`pulling ${d}`,()=>w(T,x,d)),S=ge(process.cwd(),m??y.slug??d);await be.mkdir(S,{recursive:!0});let R=await f(S,y.files,!!_.force);v(`pulled ${R} file${R===1?"":"s"} \u2192 ${S} (rev ${y.rev}).`),v(`next: cd ${dl(process.cwd(),S)||"."} && 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(d,m,_)=>{let T=ge(process.cwd(),m??d),x=await Xt(_.baseUrl).catch(()=>null),{scaffoldAppFiles:y,starterApp:S}=await Promise.resolve().then(()=>(xw(),_w)),R=_.title??d,N=y({slug:d,title:R,appTsx:S(R),instanceOrigin:x?.baseUrl});await be.mkdir(T,{recursive:!0});let L=await f(T,N,!!_.force);if(v(`scaffolded ${L} file${L===1?"":"s"} \u2192 ${T}`),_.claude!==!1){let H=fu({baseUrl:x?.baseUrl,token:x?.token,appSlug:d}),j=0;for(let Q of H){let ve=await QS(Ot(T,Q.path),Q);(ve==="wrote"||ve==="merged")&&(j+=1)}v(`wired Claude Code: ${j} file${j===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),x||q("not signed in \u2014 .mcp.json and the dev proxy carry placeholders. Run `turbobase auth login`, then `turbobase apps init` again (existing files are kept).")}let D=dl(process.cwd(),T)||".";v(`next: cd ${D} && npm install && npm run dev`),v(` turbobase apps create ${d}`),v(` turbobase apps push ${d} .`),v(` turbobase apps deploy ${d} .`)}),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 d=>{let{baseUrl:m,token:_}=await ne(d.baseUrl),T=new ee({baseUrl:m,token:_}),x;try{x=await T.appsList()}catch(y){se(y,"extensions:deploy","list apps"),k(`list apps failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return v(JSON.stringify(x,null,2));if(x.length===0)return v("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");v(Qt(x.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(d,m,_)=>{let T=ge(process.cwd(),m??".");await be.stat(T).then(Pe=>Pe.isDirectory()).catch(()=>!1)||k(`${T} is not a directory.`);let{baseUrl:y,token:S}=await ne(_.baseUrl),R=_.proposal??await $(T),{files:N,skipped:L,secrets:D,unstorable:H}=await Ub(T),j=Object.keys(N).length;if(j===0&&k(`no source files found under ${T} (build output and node_modules are skipped).`),H.length>0){for(let Pe of H)q(`${Pe} contains a NUL byte (U+0000), which cannot be stored.`);k(`push aborted: ${H.length} ${H.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let Pe of L)q(g.dim(`skipped binary file ${Pe}`));for(let Pe of D)q(g.dim(`skipped ${Pe} (holds credentials \u2014 never pushed)`));let Q=await ae(`pushing ${j} file${j===1?"":"s"}`,()=>E(y,S,d,N,_.note,R));v(`pushed ${Q.files} file${Q.files===1?"":"s"} \u2192 ${Q.slug} rev ${Q.rev} (source only, nothing deployed).`);let ve=await ms(new ee({baseUrl:y,token:S}),Q.slug);ve&&ve.entriesAdded>0&&v(`${ve.entriesAdded} new finding(s) queued \u2014 run \`turbobase skills push\` / \`turbobase kb push\` to act on them.`),v(`next: turbobase apps deploy ${Q.slug}`)}),o.command("plan").description("Diff this project (hooks/, conduits/, turbobase/) 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 d=>{let m=await Qm(),{baseUrl:_,token:T}=await ne(d.baseUrl),x=new ee({baseUrl:_,token:T}),y;try{y=await ae(`planning against ${d.to??_}`,()=>x.configPlan(m))}catch(S){k(`plan failed: ${S instanceof Error?S.message:String(S)}`)}FM(y,d.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).").option("--prune","Also REMOVE anything on the target this project no longer declares. Off by default.").action(async d=>{let m=await Qm(),{baseUrl:_,token:T}=await ne(d.baseUrl),x=m.tenant??HM(_),y=Xy(d.confirm,x);y.ok||k(`promote refused (fail-closed): ${y.reason}`);let S=new ee({baseUrl:_,token:T});try{let R=await ae(`promoting ${d.from} \u2192 ${d.to} (${x})`,()=>S.configApply(m,{prune:d.prune}));if(tt()){let L=[`${g.bold(`${d.from} \u2192 ${d.to}`)} ${g.dim(x??"")}`,`${Hr.add(String(R.applied.add))} ${Hr.change(String(R.applied.change))} ${Hr.destroy(String(R.applied.destroy))}`];R.backfillsQueued.length&&L.push(g.dim(`${R.backfillsQueued.length} backfill(s) queued`)),v(Vr("Promoted",L))}else v(`promoted ${d.from} \u2192 ${d.to} (${x}): +${R.applied.add} ~${R.applied.change} -${R.applied.destroy}`+(R.backfillsQueued.length?` (${R.backfillsQueued.length} backfill(s) queued)`:""));let N=R.skippedDestroys??[];if(N.length>0){q(`${N.length} resource(s) on ${d.to} are not declared by this project \u2014 NOT removed:`);for(let L of N)q(` ${L.kind} ${L.id}`);q("Re-run with --prune to remove them, or add them to this repo.")}}catch(R){R instanceof le&&R.status===403&&k("promote forbidden (403) \u2014 the stored PAT is not for an admin."),k(`promote failed: ${R instanceof Error?R.message:String(R)}`)}}),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(d,m)=>{let _=Xm(m.reporter),T=ge(process.cwd(),d),x=await ls(T),y=Iy(x);_?v(ta(MM(d,y),_)):v(Oy(d,y,{warn:g.yellow,ok:g.green,dim:g.dim})),m.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(d,m)=>{let _=Xm(m.reporter),T=await ky(ge(process.cwd(),d));if(m.against){m.against!=="sandbox"&&k(`unknown --against target '${m.against}' (only 'sandbox' is supported).`);try{await _y(au(T))}catch(S){k(S instanceof Error?S.message:String(S))}return}m.fixture||k("replay needs a --fixture <file> (offline) or --against sandbox (online).");let x;try{x=await xy(ge(process.cwd(),m.fixture))}catch(S){k(`could not read fixture ${m.fixture}: ${S instanceof Error?S.message:String(S)}`)}let y=await vy(T,x,m.fixture,{resolveDir:Lr(ge(process.cwd(),d))});if(_){let S=UM(y);v(ta(S,_)),ul(S.cases.some(R=>R.status==="failed")?1:0)}v($y(y,!!m.trace)),ul(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 d=>{let{baseUrl:m,token:_}=await ne(d.baseUrl),T=new ee({baseUrl:m,token:_});try{await My(T,{status:d.status,retry:d.retry,limit:d.limit?Number(d.limit):void 0,sink:v})}catch(x){x instanceof le&&x.status===403&&k("forbidden (403) \u2014 binding --retry requires an admin PAT."),x instanceof le&&x.status===409&&k("binding is not retryable (only divergent/blocked bindings can be retried)."),k(`ext binding failed: ${x instanceof Error?x.message:String(x)}`)}});let Mr=o.command("proposals").description("Review the hook proposals waiting on a decision \u2014 list, promote, retract, reject.");Mr.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 d=>{await Rb(d)}),Mr.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(d,m)=>{await Pb(d??[],m)}),Mr.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(d,m)=>{await Ab(d,m)}),Mr.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(d,m)=>{await Ib(d,m)}),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(d,m)=>{let _=d.lastIndexOf("@"),T=_>0?d.slice(0,_):d,x=_>0?d.slice(_+1):void 0,y=ru();y||k(`marketplace not configured \u2014 set ${lo} and ${Ki}.
3763
- Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let S=nu(y.registryUrl);S&&k(S);let{baseUrl:R,token:N}=await ne(m.baseUrl),L=new is(y),D;try{D=await ae(`fetching ${d}`,()=>L.fetchBundle(T,x))}catch(Pe){k(`marketplace fetch failed for ${d}: ${Pe instanceof Error?Pe.message:String(Pe)}`)}let H=Mi(D.manifest),j=null;if(H.length>0){if(!m.connection){let Pe=H.map(eo=>eo.source_system).join(", ");k(`${D.name}@${D.version} declares a connection input (source: ${Pe}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}j=m.connection}let Q=qM(D.bundle,D.name,D.kind),ve=new ee({baseUrl:R,token:N});try{let Pe=await ae(`installing ${D.name}@${D.version}`,()=>ve.deploy({...Q,provenance:"marketplace",...j?{connectionId:j}:{}}));v(`installed ${D.name}@${D.version} \u2192 ${Pe.id} (status=${Pe.status}, ${Pe.outcome})`+(j?` bound to connection ${j}.`:"."))}catch(Pe){Pe instanceof le&&Pe.status===403&&k("install forbidden (403) \u2014 the stored PAT is not for an admin."),k(`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(d,m)=>{let _=ru();_||k(`marketplace not configured \u2014 set ${lo} and ${Ki}.
3764
- Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let T=nu(_.registryUrl);T&&k(T);let x=ge(process.cwd(),d),y=await ls(x),S=/\bdefineConduit\s*[<(]/.test(y)?"conduit":"hook",R={};if(m.manifest){let D=ge(process.cwd(),m.manifest),H;try{H=await be.readFile(D,"utf8")}catch{k(`manifest not found at ${m.manifest}.`)}let j;try{j=JSON.parse(H)}catch{k(`manifest is not valid JSON: ${m.manifest}.`)}(typeof j!="object"||j===null||Array.isArray(j))&&k("manifest must be a JSON object."),R=j}try{Ll(R,y)}catch(D){D instanceof Fr&&k(D.message),k(`manifest validation failed: ${D instanceof Error?D.message:String(D)}`)}let N=new is(_);try{await ae(`publishing ${m.name}@${m.pkgVersion}`,()=>N.publish({name:m.name,version:m.pkgVersion,kind:S,bundle:y,manifest:R}))}catch(D){D instanceof le&&D.status===403&&k("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),D instanceof le&&D.status===409&&k(`version already published \u2014 ${m.name}@${m.pkgVersion} exists. Bump the version.`),k(`publish failed: ${D instanceof Error?D.message:String(D)}`)}let L=Mi(R);v(`published ${m.name}@${m.pkgVersion} (kind=${S}) to the marketplace.`),L.length>0&&v(` declares ${L.length} connection input(s): ${L.map(D=>D.source_system).join(", ")} \u2014 bound at install.`)}),n.command("init").description("Scaffold a Claude-Code extension project in the current dir.").option("--base-url <url>","Instance to wire .mcp.json to (defaults to the active instance).").action(async d=>{let m=await Xt(d.baseUrl).catch(()=>null),_=fu({baseUrl:m?.baseUrl,token:m?.token}),T=0,x=0,y=0;for(let S of _){let R=ge(process.cwd(),S.path),N=await QS(R,S);N==="wrote"?(T+=1,v(` wrote ${S.path}`)):N==="merged"?(y+=1,v(` merged ${S.path} (added the .mcp.json rule)`)):(x+=1,v(` skipped ${S.path} (exists)`))}v(`
3765
- project init: ${T} written, ${y} merged, ${x} skipped.`)}),n.command("ci").description(`Write the reusable release-deploy GitHub Action to ${hu} (non-destructive).`).action(async()=>{let d=Zy(),m=0,_=0;for(let T of d){let x=ge(process.cwd(),T.path);await Xn(x,T.content,T.executable)==="wrote"?(m+=1,v(` wrote ${T.path}`)):(_+=1,v(` skipped ${T.path} (exists)`))}v(`
3769
+ `)}async function $(d){try{let m=await be.readFile(Ot(d,".turbobase","proposal.json"),"utf8"),_=JSON.parse(m);return typeof _.proposalId=="string"&&_.proposalId?_.proposalId:void 0}catch{return}}async function E(d,m,_,T,x,y){let S=new ee({baseUrl:d,token:m});try{return await S.appsPush(_,T,{note:x,proposalId:y})}catch(R){if(R instanceof le){let N=R.body;if(R.status===401&&k("push unauthorized (401) \u2014 re-run `turbobase auth login`."),R.status===403&&N?.error==="admin_required"&&k("push forbidden (403) \u2014 the PAT is not for an admin."),R.status===403&&se(R,"extensions:deploy","push app source"),R.status===404&&k(`no app "${_}" on this instance \u2014 create it with \`turbobase apps create ${_}\`.`),R.status===413&&(N?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&k("push rejected: the request body exceeded the instance limit."),k(`push rejected: ${N?.error??"too large"} (limit ${N?.limit??"?"}).`)),R.status===400){let L=N?.path?` in ${N.path}`:"",D=N?.reason?` (${N.reason})`:"";k(`push rejected: ${N?.error??"bad request"}${D}${L}.`)}}k(`push failed: ${R instanceof Error?R.message:String(R)}`)}}function P(d,m,_){return new Promise((T,x)=>{let y=sg("npm",d,{cwd:m,stdio:"inherit",..._?{env:{...process.env,..._}}:{}});y.on("error",x),y.on("exit",S=>S===0?T():x(new Error(`npm ${d.join(" ")} exited ${S??"?"}`)))})}async function z(d,m,_,T){let x=`${d.replace(/\/+$/,"")}${_}`,y;try{y=await u(x,{method:T.method,headers:{Authorization:`Bearer ${m}`,...T.body?{"content-type":"application/json"}:{}},...T.body?{body:JSON.stringify(T.body)}:{}})}catch(S){k(`request failed: ${S instanceof Error?S.message:String(S)}`)}if(y.status===401&&k("unauthorized (401) \u2014 re-run `turbobase auth login`."),y.status===403&&k("forbidden (403) \u2014 the PAT is not for an admin."),!y.ok){let S=await y.text().catch(()=>""),R=S.slice(0,300);try{let N=JSON.parse(S);R=N.message??N.error??R}catch{}k(`failed: HTTP ${y.status} ${R}`)}return await y.json().catch(()=>({}))}async function B(d,m,_,T,x){return await z(d,m,`/v1/apps/${encodeURIComponent(_)}/preview/${T}`,{method:"POST",body:x})}async function W(d,m,_){return{previews:(await z(d,m,`/v1/apps/${encodeURIComponent(_)}/previews`,{method:"GET"})).previews??[]}}async function Ve(d,m,_,T,x,y,S,R){let N;try{N=await ae(`zipping ${T}`,()=>Oy(T))}catch(j){k(`could not zip ${T}: ${j instanceof Error?j.message:String(j)}`)}N.fileCount===0&&k(`${T} is empty \u2014 the build produced nothing.`),N.buffer.byteLength>Ru&&k(`${T} zips to ${nT(N.buffer.byteLength)} \u2014 over the ${nT(Ru)} deploy limit. Check the build output for node_modules, source maps or media that should not ship.`);let L={Authorization:`Bearer ${m}`,"Content-Type":"application/zip"};x&&(L["x-app-entry"]=x),y&&(L["x-proposal-id"]=y),S&&(L["x-app-build-id"]=S.buildId,L["x-app-asset-base"]=S.assetBase),R&&(L["x-app-channel"]="preview",R.label&&(L["x-app-preview-label"]=encodeURIComponent(R.label)),R.replacePreviewId&&(L["x-app-preview-replace"]=R.replacePreviewId));let D=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(_)}/deploy`,H;try{H=await ae(`deploying ${_} (${N.fileCount} file${N.fileCount===1?"":"s"})`,()=>u(D,{method:"POST",headers:L,body:new Uint8Array(N.buffer)}))}catch(j){k(`deploy request failed: ${j instanceof Error?j.message:String(j)}`)}if(H.status===401&&k("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),H.status===403&&k("deploy forbidden (403) \u2014 the PAT is not for an admin."),H.status===404){let j=await H.text().catch(()=>""),Q={};try{Q=JSON.parse(j)}catch{}Q.error==="no_preview"&&k(`${Q.message??`no open preview to replace on ${_}`} \u2014 list them with \`turbobase apps preview list ${_}\`.`),k(`no app "${_}" on ${d} \u2014 create it with \`turbobase apps create ${_}\`.`)}if(!H.ok){let j=await H.text().catch(()=>""),Q=j.slice(0,300);try{let ve=JSON.parse(j);Q=ve.message??ve.error??Q}catch{}k(`deploy failed: HTTP ${H.status} ${Q}`)}return await H.json().catch(()=>({}))}function Ye(d){let m=d.roles;if(!m||m.verdicts.length===0)return;let _=m.verdicts.filter(x=>x.action!=="noop");if(_.length===0)return;v(""),v(g.bold(m.applied?"roles":"roles (preview \u2014 not applied)"));let T=Math.max(..._.map(x=>x.name.length));for(let x of _){let y=x.name.padEnd(T);if(x.action==="create"){let S=x.addCapabilities?.length??0;v(` created ${y} ${g.dim(`${S} capabilit${S===1?"y":"ies"}`)}`)}else if(x.action==="add_capabilities"){let S=(x.addCapabilities??[]).map(N=>`+${N}`).join(", "),R=x.holdersRestamped?g.dim(` (${x.holdersRestamped} holder${x.holdersRestamped===1?"":"s"} re-stamped)`):"";v(` updated ${y} ${g.dim(S)}${R}`)}}v(g.dim(m.applied?" assign these in Admin \u2192 Users \u2014 a declared role has no holders until you do.":" nothing was created \u2014 promoting this preview applies them."))}function Gt(d){let m=d.labels;if(!m||m.verdicts.length===0)return;let _=m.verdicts.filter(x=>x.action!=="noop");if(_.length===0)return;v(""),v(g.bold(m.applied?"labels":"labels (preview \u2014 not applied)"));let T=Math.max(..._.map(x=>x.name.length));for(let x of _){let y=x.name.padEnd(T);if(x.action==="detach")v(` removed ${y} ${g.dim("no longer declared in the manifest")}`);else if(x.action==="create")v(` created ${y} ${g.dim(x.color)}`);else{let S=x.declaredColor?`${x.color} \u2014 declared ${x.declaredColor}, the instance's colour is kept`:x.color;v(` added ${y} ${g.dim(S)}`)}}v(g.dim(m.applied?" labels are launcher navigation only \u2014 they change nothing about who can open this app.":" nothing was changed \u2014 promoting this preview applies them."))}async function Dr(d,m){let _=Hy(d,{localDocsModifiedAt:await pn(m)});_&&v(_.level==="warn"?g.yellow(_.message):g.dim(_.message))}async function pn(d){if(!d)return null;let m=null;for(let _ of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let T=await be.stat(Ot(d,_));(m===null||T.mtimeMs>m)&&(m=T.mtimeMs)}catch{}return m===null?null:new Date(m)}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(d,m,_)=>{let{baseUrl:T,token:x}=await ne(_.baseUrl);if(_.proposal){let N=new ee({baseUrl:T,token:x}),L;try{L=await ae(`fetching proposal ${_.proposal}`,()=>N.appPullContext(_.proposal))}catch(ve){se(ve,"extensions:deploy","pull proposal"),ve instanceof le&&ve.status===404&&k(`no widget proposal "${_.proposal}" on ${T}.`),k(`could not fetch proposal ${_.proposal}: ${ve instanceof Error?ve.message:String(ve)}`)}let D=await ae(`pulling ${L.appSlug}`,()=>w(T,x,L.appSlug)),H=m??d,j=ge(process.cwd(),H??L.appSlug);await be.mkdir(j,{recursive:!0});let Q=await f(j,D.files,!!_.force);await b(j,L,!!_.force),v(`pulled ${Q} file${Q===1?"":"s"} \u2192 ${j} (rev ${D.rev}), linked to proposal ${L.proposalId}.`),v(`next: cd ${hl(process.cwd(),j)||"."} && turbobase apps deploy ${L.appSlug}`);return}d||k("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let y=await ae(`pulling ${d}`,()=>w(T,x,d)),S=ge(process.cwd(),m??y.slug??d);await be.mkdir(S,{recursive:!0});let R=await f(S,y.files,!!_.force);v(`pulled ${R} file${R===1?"":"s"} \u2192 ${S} (rev ${y.rev}).`),v(`next: cd ${hl(process.cwd(),S)||"."} && 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(d,m,_)=>{let T=ge(process.cwd(),m??d),x=await Xt(_.baseUrl).catch(()=>null),{scaffoldAppFiles:y,starterApp:S}=await Promise.resolve().then(()=>(Sw(),$w)),R=_.title??d,N=y({slug:d,title:R,appTsx:S(R),instanceOrigin:x?.baseUrl});await be.mkdir(T,{recursive:!0});let L=await f(T,N,!!_.force);if(v(`scaffolded ${L} file${L===1?"":"s"} \u2192 ${T}`),_.claude!==!1){let H=gu({baseUrl:x?.baseUrl,token:x?.token,appSlug:d}),j=0;for(let Q of H){let ve=await rT(Ot(T,Q.path),Q);(ve==="wrote"||ve==="merged")&&(j+=1)}v(`wired Claude Code: ${j} file${j===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),x||q("not signed in \u2014 .mcp.json and the dev proxy carry placeholders. Run `turbobase auth login`, then `turbobase apps init` again (existing files are kept).")}let D=hl(process.cwd(),T)||".";v(`next: cd ${D} && npm install && npm run dev`),v(` turbobase apps create ${d}`),v(` turbobase apps push ${d} .`),v(` turbobase apps deploy ${d} .`)}),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 d=>{let{baseUrl:m,token:_}=await ne(d.baseUrl),T=new ee({baseUrl:m,token:_}),x;try{x=await T.appsList()}catch(y){se(y,"extensions:deploy","list apps"),k(`list apps failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return v(JSON.stringify(x,null,2));if(x.length===0)return v("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");v(Qt(x.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(d,m,_)=>{let T=ge(process.cwd(),m??".");await be.stat(T).then(Pe=>Pe.isDirectory()).catch(()=>!1)||k(`${T} is not a directory.`);let{baseUrl:y,token:S}=await ne(_.baseUrl),R=_.proposal??await $(T),{files:N,skipped:L,secrets:D,unstorable:H}=await Zb(T),j=Object.keys(N).length;if(j===0&&k(`no source files found under ${T} (build output and node_modules are skipped).`),H.length>0){for(let Pe of H)q(`${Pe} contains a NUL byte (U+0000), which cannot be stored.`);k(`push aborted: ${H.length} ${H.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let Pe of L)q(g.dim(`skipped binary file ${Pe}`));for(let Pe of D)q(g.dim(`skipped ${Pe} (holds credentials \u2014 never pushed)`));let Q=await ae(`pushing ${j} file${j===1?"":"s"}`,()=>E(y,S,d,N,_.note,R));v(`pushed ${Q.files} file${Q.files===1?"":"s"} \u2192 ${Q.slug} rev ${Q.rev} (source only, nothing deployed).`);let ve=await ms(new ee({baseUrl:y,token:S}),Q.slug);ve&&ve.entriesAdded>0&&v(`${ve.entriesAdded} new finding(s) queued \u2014 run \`turbobase skills push\` / \`turbobase kb push\` to act on them.`),v(`next: turbobase apps deploy ${Q.slug}`)}),o.command("plan").description("Diff this project (hooks/, conduits/, turbobase/) 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 d=>{let m=await tg(),{baseUrl:_,token:T}=await ne(d.baseUrl),x=new ee({baseUrl:_,token:T}),y;try{y=await ae(`planning against ${d.to??_}`,()=>x.configPlan(m))}catch(S){k(`plan failed: ${S instanceof Error?S.message:String(S)}`)}JM(y,d.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).").option("--prune","Also REMOVE anything on the target this project no longer declares. Off by default.").action(async d=>{let m=await tg(),{baseUrl:_,token:T}=await ne(d.baseUrl),x=m.tenant??YM(_),y=tb(d.confirm,x);y.ok||k(`promote refused (fail-closed): ${y.reason}`);let S=new ee({baseUrl:_,token:T});try{let R=await ae(`promoting ${d.from} \u2192 ${d.to} (${x})`,()=>S.configApply(m,{prune:d.prune}));if(tt()){let L=[`${g.bold(`${d.from} \u2192 ${d.to}`)} ${g.dim(x??"")}`,`${Hr.add(String(R.applied.add))} ${Hr.change(String(R.applied.change))} ${Hr.destroy(String(R.applied.destroy))}`];R.backfillsQueued.length&&L.push(g.dim(`${R.backfillsQueued.length} backfill(s) queued`)),v(Vr("Promoted",L))}else v(`promoted ${d.from} \u2192 ${d.to} (${x}): +${R.applied.add} ~${R.applied.change} -${R.applied.destroy}`+(R.backfillsQueued.length?` (${R.backfillsQueued.length} backfill(s) queued)`:""));let N=R.skippedDestroys??[];if(N.length>0){q(`${N.length} resource(s) on ${d.to} are not declared by this project \u2014 NOT removed:`);for(let L of N)q(` ${L.kind} ${L.id}`);q("Re-run with --prune to remove them, or add them to this repo.")}}catch(R){R instanceof le&&R.status===403&&k("promote forbidden (403) \u2014 the stored PAT is not for an admin."),k(`promote failed: ${R instanceof Error?R.message:String(R)}`)}}),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(d,m)=>{let _=eg(m.reporter),T=ge(process.cwd(),d),x=await ls(T),y=Ny(x);_?v(na(HM(d,y),_)):v(zy(d,y,{warn:g.yellow,ok:g.green,dim:g.dim})),m.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(d,m)=>{let _=eg(m.reporter),T=await Ty(ge(process.cwd(),d));if(m.against){m.against!=="sandbox"&&k(`unknown --against target '${m.against}' (only 'sandbox' is supported).`);try{await $y(lu(T))}catch(S){k(S instanceof Error?S.message:String(S))}return}m.fixture||k("replay needs a --fixture <file> (offline) or --against sandbox (online).");let x;try{x=await Sy(ge(process.cwd(),m.fixture))}catch(S){k(`could not read fixture ${m.fixture}: ${S instanceof Error?S.message:String(S)}`)}let y=await ky(T,x,m.fixture,{resolveDir:Lr(ge(process.cwd(),d))});if(_){let S=VM(y);v(na(S,_)),pl(S.cases.some(R=>R.status==="failed")?1:0)}v(Ey(y,!!m.trace)),pl(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 d=>{let{baseUrl:m,token:_}=await ne(d.baseUrl),T=new ee({baseUrl:m,token:_});try{await By(T,{status:d.status,retry:d.retry,limit:d.limit?Number(d.limit):void 0,sink:v})}catch(x){x instanceof le&&x.status===403&&k("forbidden (403) \u2014 binding --retry requires an admin PAT."),x instanceof le&&x.status===409&&k("binding is not retryable (only divergent/blocked bindings can be retried)."),k(`ext binding failed: ${x instanceof Error?x.message:String(x)}`)}});let Mr=o.command("proposals").description("Review the hook proposals waiting on a decision \u2014 list, promote, retract, reject.");Mr.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 d=>{await Ib(d)}),Mr.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(d,m)=>{await Ob(d??[],m)}),Mr.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(d,m)=>{await Cb(d,m)}),Mr.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(d,m)=>{await Nb(d,m)}),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(d,m)=>{let _=d.lastIndexOf("@"),T=_>0?d.slice(0,_):d,x=_>0?d.slice(_+1):void 0,y=ou();y||k(`marketplace not configured \u2014 set ${lo} and ${Gi}.
3770
+ Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let S=su(y.registryUrl);S&&k(S);let{baseUrl:R,token:N}=await ne(m.baseUrl),L=new is(y),D;try{D=await ae(`fetching ${d}`,()=>L.fetchBundle(T,x))}catch(Pe){k(`marketplace fetch failed for ${d}: ${Pe instanceof Error?Pe.message:String(Pe)}`)}let H=Mi(D.manifest),j=null;if(H.length>0){if(!m.connection){let Pe=H.map(eo=>eo.source_system).join(", ");k(`${D.name}@${D.version} declares a connection input (source: ${Pe}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}j=m.connection}let Q=KM(D.bundle,D.name,D.kind),ve=new ee({baseUrl:R,token:N});try{let Pe=await ae(`installing ${D.name}@${D.version}`,()=>ve.deploy({...Q,provenance:"marketplace",...j?{connectionId:j}:{}}));v(`installed ${D.name}@${D.version} \u2192 ${Pe.id} (status=${Pe.status}, ${Pe.outcome})`+(j?` bound to connection ${j}.`:"."))}catch(Pe){Pe instanceof le&&Pe.status===403&&k("install forbidden (403) \u2014 the stored PAT is not for an admin."),k(`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(d,m)=>{let _=ou();_||k(`marketplace not configured \u2014 set ${lo} and ${Gi}.
3771
+ Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let T=su(_.registryUrl);T&&k(T);let x=ge(process.cwd(),d),y=await ls(x),S=/\bdefineConduit\s*[<(]/.test(y)?"conduit":"hook",R={};if(m.manifest){let D=ge(process.cwd(),m.manifest),H;try{H=await be.readFile(D,"utf8")}catch{k(`manifest not found at ${m.manifest}.`)}let j;try{j=JSON.parse(H)}catch{k(`manifest is not valid JSON: ${m.manifest}.`)}(typeof j!="object"||j===null||Array.isArray(j))&&k("manifest must be a JSON object."),R=j}try{Ml(R,y)}catch(D){D instanceof Fr&&k(D.message),k(`manifest validation failed: ${D instanceof Error?D.message:String(D)}`)}let N=new is(_);try{await ae(`publishing ${m.name}@${m.pkgVersion}`,()=>N.publish({name:m.name,version:m.pkgVersion,kind:S,bundle:y,manifest:R}))}catch(D){D instanceof le&&D.status===403&&k("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),D instanceof le&&D.status===409&&k(`version already published \u2014 ${m.name}@${m.pkgVersion} exists. Bump the version.`),k(`publish failed: ${D instanceof Error?D.message:String(D)}`)}let L=Mi(R);v(`published ${m.name}@${m.pkgVersion} (kind=${S}) to the marketplace.`),L.length>0&&v(` declares ${L.length} connection input(s): ${L.map(D=>D.source_system).join(", ")} \u2014 bound at install.`)}),n.command("init").description("Scaffold a Claude-Code extension project in the current dir.").option("--base-url <url>","Instance to wire .mcp.json to (defaults to the active instance).").action(async d=>{let m=await Xt(d.baseUrl).catch(()=>null),_=gu({baseUrl:m?.baseUrl,token:m?.token}),T=0,x=0,y=0;for(let S of _){let R=ge(process.cwd(),S.path),N=await rT(R,S);N==="wrote"?(T+=1,v(` wrote ${S.path}`)):N==="merged"?(y+=1,v(` merged ${S.path} (added the .mcp.json rule)`)):(x+=1,v(` skipped ${S.path} (exists)`))}v(`
3772
+ project init: ${T} written, ${y} merged, ${x} skipped.`)}),n.command("ci").description(`Write the reusable release-deploy GitHub Action to ${mu} (non-destructive).`).action(async()=>{let d=Vy(),m=0,_=0;for(let T of d){let x=ge(process.cwd(),T.path);await Xn(x,T.content,T.executable)==="wrote"?(m+=1,v(` wrote ${T.path}`)):(_+=1,v(` skipped ${T.path} (exists)`))}v(`
3766
3773
  project ci: ${m} written, ${_} skipped.`),m>0&&(v(`
3767
- Next: mint a releases:write PAT in your Turbobase app (Settings \u203A Access tokens),`),v("store it as the GitHub Actions secret TURBOBASE_RELEASE_PAT, and set the repo"),v("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 d=>{let{baseUrl:m,token:_}=await ne(d.baseUrl),T=new ee({baseUrl:m,token:_}),x;try{x=await T.catalogRecords()}catch(L){L instanceof le&&(L.status===401||L.status===403)&&k("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),k(`catalog fetch failed: ${L instanceof Error?L.message:String(L)}`)}if(x.length===0){v("no records in the instance catalog \u2014 nothing to generate.");return}let y=ge(process.cwd(),d.out),S=Ty(x,{event:d.event}),R=0,N=0;for(let{recordType:L,fixture:D}of S){let H=Ot(y,`${L}.json`),j=`${JSON.stringify(D,null,2)}
3774
+ Next: mint a releases:write PAT in your Turbobase app (Settings \u203A Access tokens),`),v("store it as the GitHub Actions secret TURBOBASE_RELEASE_PAT, and set the repo"),v("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 d=>{let{baseUrl:m,token:_}=await ne(d.baseUrl),T=new ee({baseUrl:m,token:_}),x;try{x=await T.catalogRecords()}catch(L){L instanceof le&&(L.status===401||L.status===403)&&k("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),k(`catalog fetch failed: ${L instanceof Error?L.message:String(L)}`)}if(x.length===0){v("no records in the instance catalog \u2014 nothing to generate.");return}let y=ge(process.cwd(),d.out),S=Py(x,{event:d.event}),R=0,N=0;for(let{recordType:L,fixture:D}of S){let H=Ot(y,`${L}.json`),j=`${JSON.stringify(D,null,2)}
3768
3775
  `;d.force?(await be.mkdir(Lr(H),{recursive:!0}),await be.writeFile(H,j,{mode:420}),R+=1,v(` wrote ${d.out}/${L}.json`)):await Xn(H,j)==="wrote"?(R+=1,v(` wrote ${d.out}/${L}.json`)):(N+=1,v(` skipped ${d.out}/${L}.json (exists \u2014 use --force to overwrite)`))}v(`
3769
- samples init: ${R} written, ${N} skipped.`)});let lr=e.command("guardrails").description("Control PG\u2192source write-back with policy rules (staged write rollout)."),$i=d=>[d.name??g.dim(d.id.slice(0,8)),d.status==="active"?g.green("active"):d.status==="proposed"?g.yellow("proposed"):g.dim("inactive"),d.decision==="deny"?g.red(d.decision):d.decision==="require_confirm"?g.yellow(d.decision):g.green(d.decision),String(d.priority),d.source,d.record??d.op,d.actor??g.dim("any"),d.when||g.dim("(always)"),d.reason??""],pl=["NAME","STATUS","DECISION","PRIO","SOURCE","RECORD","ACTOR","WHEN","REASON"];lr.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 d=>{let{baseUrl:m,token:_}=await ne(d.baseUrl),T=new ee({baseUrl:m,token:_}),x;try{x=await T.guardrailsList()}catch(y){se(y,"extensions:deploy","list guardrails"),k(`list guardrails failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return v(JSON.stringify(x,null,2));if(x.length===0)return v(`no write guardrails \u2014 every record the admin entitlement allows is writable.
3770
- `+g.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));v(Qt(x.map($i),{head:pl})),v(g.dim(" first match wins; lower PRIO is evaluated first."))}),lr.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).",d=>Number(d)).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(d,m)=>{let{baseUrl:_,token:T}=await ne(m.baseUrl),x=new ee({baseUrl:_,token:T}),y;try{y=await x.guardrailCreate({name:d,source:m.source,record:m.record,decision:m.decision,...m.op?{op:m.op}:{},...m.target?{target:m.target}:{},...m.actor?{actor:m.actor}:{},...Number.isFinite(m.priority)?{priority:Number(m.priority)}:{},...m.when?{when:m.when}:{},...m.reason?{reason:m.reason}:{},...m.disabled?{enabled:!1}:{},...m.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(S){se(S,"extensions:deploy","create a guardrail"),k(`create guardrail failed: ${S instanceof Error?S.message:String(S)}`)}v(`${g.green("\u2713")} guardrail ${g.bold(y.name??y.id)} created${y.status==="active"?"":g.dim(` (${y.status} \u2014 activate it to take effect)`)}`),v(g.dim(` ${y.decision} ${y.source}/${y.record??y.op}${y.actor?` actor=${y.actor}`:""}${y.when?` where ${y.when}`:""} @prio ${y.priority}`)),v(g.dim(` verify with: turbobase guardrails test --source ${y.source==="*"?"<source>":y.source} --record <record>`))}),lr.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.",d=>Number(d)).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(d,m)=>{m.decision===void 0&&m.priority===void 0&&m.when===void 0&&m.reason===void 0&&k("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:_,token:T}=await ne(m.baseUrl),x=new ee({baseUrl:_,token:T}),y;try{y=await x.guardrailUpdate(d,{...m.decision!==void 0?{decision:m.decision}:{},...Number.isFinite(m.priority)?{priority:Number(m.priority)}:{},...m.when!==void 0?{when:m.when}:{},...m.reason!==void 0?{reason:m.reason}:{}})}catch(S){se(S,"extensions:deploy","edit a guardrail"),k(`edit guardrail failed: ${S instanceof Error?S.message:String(S)}`)}v(`${g.green("\u2713")} guardrail ${g.bold(y.name??y.id)} updated`),v(g.dim(` ${y.decision} ${y.source}/${y.record??y.op}${y.when?` where ${y.when}`:""} @prio ${y.priority}`))});for(let[d,m,_]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])lr.command(`${d} <name>`).description(m==="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(T,x)=>{let{baseUrl:y,token:S}=await ne(x.baseUrl),R=new ee({baseUrl:y,token:S});try{await R.guardrailUpdate(T,{status:m})}catch(N){se(N,"extensions:deploy",`${d} a guardrail`),k(`${d} guardrail failed: ${N instanceof Error?N.message:String(N)}`)}v(`${g.green("\u2713")} guardrail ${g.bold(T)} ${_}`),m==="inactive"&&v(g.dim(" writes it was gating now fall through to the other rules."))});lr.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(d,m)=>{let{baseUrl:_,token:T}=await ne(m.baseUrl),x=new ee({baseUrl:_,token:T});try{await x.guardrailDelete(d)}catch(y){se(y,"extensions:deploy","delete a guardrail"),k(`delete guardrail failed: ${y instanceof Error?y.message:String(y)}`)}v(`${g.green("\u2713")} guardrail ${g.bold(d)} deleted`)}),lr.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(d,m)=>{let{baseUrl:_,token:T}=await ne(m.baseUrl),x=new ee({baseUrl:_,token:T}),y=N=>N==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let N;try{N=await x.guardrailPostureGet()}catch(L){se(L,"extensions:deploy","read the guardrail posture"),k(`read posture failed: ${L instanceof Error?L.message:String(L)}`)}v(`guardrail posture: ${g.bold(y(N.mode))}`),v(g.dim(N.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 S=d.trim().toLowerCase();S!=="allow"&&S!=="deny"&&k("posture must be 'allow' or 'deny'.");let R;try{R=await x.guardrailPostureSet(S)}catch(N){se(N,"extensions:deploy","set the guardrail posture"),k(`set posture failed: ${N instanceof Error?N.message:String(N)}`)}v(`${g.green("\u2713")} guardrail posture set to ${g.bold(y(R.mode))}`),R.mode==="deny"&&v(g.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),lr.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("--op <op>","Write op: 'delete' tests <record>.delete; omitted tests <record>.write.").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 d=>{let m;if(d.fields)try{m=JSON.parse(d.fields)}catch(R){k(`--fields must be valid JSON: ${R instanceof Error?R.message:String(R)}`)}let{baseUrl:_,token:T}=await ne(d.baseUrl),x=new ee({baseUrl:_,token:T}),y;try{y=await x.guardrailTest({source:d.source,record:d.record,...d.actor?{actor:d.actor}:{},...d.externalId?{externalId:d.externalId}:{},...m?{fields:m}:{},...d.op?{op:d.op}:{},...d.phase?{phase:d.phase}:{}})}catch(R){se(R,"extensions:deploy","test guardrails"),k(`guardrails test failed: ${R instanceof Error?R.message:String(R)}`)}if(d.json)return v(JSON.stringify(y,null,2));let S=`${d.source}/${y.op??d.record}`;y.degraded?(v(`${g.red("\u2717")} ${S} \u2014 guardrail policy is UNREADABLE; writes fail closed`),v(g.dim(` ${y.reason}`))):y.allowed?v(`${g.green("\u2713")} ${S} \u2014 ${y.decision}`+(y.blockedBy?g.dim(` (rule ${y.blockedBy})`):g.dim(" (no rule matched)"))):(v(`${g.red("\u2717")} ${S} \u2014 ${y.decision} by ${g.bold(y.blockedBy??"?")} at the ${y.phase} gate`),y.message&&v(g.dim(` ${y.message}`))),y.decision==="require_confirm"&&v(g.yellow(" this write is HELD for operator approval, not refused.")),y.allowed||(process.exitCode=1)});let Go=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),Si=(d,m={})=>{let _=`${g.bold(d.table)} ${g.dim(d.displayName)}`;v(d.exists===!1?`${_} ${g.dim("(new)")}`:_);for(let T of d.fields){let x=[T.required?"required":null].filter(Boolean).join(", "),y=m.showClaimants&&T.claimedBy?.length?` ${g.dim(`\u2190 ${T.claimedBy.join(", ")}`)}`:"";v(` ${T.column.padEnd(28)} ${T.type}${x?` (${x})`:""}${y}`)}m.showClaimants&&d.claimants.length>1&&v(g.dim(` claimed by ${d.claimants.join(", ")}`))};function Ti(d){if(d instanceof le&&d.status===409){let m=d.body;m?.error==="table_conflict"&&m.message&&(q(m.message),process.exit(1))}k(`tables: ${d instanceof Error?d.message:String(d)}`)}let sg=async d=>{let m=Ot(ge(process.cwd(),d),"public","turbobase.json"),_=await be.readFile(m,"utf8").catch(()=>null);if(_===null)return null;let T;try{T=JSON.parse(_)}catch(y){k(`${m} is not valid JSON: ${y instanceof Error?y.message:String(y)}`)}let x=T.tables;return x===void 0?{tables:[],manifestPath:m}:(Array.isArray(x)||k(`${m}: "tables" must be an array.`),{tables:x,manifestPath:m})};Go.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 d=>{let{baseUrl:m,token:_}=await ne(d.baseUrl),T=new ee({baseUrl:m,token:_}),x;try{x=await T.tablesList()}catch(y){se(y,"extensions:deploy","list tables"),k(`list tables failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return v(JSON.stringify(x,null,2));if(x.length===0)return v("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");v(Qt(x.map(y=>[y.table,y.displayName,String(y.fields.length),y.status,y.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),Go.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(d,m)=>{let _=await sg(d??".");if(_||k(`no public/turbobase.json under ${ge(process.cwd(),d??".")}.`),_.tables.length===0)return v(`${_.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:T,token:x}=await ne(m.baseUrl),y=new ee({baseUrl:T,token:x}),S;try{S=await ae("planning tables",()=>y.tablesPlan({claimedBy:m.as,tables:_.tables}))}catch(R){se(R,"extensions:deploy","plan tables"),Ti(R)}v(`claiming as ${g.bold(S.claimedBy)}`);for(let R of S.tables)Si(R,{showClaimants:!0});v(""),v(g.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),Go.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(d,m)=>{let _=await sg(d??".");if(_||k(`no public/turbobase.json under ${ge(process.cwd(),d??".")}.`),_.tables.length===0)return v(`${_.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:T,token:x}=await ne(m.baseUrl),y=new ee({baseUrl:T,token:x}),S;try{S=await ae("applying tables",()=>y.tablesApply({claimedBy:m.as,tables:_.tables}))}catch(R){se(R,"extensions:deploy","apply tables"),Ti(R)}for(let R of S.tables)Si(R,{showClaimants:!0});v(`applied ${S.tables.length} table${S.tables.length===1?"":"s"} as ${S.claimedBy}.`)}),Go.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.",(d,m)=>[...m??[],d],[]).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(d,m)=>{let _=m.field.map(R=>{let[N,L,D]=R.split(":");return(!N||!L)&&k(`--field "${R}" must be name:type[:required] (e.g. title:text:required).`),D!==void 0&&D!=="required"&&k(`--field "${R}": the third part may only be "required".`),{name:N,type:L,...D==="required"?{required:!0}:{}}}),{baseUrl:T,token:x}=await ne(m.baseUrl),y=new ee({baseUrl:T,token:x}),S;try{S=await ae(`creating cr_${d}`,()=>y.tablesApply({tables:[{slug:d,displayName:m.name??d,fields:_,...m.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(R){se(R,"extensions:deploy","create a table"),Ti(R)}for(let R of S.tables)Si(R);v(""),v(g.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),Go.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(d,m)=>{m.confirm!==d&&k(`drop refused: --confirm "${m.confirm}" does not match "${d}".`);let{baseUrl:_,token:T}=await ne(m.baseUrl),x=new ee({baseUrl:_,token:T}),y;try{y=await ae(`dropping cr_${d}`,()=>x.tablesDrop(d,m.confirm))}catch(S){se(S,"extensions:deploy","drop a table"),k(`drop failed: ${S instanceof Error?S.message:String(S)}`)}if(!y.removed)return v(`no table named "${d}" on this instance \u2014 nothing dropped.`);v(`dropped ${y.table} and every row in it.`)});let hl=e.command("sandbox").description("Ephemeral local authoring sandboxes.");hl.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 d=>{process.env.TURBOBASE_SANDBOX="1";let m=eg(),_;try{_=await Yb(m,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(T){T instanceof ys&&k(T.message),k(`sandbox create failed: ${T instanceof Error?T.message:String(T)}`)}v(`sandbox ${_.name} ready.`),v(` source: ${_.fromTenant} (sampled ${Math.round(_.sampleFraction*100)}%, redacted)`),v(` url: ${_.url}`),v(` expires: ${_.expiresAt}`)}),hl.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async d=>{let m=eg();await ju(m).catch(()=>[]);let _;try{_=await Xb(m,d)}catch(T){k(`sandbox destroy failed: ${T instanceof Error?T.message:String(T)}`)}_||k(`no sandbox named '${d}'.`),v(`destroyed sandbox ${_.name} (dropped ${_.database}).`)}),hl.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=eg(),m=await ju(d).catch(()=>[]),_=await ga(),{active:T}=zu(_);if(T.length===0)v("no active sandboxes.");else{for(let x of T)v(` ${x.name} from=${x.fromTenant} expires=${x.expiresAt} ${x.url}`);v(`
3771
- ${T.length} active sandbox(es).`)}m.length>0&&v(`(reaped ${m.length} expired sandbox(es).)`)}),o.command("export").description("Pull the live instance into turbobase/bundle.json (adopt an instance into a repo).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",ia).action(async d=>{let{baseUrl:m,token:_}=await ne(d.baseUrl),T=new ee({baseUrl:m,token:_}),x;try{x=await ae("exporting instance config",()=>T.configExport())}catch(R){R instanceof le&&(R.status===401||R.status===403)&&k("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),k(`ext export failed: ${R instanceof Error?R.message:String(R)}`)}let y=typeof x.serialized=="string"?x.serialized:`${JSON.stringify(x.manifest??x,null,2)}
3776
+ samples init: ${R} written, ${N} skipped.`)});let lr=e.command("guardrails").description("Control PG\u2192source write-back with policy rules (staged write rollout)."),$i=d=>[d.name??g.dim(d.id.slice(0,8)),d.status==="active"?g.green("active"):d.status==="proposed"?g.yellow("proposed"):g.dim("inactive"),d.decision==="deny"?g.red(d.decision):d.decision==="require_confirm"?g.yellow(d.decision):g.green(d.decision),String(d.priority),d.source,d.record??d.op,d.actor??g.dim("any"),d.when||g.dim("(always)"),d.reason??""],fl=["NAME","STATUS","DECISION","PRIO","SOURCE","RECORD","ACTOR","WHEN","REASON"];lr.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 d=>{let{baseUrl:m,token:_}=await ne(d.baseUrl),T=new ee({baseUrl:m,token:_}),x;try{x=await T.guardrailsList()}catch(y){se(y,"extensions:deploy","list guardrails"),k(`list guardrails failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return v(JSON.stringify(x,null,2));if(x.length===0)return v(`no write guardrails \u2014 every record the admin entitlement allows is writable.
3777
+ `+g.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));v(Qt(x.map($i),{head:fl})),v(g.dim(" first match wins; lower PRIO is evaluated first."))}),lr.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).",d=>Number(d)).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(d,m)=>{let{baseUrl:_,token:T}=await ne(m.baseUrl),x=new ee({baseUrl:_,token:T}),y;try{y=await x.guardrailCreate({name:d,source:m.source,record:m.record,decision:m.decision,...m.op?{op:m.op}:{},...m.target?{target:m.target}:{},...m.actor?{actor:m.actor}:{},...Number.isFinite(m.priority)?{priority:Number(m.priority)}:{},...m.when?{when:m.when}:{},...m.reason?{reason:m.reason}:{},...m.disabled?{enabled:!1}:{},...m.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(S){se(S,"extensions:deploy","create a guardrail"),k(`create guardrail failed: ${S instanceof Error?S.message:String(S)}`)}v(`${g.green("\u2713")} guardrail ${g.bold(y.name??y.id)} created${y.status==="active"?"":g.dim(` (${y.status} \u2014 activate it to take effect)`)}`),v(g.dim(` ${y.decision} ${y.source}/${y.record??y.op}${y.actor?` actor=${y.actor}`:""}${y.when?` where ${y.when}`:""} @prio ${y.priority}`)),v(g.dim(` verify with: turbobase guardrails test --source ${y.source==="*"?"<source>":y.source} --record <record>`))}),lr.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.",d=>Number(d)).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(d,m)=>{m.decision===void 0&&m.priority===void 0&&m.when===void 0&&m.reason===void 0&&k("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:_,token:T}=await ne(m.baseUrl),x=new ee({baseUrl:_,token:T}),y;try{y=await x.guardrailUpdate(d,{...m.decision!==void 0?{decision:m.decision}:{},...Number.isFinite(m.priority)?{priority:Number(m.priority)}:{},...m.when!==void 0?{when:m.when}:{},...m.reason!==void 0?{reason:m.reason}:{}})}catch(S){se(S,"extensions:deploy","edit a guardrail"),k(`edit guardrail failed: ${S instanceof Error?S.message:String(S)}`)}v(`${g.green("\u2713")} guardrail ${g.bold(y.name??y.id)} updated`),v(g.dim(` ${y.decision} ${y.source}/${y.record??y.op}${y.when?` where ${y.when}`:""} @prio ${y.priority}`))});for(let[d,m,_]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])lr.command(`${d} <name>`).description(m==="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(T,x)=>{let{baseUrl:y,token:S}=await ne(x.baseUrl),R=new ee({baseUrl:y,token:S});try{await R.guardrailUpdate(T,{status:m})}catch(N){se(N,"extensions:deploy",`${d} a guardrail`),k(`${d} guardrail failed: ${N instanceof Error?N.message:String(N)}`)}v(`${g.green("\u2713")} guardrail ${g.bold(T)} ${_}`),m==="inactive"&&v(g.dim(" writes it was gating now fall through to the other rules."))});lr.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(d,m)=>{let{baseUrl:_,token:T}=await ne(m.baseUrl),x=new ee({baseUrl:_,token:T});try{await x.guardrailDelete(d)}catch(y){se(y,"extensions:deploy","delete a guardrail"),k(`delete guardrail failed: ${y instanceof Error?y.message:String(y)}`)}v(`${g.green("\u2713")} guardrail ${g.bold(d)} deleted`)}),lr.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(d,m)=>{let{baseUrl:_,token:T}=await ne(m.baseUrl),x=new ee({baseUrl:_,token:T}),y=N=>N==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let N;try{N=await x.guardrailPostureGet()}catch(L){se(L,"extensions:deploy","read the guardrail posture"),k(`read posture failed: ${L instanceof Error?L.message:String(L)}`)}v(`guardrail posture: ${g.bold(y(N.mode))}`),v(g.dim(N.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 S=d.trim().toLowerCase();S!=="allow"&&S!=="deny"&&k("posture must be 'allow' or 'deny'.");let R;try{R=await x.guardrailPostureSet(S)}catch(N){se(N,"extensions:deploy","set the guardrail posture"),k(`set posture failed: ${N instanceof Error?N.message:String(N)}`)}v(`${g.green("\u2713")} guardrail posture set to ${g.bold(y(R.mode))}`),R.mode==="deny"&&v(g.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),lr.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("--op <op>","Write op: 'delete' tests <record>.delete; omitted tests <record>.write.").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 d=>{let m;if(d.fields)try{m=JSON.parse(d.fields)}catch(R){k(`--fields must be valid JSON: ${R instanceof Error?R.message:String(R)}`)}let{baseUrl:_,token:T}=await ne(d.baseUrl),x=new ee({baseUrl:_,token:T}),y;try{y=await x.guardrailTest({source:d.source,record:d.record,...d.actor?{actor:d.actor}:{},...d.externalId?{externalId:d.externalId}:{},...m?{fields:m}:{},...d.op?{op:d.op}:{},...d.phase?{phase:d.phase}:{}})}catch(R){se(R,"extensions:deploy","test guardrails"),k(`guardrails test failed: ${R instanceof Error?R.message:String(R)}`)}if(d.json)return v(JSON.stringify(y,null,2));let S=`${d.source}/${y.op??d.record}`;y.degraded?(v(`${g.red("\u2717")} ${S} \u2014 guardrail policy is UNREADABLE; writes fail closed`),v(g.dim(` ${y.reason}`))):y.allowed?v(`${g.green("\u2713")} ${S} \u2014 ${y.decision}`+(y.blockedBy?g.dim(` (rule ${y.blockedBy})`):g.dim(" (no rule matched)"))):(v(`${g.red("\u2717")} ${S} \u2014 ${y.decision} by ${g.bold(y.blockedBy??"?")} at the ${y.phase} gate`),y.message&&v(g.dim(` ${y.message}`))),y.decision==="require_confirm"&&v(g.yellow(" this write is HELD for operator approval, not refused.")),y.allowed||(process.exitCode=1)});let Go=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),Si=(d,m={})=>{let _=`${g.bold(d.table)} ${g.dim(d.displayName)}`;v(d.exists===!1?`${_} ${g.dim("(new)")}`:_);for(let T of d.fields){let x=[T.required?"required":null].filter(Boolean).join(", "),y=m.showClaimants&&T.claimedBy?.length?` ${g.dim(`\u2190 ${T.claimedBy.join(", ")}`)}`:"";v(` ${T.column.padEnd(28)} ${T.type}${x?` (${x})`:""}${y}`)}m.showClaimants&&d.claimants.length>1&&v(g.dim(` claimed by ${d.claimants.join(", ")}`))};function Ti(d){if(d instanceof le&&d.status===409){let m=d.body;m?.error==="table_conflict"&&m.message&&(q(m.message),process.exit(1))}k(`tables: ${d instanceof Error?d.message:String(d)}`)}let ag=async d=>{let m=Ot(ge(process.cwd(),d),"public","turbobase.json"),_=await be.readFile(m,"utf8").catch(()=>null);if(_===null)return null;let T;try{T=JSON.parse(_)}catch(y){k(`${m} is not valid JSON: ${y instanceof Error?y.message:String(y)}`)}let x=T.tables;return x===void 0?{tables:[],manifestPath:m}:(Array.isArray(x)||k(`${m}: "tables" must be an array.`),{tables:x,manifestPath:m})};Go.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 d=>{let{baseUrl:m,token:_}=await ne(d.baseUrl),T=new ee({baseUrl:m,token:_}),x;try{x=await T.tablesList()}catch(y){se(y,"extensions:deploy","list tables"),k(`list tables failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return v(JSON.stringify(x,null,2));if(x.length===0)return v("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");v(Qt(x.map(y=>[y.table,y.displayName,String(y.fields.length),y.status,y.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),Go.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(d,m)=>{let _=await ag(d??".");if(_||k(`no public/turbobase.json under ${ge(process.cwd(),d??".")}.`),_.tables.length===0)return v(`${_.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:T,token:x}=await ne(m.baseUrl),y=new ee({baseUrl:T,token:x}),S;try{S=await ae("planning tables",()=>y.tablesPlan({claimedBy:m.as,tables:_.tables}))}catch(R){se(R,"extensions:deploy","plan tables"),Ti(R)}v(`claiming as ${g.bold(S.claimedBy)}`);for(let R of S.tables)Si(R,{showClaimants:!0});v(""),v(g.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),Go.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(d,m)=>{let _=await ag(d??".");if(_||k(`no public/turbobase.json under ${ge(process.cwd(),d??".")}.`),_.tables.length===0)return v(`${_.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:T,token:x}=await ne(m.baseUrl),y=new ee({baseUrl:T,token:x}),S;try{S=await ae("applying tables",()=>y.tablesApply({claimedBy:m.as,tables:_.tables}))}catch(R){se(R,"extensions:deploy","apply tables"),Ti(R)}for(let R of S.tables)Si(R,{showClaimants:!0});v(`applied ${S.tables.length} table${S.tables.length===1?"":"s"} as ${S.claimedBy}.`)}),Go.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.",(d,m)=>[...m??[],d],[]).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(d,m)=>{let _=m.field.map(R=>{let[N,L,D]=R.split(":");return(!N||!L)&&k(`--field "${R}" must be name:type[:required] (e.g. title:text:required).`),D!==void 0&&D!=="required"&&k(`--field "${R}": the third part may only be "required".`),{name:N,type:L,...D==="required"?{required:!0}:{}}}),{baseUrl:T,token:x}=await ne(m.baseUrl),y=new ee({baseUrl:T,token:x}),S;try{S=await ae(`creating cr_${d}`,()=>y.tablesApply({tables:[{slug:d,displayName:m.name??d,fields:_,...m.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(R){se(R,"extensions:deploy","create a table"),Ti(R)}for(let R of S.tables)Si(R);v(""),v(g.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),Go.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(d,m)=>{m.confirm!==d&&k(`drop refused: --confirm "${m.confirm}" does not match "${d}".`);let{baseUrl:_,token:T}=await ne(m.baseUrl),x=new ee({baseUrl:_,token:T}),y;try{y=await ae(`dropping cr_${d}`,()=>x.tablesDrop(d,m.confirm))}catch(S){se(S,"extensions:deploy","drop a table"),k(`drop failed: ${S instanceof Error?S.message:String(S)}`)}if(!y.removed)return v(`no table named "${d}" on this instance \u2014 nothing dropped.`);v(`dropped ${y.table} and every row in it.`)});let ml=e.command("sandbox").description("Ephemeral local authoring sandboxes.");ml.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 d=>{process.env.TURBOBASE_SANDBOX="1";let m=rg(),_;try{_=await ew(m,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(T){T instanceof ys&&k(T.message),k(`sandbox create failed: ${T instanceof Error?T.message:String(T)}`)}v(`sandbox ${_.name} ready.`),v(` source: ${_.fromTenant} (sampled ${Math.round(_.sampleFraction*100)}%, redacted)`),v(` url: ${_.url}`),v(` expires: ${_.expiresAt}`)}),ml.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async d=>{let m=rg();await Du(m).catch(()=>[]);let _;try{_=await tw(m,d)}catch(T){k(`sandbox destroy failed: ${T instanceof Error?T.message:String(T)}`)}_||k(`no sandbox named '${d}'.`),v(`destroyed sandbox ${_.name} (dropped ${_.database}).`)}),ml.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=rg(),m=await Du(d).catch(()=>[]),_=await ba(),{active:T}=Lu(_);if(T.length===0)v("no active sandboxes.");else{for(let x of T)v(` ${x.name} from=${x.fromTenant} expires=${x.expiresAt} ${x.url}`);v(`
3778
+ ${T.length} active sandbox(es).`)}m.length>0&&v(`(reaped ${m.length} expired sandbox(es).)`)}),o.command("export").description("Pull the live instance into turbobase/bundle.json (adopt an instance into a repo).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",ca).action(async d=>{let{baseUrl:m,token:_}=await ne(d.baseUrl),T=new ee({baseUrl:m,token:_}),x;try{x=await ae("exporting instance config",()=>T.configExport())}catch(R){R instanceof le&&(R.status===401||R.status===403)&&k("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),k(`ext export failed: ${R instanceof Error?R.message:String(R)}`)}let y=typeof x.serialized=="string"?x.serialized:`${JSON.stringify(x.manifest??x,null,2)}
3772
3779
  `,S=ge(process.cwd(),d.out,ds);await be.mkdir(Lr(S),{recursive:!0}),await be.writeFile(S,y,"utf8"),v(`wrote ${d.out}/${ds} (${y.split(`
3773
- `).length} lines).`)});let ig=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),rT=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],ag=()=>process.env.TURBOBASE_HOME?.trim()||Ot(OM(),".turbobase"),nT=()=>"1.23.0",Ei=async()=>Promise.all(rT.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));ig.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await Ei();for(let m of d)v(`${m.present?Ke.success("installed"):Ke.warn("missing")} ${g.bold(m.name)} \u2014 ${m.needs}`);d.some(m=>!m.present)&&v(`
3774
- run \`${hs} ext extras install\` to fetch them into ${ag()}.`)}),ig.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await Ei();if(d.every(N=>N.present)){v(Ke.success("extras already installed \u2014 nothing to do."));return}let m=ag();await be.mkdir(m,{recursive:!0});let _=d.filter(N=>!N.present).map(N=>N.name),T=Pu(process.platform,process.arch),x=async(N,L)=>{let{code:D,stderr:H}=await ki("npm",["install","--prefix",m,"--no-audit","--no-fund",...N]);D!==0&&k(`extras install failed while installing ${L} (npm exited ${D}).
3780
+ `).length} lines).`)});let cg=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),sT=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],lg=()=>process.env.TURBOBASE_HOME?.trim()||Ot(DM(),".turbobase"),iT=()=>"1.24.0",Ei=async()=>Promise.all(sT.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));cg.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await Ei();for(let m of d)v(`${m.present?Ke.success("installed"):Ke.warn("missing")} ${g.bold(m.name)} \u2014 ${m.needs}`);d.some(m=>!m.present)&&v(`
3781
+ run \`${hs} ext extras install\` to fetch them into ${lg()}.`)}),cg.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await Ei();if(d.every(N=>N.present)){v(Ke.success("extras already installed \u2014 nothing to do."));return}let m=lg();await be.mkdir(m,{recursive:!0});let _=d.filter(N=>!N.present).map(N=>N.name),T=Iu(process.platform,process.arch),x=async(N,L)=>{let{code:D,stderr:H}=await ki("npm",["install","--prefix",m,"--no-audit","--no-fund",...N]);D!==0&&k(`extras install failed while installing ${L} (npm exited ${D}).
3775
3782
  ${H.trim()}
3776
- These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},y=_.filter(N=>N!=="isolated-vm");if(y.length>0){let N=y.map(L=>`${L}@${Eu[L]??"latest"}`);v(`installing ${N.join(", ")} \u2192 ${m}/node_modules \u2026`),await x(N,y.join(", "))}if(_.includes("isolated-vm")){let N=`isolated-vm@${Eu["isolated-vm"]}`;if(v(`installing ${N} \u2192 ${m}/node_modules \u2026`),await x(["--ignore-scripts",N],"isolated-vm"),Fb.includes(T)){let D=`${Ru}@${nT()}`;v(`fetching ${D} (no upstream binary for ${T}) \u2026`);let{code:H}=await ki("npm",["install","--prefix",m,"--no-audit","--no-fund","--ignore-scripts",D]);H!==0&&v(Ke.warn(`could not fetch ${D} \u2014 falling back to a source build.`))}let L=await Hb({home:m});L.length>0&&v(` ${Ke.success("prebuilt")} ${L.join(", ")} \u2192 isolated-vm/prebuilds/${T}`)}let S=await Ei(),R=S.filter(N=>!N.present).map(N=>N.name);if(R.includes("isolated-vm")){v(Ke.warn(`no prebuilt isolated-vm for ${T} / Node ${process.versions.node} (${Au()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:N}=await ki("npm",["rebuild","--prefix",m,"isolated-vm"]);N===0&&(S=await Ei(),R=S.filter(L=>!L.present).map(L=>L.name))}R.length>0&&k(`npm succeeded but ${R.join(", ")} still will not load \u2014 no prebuilt binary for ${T} / Node ${process.versions.node} (${Au()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),v(Ke.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let Qn=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return Qn.command("deploy").description("Enqueue a server-side release deploy. UPLOADS the SDF project src/ from the checkout (the producer swap) when present; else a solution-only live-fetch deploy. An approved target requires --approved-by.").requiredOption("--target <mode>","Deploy posture: auto (apply now) | approved (needs a recorded approval).").option("--solution <id>","The solution id the release delivers (omit for an upload-only deploy).").option("--project <dir>","SDF project dir whose src/ is uploaded (default: cwd).").option("--git-repo <repo>","Git provenance LINK: source repo (default $GITHUB_REPOSITORY or `git remote get-url origin`).").option("--git-ref <ref>","Git provenance LINK: ref/branch/tag (default $GITHUB_REF).").option("--ref <committish>","Git provenance: the ref/branch/tag/sha the upload was built from; resolved to a commit sha via `git rev-parse` (default $GITHUB_SHA or HEAD).").option("--pr-url <url>","Git provenance LINK: the PR this deploy came from (default $PR_URL).").option("--approved-by <email>","Record the approval (REQUIRED for --target approved).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async d=>{let m=d.target==="approved"?"approved":d.target==="auto"?"auto":null;m||k(`--target must be 'auto' or 'approved' (got '${d.target}').`);let _=await VM(ge(process.cwd(),d.project??".")),T=Object.keys(_).length;!d.solution&&T===0&&k("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let y=(d.ref?await tg(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await tg(["rev-parse","HEAD"]),S=d.gitRepo??process.env.GITHUB_REPOSITORY??await tg(["remote","get-url","origin"]),R=d.gitRef??process.env.GITHUB_REF??null,N=d.prUrl??process.env.PR_URL??null,{baseUrl:L,token:D}=await ne(d.baseUrl),H=new ee({baseUrl:L,token:D}),j;try{j=await H.releaseDeploy({solutionId:d.solution??null,target:m,approvedBy:d.approvedBy??null,files:T>0?_:null,gitRepo:S,gitRef:R,gitSha:y,prUrl:N})}catch(Q){se(Q,"releases:write","release deploy"),Q instanceof le&&Q.status===404&&k("solution_not_found \u2014 no solution with that id."),k(`release deploy failed: ${Q instanceof Error?Q.message:String(Q)}`)}v(`release ${j.releaseId} enqueued \u2192 taskId=${j.taskId} (target=${m}`+(T>0?`, uploaded ${T} bundle file(s)`:", live-fetch")+")."),d.follow&&await wu(()=>H.releaseStatus(j.releaseId),`release ${j.releaseId}`,d.intervalMs)}),Qn.command("pull").argument("<id>","The release id").description("Write the SDF project a FAILED release built into <dir>: owned/ (yours, editable) and context/ (the rest of the bundle, read-only). Edit owned/, then `release push`.").requiredOption("--dir <path>","Directory to write the project into (created if absent).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,m)=>{let{baseUrl:_,token:T}=await ne(m.baseUrl),x=new ee({baseUrl:_,token:T}),y;try{y=await x.releaseFiles(d)}catch(N){N instanceof le&&N.status===404&&k(`release ${d} not found.`),N instanceof le&&N.status===409&&k(`no built project was retained for release ${d}. Files are kept for a FAILED attempt only \u2014 a shipped bundle is recoverable from the account.`),se(N,"releases:write","pull a release"),k(`release pull failed: ${N instanceof Error?N.message:String(N)}`)}let S=ge(process.cwd(),m.dir),R=0;for(let[N,L]of[["owned",y.owned],["context",y.context]])for(let[D,H]of Object.entries(L)){let j=Ot(S,N,D);await be.mkdir(Lr(j),{recursive:!0}),await be.writeFile(j,H,"utf8"),R++}await be.writeFile(Ot(S,".turbobase-release.json"),JSON.stringify({releaseId:y.releaseId,version:y.version,contentDigest:y.contentDigest},null,2),"utf8"),v(`pulled release ${y.releaseId} (${y.status}) \u2192 ${S}
3783
+ These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},y=_.filter(N=>N!=="isolated-vm");if(y.length>0){let N=y.map(L=>`${L}@${Pu[L]??"latest"}`);v(`installing ${N.join(", ")} \u2192 ${m}/node_modules \u2026`),await x(N,y.join(", "))}if(_.includes("isolated-vm")){let N=`isolated-vm@${Pu["isolated-vm"]}`;if(v(`installing ${N} \u2192 ${m}/node_modules \u2026`),await x(["--ignore-scripts",N],"isolated-vm"),Kb.includes(T)){let D=`${Au}@${iT()}`;v(`fetching ${D} (no upstream binary for ${T}) \u2026`);let{code:H}=await ki("npm",["install","--prefix",m,"--no-audit","--no-fund","--ignore-scripts",D]);H!==0&&v(Ke.warn(`could not fetch ${D} \u2014 falling back to a source build.`))}let L=await Wb({home:m});L.length>0&&v(` ${Ke.success("prebuilt")} ${L.join(", ")} \u2192 isolated-vm/prebuilds/${T}`)}let S=await Ei(),R=S.filter(N=>!N.present).map(N=>N.name);if(R.includes("isolated-vm")){v(Ke.warn(`no prebuilt isolated-vm for ${T} / Node ${process.versions.node} (${Ou()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:N}=await ki("npm",["rebuild","--prefix",m,"isolated-vm"]);N===0&&(S=await Ei(),R=S.filter(L=>!L.present).map(L=>L.name))}R.length>0&&k(`npm succeeded but ${R.join(", ")} still will not load \u2014 no prebuilt binary for ${T} / Node ${process.versions.node} (${Ou()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),v(Ke.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let Qn=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return Qn.command("deploy").description("Enqueue a server-side release deploy. UPLOADS the SDF project src/ from the checkout (the producer swap) when present; else a solution-only live-fetch deploy. An approved target requires --approved-by.").requiredOption("--target <mode>","Deploy posture: auto (apply now) | approved (needs a recorded approval).").option("--solution <id>","The solution id the release delivers (omit for an upload-only deploy).").option("--project <dir>","SDF project dir whose src/ is uploaded (default: cwd).").option("--git-repo <repo>","Git provenance LINK: source repo (default $GITHUB_REPOSITORY or `git remote get-url origin`).").option("--git-ref <ref>","Git provenance LINK: ref/branch/tag (default $GITHUB_REF).").option("--ref <committish>","Git provenance: the ref/branch/tag/sha the upload was built from; resolved to a commit sha via `git rev-parse` (default $GITHUB_SHA or HEAD).").option("--pr-url <url>","Git provenance LINK: the PR this deploy came from (default $PR_URL).").option("--approved-by <email>","Record the approval (REQUIRED for --target approved).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async d=>{let m=d.target==="approved"?"approved":d.target==="auto"?"auto":null;m||k(`--target must be 'auto' or 'approved' (got '${d.target}').`);let _=await XM(ge(process.cwd(),d.project??".")),T=Object.keys(_).length;!d.solution&&T===0&&k("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let y=(d.ref?await ng(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await ng(["rev-parse","HEAD"]),S=d.gitRepo??process.env.GITHUB_REPOSITORY??await ng(["remote","get-url","origin"]),R=d.gitRef??process.env.GITHUB_REF??null,N=d.prUrl??process.env.PR_URL??null,{baseUrl:L,token:D}=await ne(d.baseUrl),H=new ee({baseUrl:L,token:D}),j;try{j=await H.releaseDeploy({solutionId:d.solution??null,target:m,approvedBy:d.approvedBy??null,files:T>0?_:null,gitRepo:S,gitRef:R,gitSha:y,prUrl:N})}catch(Q){se(Q,"releases:write","release deploy"),Q instanceof le&&Q.status===404&&k("solution_not_found \u2014 no solution with that id."),k(`release deploy failed: ${Q instanceof Error?Q.message:String(Q)}`)}v(`release ${j.releaseId} enqueued \u2192 taskId=${j.taskId} (target=${m}`+(T>0?`, uploaded ${T} bundle file(s)`:", live-fetch")+")."),d.follow&&await _u(()=>H.releaseStatus(j.releaseId),`release ${j.releaseId}`,d.intervalMs)}),Qn.command("pull").argument("<id>","The release id").description("Write the SDF project a FAILED release built into <dir>: owned/ (yours, editable) and context/ (the rest of the bundle, read-only). Edit owned/, then `release push`.").requiredOption("--dir <path>","Directory to write the project into (created if absent).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,m)=>{let{baseUrl:_,token:T}=await ne(m.baseUrl),x=new ee({baseUrl:_,token:T}),y;try{y=await x.releaseFiles(d)}catch(N){N instanceof le&&N.status===404&&k(`release ${d} not found.`),N instanceof le&&N.status===409&&k(`no built project was retained for release ${d}. Files are kept for a FAILED attempt only \u2014 a shipped bundle is recoverable from the account.`),se(N,"releases:write","pull a release"),k(`release pull failed: ${N instanceof Error?N.message:String(N)}`)}let S=ge(process.cwd(),m.dir),R=0;for(let[N,L]of[["owned",y.owned],["context",y.context]])for(let[D,H]of Object.entries(L)){let j=Ot(S,N,D);await be.mkdir(Lr(j),{recursive:!0}),await be.writeFile(j,H,"utf8"),R++}await be.writeFile(Ot(S,".turbobase-release.json"),JSON.stringify({releaseId:y.releaseId,version:y.version,contentDigest:y.contentDigest},null,2),"utf8"),v(`pulled release ${y.releaseId} (${y.status}) \u2192 ${S}
3777
3784
  ${Object.keys(y.owned).length} owned file(s), ${Object.keys(y.context).length} context file(s), ${R} total
3778
3785
  `+(y.logTail?`
3779
3786
  the failure these bytes produced:
@@ -3784,9 +3791,9 @@ edit the files under owned/, then:
3784
3791
  `+N.map(j=>` context/${j}`).join(`
3785
3792
  `)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let L={...S.context},D=0;for(let[j,Q]of Object.entries(S.owned)){let ve=await R("owned",j);L[j]=ve??Q,ve!==null&&ve!==Q&&D++}D===0&&v("nothing changed under owned/ \u2014 pushing the same bytes the release already built.");let H=m.target==="approved"?"approved":"auto";try{let j=await x.releasePush(d,{files:L,target:H,...m.approvedBy?{approvedBy:m.approvedBy}:{}});v(`pushed ${Object.keys(L).length} file(s) (${D} edited) \u2192 release ${j.releaseId} (task ${j.taskId}).
3786
3793
  follow it with:
3787
- turbobase release status ${j.releaseId} --follow`)}catch(j){j instanceof le&&j.status===403&&k("an approved target needs --approved-by (the deploy gate fails closed)."),j instanceof le&&j.status===409&&k("that solution already has an active release \u2014 roll it back or wait for it."),se(j,"releases:write","push a release"),k(`release push failed: ${j instanceof Error?j.message:String(j)}`)}}),Qn.command("status").argument("<id>","The release id").description("Show a release deploy job's status; with --follow, poll to completion.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async(d,m)=>{let{baseUrl:_,token:T}=await ne(m.baseUrl),x=new ee({baseUrl:_,token:T});if(m.follow){await wu(()=>x.releaseStatus(d),`release ${d}`,m.intervalMs);return}let y;try{y=await x.releaseStatus(d)}catch(S){se(S,"releases:write","release status"),S instanceof le&&S.status===404&&k(`release ${d} not found.`),k(`release status failed: ${S instanceof Error?S.message:String(S)}`)}v(`release ${d}: status=${y.releaseStatus??"?"} stage=${y.stage} ${y.percent}%`+(y.runStatus?` (${y.runStatus})`:"")),y.outputTail&&v(y.outputTail.replace(/\n+$/,""))}),Qn.command("rollback").argument("<id>","The release id to roll back").description("Roll back a live release (LIFO-guarded; server-side reverse deploy).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,m)=>{let{baseUrl:_,token:T}=await ne(m.baseUrl),x=new ee({baseUrl:_,token:T}),y;try{y=await x.releaseRollback(d)}catch(S){se(S,"releases:write","release rollback"),S instanceof le&&S.status===404&&k(`release ${d} not found.`),S instanceof le&&S.status===409&&k(`release ${d} cannot be rolled back (not live, or a newer release advanced past it).`),k(`release rollback failed: ${S instanceof Error?S.message:String(S)}`)}v(`release ${y.releaseId} rolled back \u2192 status=${y.release?.status??"rolled_back"}.`)}),Qn.command("list").description("List releases, newest-first, with delivered titles + latest status.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async d=>{let{baseUrl:m,token:_}=await ne(d.baseUrl),T=new ee({baseUrl:m,token:_}),x;try{x=await T.releaseList()}catch(y){se(y,"releases:write","release list"),k(`release list failed: ${y instanceof Error?y.message:String(y)}`)}if(x.length===0){v("no releases.");return}if(tt())v(Qt(x.map(y=>[y.id,ho(y.status),y.target,y.backend,y.solutionTitles?.length?y.solutionTitles.map(S=>`"${S}"`).join(", "):g.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let y of x){let S=y.solutionTitles?.length?` "${y.solutionTitles.join('", "')}"`:"";v(` ${y.id} ${y.status.padEnd(11)} target=${y.target} backend=${y.backend}${S}`)}v(`
3788
- ${x.length} release(s).`)}),e.command("logs").description("Read the platform event log \u2014 guardrails, hooks, scheduled tasks, conduits and sync in one stream. Absorbs the old `ext logs` via --extension / --conduit.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--subsystem <s>","guardrails | hooks | tasks | conduits | sync").option("--severity <s>","Minimum severity: debug | info | warn | error (a THRESHOLD \u2014 `warn` includes errors).").option("--code <code>","One event code, e.g. guardrails.write_denied").option("--since <window>","Relative window (10m, 2h, 3d) or an ISO timestamp.").option("--correlation-id <id>","Follow one root action across every subsystem it touched.").option("--extension <id>","One extension's own log ring buffer (was `ext logs <id>`).").option("--conduit <id>","One conduit's run ledger (was `ext logs <id> --follow`).").option("--follow","Poll for new rows and print them as they land.").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").option("--limit <n>","Max rows on the first read (default 100, max 500).").option("--json","Emit raw rows as JSON, one per line.").action(async d=>{let{baseUrl:m,token:_}=await ne(d.baseUrl),T=new ee({baseUrl:m,token:_}),x=d.limit?Number(d.limit):void 0,y=d.intervalMs?Number(d.intervalMs):void 0;if(d.conduit){try{await Dy(T,d.conduit,{...d.follow?{follow:!0}:{},...x!==void 0?{limit:x}:{},...y!==void 0?{intervalMs:y}:{},sink:v})}catch(S){k(`logs --conduit failed: ${S instanceof Error?S.message:String(S)}`)}return}if(d.extension){try{let S=await T.logs(d.extension,x);S.length===0&&v(`no logs for ${d.extension}.`);for(let R of S)v(` [${R.level}] ${R.ts??""} ${R.message}`)}catch(S){k(`logs --extension failed: ${S instanceof Error?S.message:String(S)}`)}return}try{await Uy(T,{...d.subsystem?{subsystem:d.subsystem}:{},...d.severity?{severity:d.severity}:{},...d.code?{code:d.code}:{},...d.since?{since:d.since}:{},...d.correlationId?{correlationId:d.correlationId}:{},...d.follow?{follow:!0}:{},...d.json?{json:!0}:{},...x!==void 0?{limit:x}:{},...y!==void 0?{intervalMs:y}:{},sink:v})}catch(S){k(`logs failed: ${S instanceof Error?S.message:String(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 d=>{let{runAuthoringMcpServer:m}=await Promise.resolve().then(()=>(XS(),YS));await m({baseUrl:d.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(`
3789
- `)),t&&void 0,e}function qM(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 BM(t){let e=Ot(ge(process.cwd(),t),"public","turbobase.json"),r=await be.readFile(e,"utf8").catch(()=>null);if(r===null)return null;let n;try{n=JSON.parse(r)}catch(o){k(`${e} is not valid JSON: ${o instanceof Error?o.message:String(o)}`)}return(typeof n!="object"||n===null||Array.isArray(n))&&k(`${e} must be a JSON object.`),{manifest:n,manifestPath:e}}async function ZM(){let t=ge(process.cwd(),ia,ds),e;try{e=await be.readFile(t,"utf8")}catch{k(`no config found \u2014 this project authors none (no ${ca}/, ${la}/, ${Kr} or ${Wr}) and there is no ${ia}/${ds}.
3790
- Author a hook with \`turbobase ext new hook\`, or adopt an existing instance with \`turbobase ext export\`.`)}try{return Yy(e)}catch(r){k(`bundle is invalid: ${r instanceof Error?r.message:String(r)}`)}}async function Qm(){let t=process.cwd();if(!await tb(t))return ZM();let e;try{e=await rb(t,{inline:ou})}catch(r){k(`could not build the config bundle from this project: ${r instanceof Error?r.message:String(r)}`)}for(let r of e.unparsed)q(`${r.file}: ${r.reason} \u2014 NOT included in the plan.`);return e.unparsed.length>0&&k(`${e.unparsed.length} extension file(s) could not be identified. Every hook/conduit needs a literal \`id:\`, \`recordType:\` and \`event:\`/\`on:\` \u2014 run \`turbobase ext lint <file>\` on each.`),e.manifest}function FM(t,e){v(`plan against ${e}:`);for(let r of t.add)v(` ${Hr.add(`${r.kind} ${r.id}`)}`);for(let r of t.change)v(` ${Hr.change(`${r.kind} ${r.id}`)}`);for(let r of t.destroy)v(` ${Hr.destroy(`${r.kind} ${r.id}`)}`);v(`
3791
- ${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 HM(t){try{let r=new URL(t).hostname.split(".")[0];return r&&r!=="localhost"?r:void 0}catch{return}}function ki(t,e,r){return new Promise(n=>{let o=ng(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 eg(){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 ki("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 ki("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 VM(t){let e=ge(t,"src"),r={},n=async o=>{let s;try{s=await be.readdir(o,{withFileTypes:!0})}catch{return}for(let i of s){let a=Ot(o,i.name);if(i.isDirectory())await n(a);else if(i.isFile()){let c=dl(e,a).split(rg).join("/");r[c]=await be.readFile(a,"utf8")}}};return await n(e),r}function tg(t){return new Promise(e=>{let r=ng("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 KM=!1;KM&&og().parseAsync(process.argv).catch(t=>k(t instanceof Error?t.message:String(t)));og().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
3794
+ turbobase release status ${j.releaseId} --follow`)}catch(j){j instanceof le&&j.status===403&&k("an approved target needs --approved-by (the deploy gate fails closed)."),j instanceof le&&j.status===409&&k("that solution already has an active release \u2014 roll it back or wait for it."),se(j,"releases:write","push a release"),k(`release push failed: ${j instanceof Error?j.message:String(j)}`)}}),Qn.command("status").argument("<id>","The release id").description("Show a release deploy job's status; with --follow, poll to completion.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async(d,m)=>{let{baseUrl:_,token:T}=await ne(m.baseUrl),x=new ee({baseUrl:_,token:T});if(m.follow){await _u(()=>x.releaseStatus(d),`release ${d}`,m.intervalMs);return}let y;try{y=await x.releaseStatus(d)}catch(S){se(S,"releases:write","release status"),S instanceof le&&S.status===404&&k(`release ${d} not found.`),k(`release status failed: ${S instanceof Error?S.message:String(S)}`)}v(`release ${d}: status=${y.releaseStatus??"?"} stage=${y.stage} ${y.percent}%`+(y.runStatus?` (${y.runStatus})`:"")),y.outputTail&&v(y.outputTail.replace(/\n+$/,""))}),Qn.command("rollback").argument("<id>","The release id to roll back").description("Roll back a live release (LIFO-guarded; server-side reverse deploy).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,m)=>{let{baseUrl:_,token:T}=await ne(m.baseUrl),x=new ee({baseUrl:_,token:T}),y;try{y=await x.releaseRollback(d)}catch(S){se(S,"releases:write","release rollback"),S instanceof le&&S.status===404&&k(`release ${d} not found.`),S instanceof le&&S.status===409&&k(`release ${d} cannot be rolled back (not live, or a newer release advanced past it).`),k(`release rollback failed: ${S instanceof Error?S.message:String(S)}`)}v(`release ${y.releaseId} rolled back \u2192 status=${y.release?.status??"rolled_back"}.`)}),Qn.command("list").description("List releases, newest-first, with delivered titles + latest status.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async d=>{let{baseUrl:m,token:_}=await ne(d.baseUrl),T=new ee({baseUrl:m,token:_}),x;try{x=await T.releaseList()}catch(y){se(y,"releases:write","release list"),k(`release list failed: ${y instanceof Error?y.message:String(y)}`)}if(x.length===0){v("no releases.");return}if(tt())v(Qt(x.map(y=>[y.id,ho(y.status),y.target,y.backend,y.solutionTitles?.length?y.solutionTitles.map(S=>`"${S}"`).join(", "):g.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let y of x){let S=y.solutionTitles?.length?` "${y.solutionTitles.join('", "')}"`:"";v(` ${y.id} ${y.status.padEnd(11)} target=${y.target} backend=${y.backend}${S}`)}v(`
3795
+ ${x.length} release(s).`)}),e.command("logs").description("Read the platform event log \u2014 guardrails, hooks, scheduled tasks, conduits and sync in one stream. Absorbs the old `ext logs` via --extension / --conduit.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--subsystem <s>","guardrails | hooks | tasks | conduits | sync").option("--severity <s>","Minimum severity: debug | info | warn | error (a THRESHOLD \u2014 `warn` includes errors).").option("--code <code>","One event code, e.g. guardrails.write_denied").option("--since <window>","Relative window (10m, 2h, 3d) or an ISO timestamp.").option("--correlation-id <id>","Follow one root action across every subsystem it touched.").option("--extension <id>","One extension's own log ring buffer (was `ext logs <id>`).").option("--conduit <id>","One conduit's run ledger (was `ext logs <id> --follow`).").option("--follow","Poll for new rows and print them as they land.").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").option("--limit <n>","Max rows on the first read (default 100, max 500).").option("--json","Emit raw rows as JSON, one per line.").action(async d=>{let{baseUrl:m,token:_}=await ne(d.baseUrl),T=new ee({baseUrl:m,token:_}),x=d.limit?Number(d.limit):void 0,y=d.intervalMs?Number(d.intervalMs):void 0;if(d.conduit){try{await qy(T,d.conduit,{...d.follow?{follow:!0}:{},...x!==void 0?{limit:x}:{},...y!==void 0?{intervalMs:y}:{},sink:v})}catch(S){k(`logs --conduit failed: ${S instanceof Error?S.message:String(S)}`)}return}if(d.extension){try{let S=await T.logs(d.extension,x);S.length===0&&v(`no logs for ${d.extension}.`);for(let R of S)v(` [${R.level}] ${R.ts??""} ${R.message}`)}catch(S){k(`logs --extension failed: ${S instanceof Error?S.message:String(S)}`)}return}try{await Zy(T,{...d.subsystem?{subsystem:d.subsystem}:{},...d.severity?{severity:d.severity}:{},...d.code?{code:d.code}:{},...d.since?{since:d.since}:{},...d.correlationId?{correlationId:d.correlationId}:{},...d.follow?{follow:!0}:{},...d.json?{json:!0}:{},...x!==void 0?{limit:x}:{},...y!==void 0?{intervalMs:y}:{},sink:v})}catch(S){k(`logs failed: ${S instanceof Error?S.message:String(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 d=>{let{runAuthoringMcpServer:m}=await Promise.resolve().then(()=>(tT(),eT));await m({baseUrl:d.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(`
3796
+ `)),t&&void 0,e}function KM(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 WM(t){let e=Ot(ge(process.cwd(),t),"public","turbobase.json"),r=await be.readFile(e,"utf8").catch(()=>null);if(r===null)return null;let n;try{n=JSON.parse(r)}catch(o){k(`${e} is not valid JSON: ${o instanceof Error?o.message:String(o)}`)}return(typeof n!="object"||n===null||Array.isArray(n))&&k(`${e} must be a JSON object.`),{manifest:n,manifestPath:e}}async function GM(){let t=ge(process.cwd(),ca,ds),e;try{e=await be.readFile(t,"utf8")}catch{k(`no config found \u2014 this project authors none (no ${ua}/, ${da}/, ${Kr} or ${Wr}) and there is no ${ca}/${ds}.
3797
+ Author a hook with \`turbobase ext new hook\`, or adopt an existing instance with \`turbobase ext export\`.`)}try{return eb(e)}catch(r){k(`bundle is invalid: ${r instanceof Error?r.message:String(r)}`)}}async function tg(){let t=process.cwd();if(!await ob(t))return GM();let e;try{e=await sb(t,{inline:iu})}catch(r){k(`could not build the config bundle from this project: ${r instanceof Error?r.message:String(r)}`)}for(let r of e.unparsed)q(`${r.file}: ${r.reason} \u2014 NOT included in the plan.`);return e.unparsed.length>0&&k(`${e.unparsed.length} extension file(s) could not be identified. Every hook/conduit needs a literal \`id:\`, \`recordType:\` and \`event:\`/\`on:\` \u2014 run \`turbobase ext lint <file>\` on each.`),e.manifest}function JM(t,e){v(`plan against ${e}:`);for(let r of t.add)v(` ${Hr.add(`${r.kind} ${r.id}`)}`);for(let r of t.change)v(` ${Hr.change(`${r.kind} ${r.id}`)}`);for(let r of t.destroy)v(` ${Hr.destroy(`${r.kind} ${r.id}`)}`);v(`
3798
+ ${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 YM(t){try{let r=new URL(t).hostname.split(".")[0];return r&&r!=="localhost"?r:void 0}catch{return}}function ki(t,e,r){return new Promise(n=>{let o=sg(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 rg(){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 ki("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 ki("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 XM(t){let e=ge(t,"src"),r={},n=async o=>{let s;try{s=await be.readdir(o,{withFileTypes:!0})}catch{return}for(let i of s){let a=Ot(o,i.name);if(i.isDirectory())await n(a);else if(i.isFile()){let c=hl(e,a).split(og).join("/");r[c]=await be.readFile(a,"utf8")}}};return await n(e),r}function ng(t){return new Promise(e=>{let r=sg("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 QM=!1;QM&&ig().parseAsync(process.argv).catch(t=>k(t instanceof Error?t.message:String(t)));ig().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
3792
3799
  `),process.exit(1)});