@turbobase/cli 1.1.10 → 1.1.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +5 -5
- package/README.md +13 -13
- package/dist/turbobase-standalone.mjs +355 -250
- package/dist/turbobase.js +337 -232
- package/package.json +2 -2
package/dist/turbobase.js
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
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
|
|
4
|
+
var ag=Object.create;var Ko=Object.defineProperty;var cg=Object.getOwnPropertyDescriptor;var lg=Object.getOwnPropertyNames;var dg=Object.getPrototypeOf,ug=Object.prototype.hasOwnProperty;var N=(t,e)=>()=>(t&&(e=t(t=0)),e);var j=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ql=(t,e)=>{for(var r in e)Ko(t,r,{get:e[r],enumerable:!0})},pg=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of lg(e))!ug.call(t,s)&&s!==r&&Ko(t,s,{get:()=>e[s],enumerable:!(n=cg(e,s))||n.enumerable});return t};var Ml=(t,e,r)=>(r=t!=null?ag(dg(t)):{},pg(e||!t||!t.__esModule?Ko(r,"default",{value:t,enumerable:!0}):r,t));function Jr(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var rs=N(()=>{});import{z as Yt}from"zod";function ns(t){let e=Vo.safeParse(t);return e.success?(e.data.inputs??[]).filter(r=>r.type==="connection"):[]}function Go(t,e){let r=Vo.safeParse(t);if(!r.success)throw new At(`invalid manifest: ${r.error.issues.map(s=>`${s.path.join(".")||"(root)"}: ${s.message}`).join("; ")}`);if(Bl.test(e))throw new At('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(Bl.test(n))throw new At("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var Fl,Hl,Vo,At,Bl,Kl=N(()=>{Fl=Yt.object({type:Yt.literal("connection"),source_system:Yt.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:Yt.string().min(1).max(200).optional()}),Hl=Yt.discriminatedUnion("type",[Fl]),Vo=Yt.object({inputs:Yt.array(Hl).optional()}).passthrough(),At=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};Bl=/\bconnection[_-]?id\b["']?\s*[:=]/i});var ss,Wo=N(()=>{ss=["before_read","before_save","after_save","before_sync","after_sync","on_sync_failure"]});import{z as Oe}from"zod";var Jo,Vl,Gl=N(()=>{rs();Wo();Jo=Oe.object({id:Oe.string().min(1,"hook id must be non-empty"),recordType:Oe.union([Oe.string().min(1),Oe.array(Oe.string().min(1)).min(1),Oe.literal("*")]),event:Oe.enum(ss),source:Oe.string().min(1).optional(),when:Oe.unknown().optional(),run:Oe.unknown(),failClosed:Oe.boolean().optional(),timeoutMs:Oe.number().int().positive().optional(),description:Oe.string().optional(),systemReserved:Oe.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"})}),Vl=Jr({kind:"hook",schema:Jo,factoryName:"defineHook"})});var Wl=N(()=>{Gl();Wo()});var os,Zo=N(()=>{os=["after_canonicalize_inbound","after_sync_success_outbound"]});import{z as ke}from"zod";var Yo,Jl,Zl=N(()=>{rs();Zo();Yo=ke.object({id:ke.string().min(1,"conduit id must be non-empty"),on:ke.enum(os),from:ke.object({source:ke.string().min(1,"from.source must be non-empty"),recordType:ke.string().min(1,"from.recordType must be non-empty"),when:ke.unknown().optional()}),to:ke.object({source:ke.string().min(1,"to.source must be non-empty"),recordType:ke.string().min(1,"to.recordType must be non-empty")}),mode:ke.enum(["dual-bind","one-shot"]).optional(),transform:ke.unknown(),idempotencyKey:ke.unknown().optional(),cycleBudget:ke.number().int().positive().optional(),conflictStrategy:ke.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:ke.number().int().positive().optional(),description:ke.string().optional(),systemReserved:ke.boolean().optional()}).superRefine((t,e)=>{typeof t.transform!="function"&&e.addIssue({code:"custom",path:["transform"],message:"transform must be a function"});let r=t.from?.when;r!==void 0&&typeof r!="function"&&e.addIssue({code:"custom",path:["from","when"],message:"from.when, when present, must be a function"});let n=t.idempotencyKey;n!==void 0&&typeof n!="function"&&e.addIssue({code:"custom",path:["idempotencyKey"],message:"idempotencyKey, when present, must be a function"});let s=t.from,o=t.to;s?.source&&o?.source&&s.source===o.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"})}),Jl=Jr({kind:"conduit",schema:Yo,factoryName:"defineConduit"})});var Yl=N(()=>{Zl();Zo()});async function yg(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 is(t,e={}){return(e.transform??yg)(t)}var Qo=N(()=>{});function Xo(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 Ql(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function ei(t){return`${Ql(t.source)}${Ql(t.recordType)}`}function bg(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function wg(t){let e=[t.pgType];return t.label&&e.push(`"${t.label}"`),t.role==="display"&&t.displayFor?e.push(`display column for ${t.displayFor} \u2014 render this, filter/join on ${t.displayFor}`):t.role==="identifier"&&t.idFor?e.push(`identifier \u2014 render ${t.idFor} instead`):t.role&&e.push(t.role),t.format&&e.push(`format: ${t.format}`),t.description&&e.push(t.description),e.join(" \xB7 ")}function ti(t){let e=ei(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]} */`:`/**
|
|
5
5
|
* ${r.join(`
|
|
6
6
|
* `)}
|
|
7
7
|
*/`;if(t.columns.length===0)return`${n}
|
|
8
8
|
export interface ${e} {
|
|
9
9
|
// no columns introspected
|
|
10
10
|
[key: string]: unknown;
|
|
11
|
-
}`;let s=t.columns.map(o=>{let i=
|
|
12
|
-
${
|
|
11
|
+
}`;let s=t.columns.map(o=>{let i=Xo(o.pgType),a=o.nullable?"?":"",l=o.nullable?" | null":"";return` /** ${wg(o)} */
|
|
12
|
+
${bg(o.name)}${a}: ${i}${l};`});return`${n}
|
|
13
13
|
export interface ${e} {
|
|
14
14
|
${s.join(`
|
|
15
15
|
`)}
|
|
16
|
-
}`}function
|
|
16
|
+
}`}function as(t){return[...t.records].sort((n,s)=>`${n.source}:${n.recordType}`.localeCompare(`${s.source}:${s.recordType}`)).map(ti).join(`
|
|
17
17
|
|
|
18
|
-
`)}var
|
|
18
|
+
`)}var ri=N(()=>{});function vg(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function Xl(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 It(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let r=vg(t.baseUrl),n=await Xl(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 s=as(n),o=[Sg,"// ----- Record shapes (from /v1/catalog/records) -----",s];if(!t.recordsOnly){let i=await Xl(r.openapi,t.token,e),a=await is(i,t.openApi);o.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return o.join(`
|
|
19
19
|
|
|
20
20
|
`)+`
|
|
21
|
-
`}var
|
|
22
|
-
`)});var
|
|
23
|
-
`,{mode:384})}async function Ql(t){let e=Ve(t.baseUrl),r=await Wr(),n=new Date().toISOString();return r.tenants[e]={token:t.token,updatedAt:n},r.active=e,await ti(r),{baseUrl:e,token:t.token,updatedAt:n}}async function pt(t){let e=await Wr();if(t){let o=Ve(t),i=e.tenants[o];return i?{baseUrl:o,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 s=e.tenants[n];return{baseUrl:n,token:s.token,updatedAt:s.updatedAt}}async function is(t){let e=Ve(t),r=await Wr(),n=r.tenants[e];return n?(r.active=e,await ti(r),{baseUrl:e,token:n.token,updatedAt:n.updatedAt}):null}async function ri(t){let e=await Wr(),r=t?Ve(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 ti(e),r}async function Rt(){let t=await Wr();return Object.entries(t.tenants).map(([e,r])=>({baseUrl:e,token:r.token,updatedAt:r.updatedAt}))}var as=O(()=>{});function Xl(t){if(typeof t=="string")return t.trim().slice(0,200);if(!t||typeof t!="object")return"";let e=t,r=typeof e.message=="string"&&e.message?e.message:e.error;return typeof r=="string"?r.trim().slice(0,200):""}function ed(t){return t.replace(/\/+$/,"")}function ni(t=process.env){let e=(t[pr]??"").trim(),r=(t[cs]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function si(t){let e;try{e=new URL(t)}catch{return`${pr} 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:`${pr} must be https:// (got ${e.protocol}//${e.hostname}). The registry bearer is sent as an Authorization header and must not cross a plaintext connection.`}var pe,ae,pr,cs,Jr,Zr=O(()=>{pe=class extends Error{constructor(r,n,s){super(r);this.status=n;this.body=s;this.name="ApiError"}status;body};ae=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=ed(e.baseUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("ExtensionsApi: no fetch implementation available");this.fetchImpl=r}async request(e,r,n,s){let o=await this.fetchImpl(`${this.baseUrl}${r}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/json",...n!==void 0?{"Content-Type":"application/json"}:{},...s??{}},...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await o.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!o.ok){let l=Xl(a);throw new pe(`${e} ${r} \u2192 ${o.status}${l?`: ${l}`:""}`,o.status,a)}return a}deploy(e){return this.request("POST","/v1/extensions",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli",...e.connectionId?{connectionId:e.connectionId}:{}})}async list(e){let r=e?`?kind=${encodeURIComponent(e)}`:"";return(await this.request("GET",`/v1/extensions${r}`)).extensions??[]}test(e){return this.request("POST","/v1/extensions/test",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli"})}async logs(e,r){let n=r&&r>0?`?limit=${Math.floor(r)}`:"";return(await this.request("GET",`/v1/extensions/${encodeURIComponent(e)}/logs${n}`)).logs??[]}async catalogRecords(){return(await this.request("GET","/v1/catalog/records")).records??[]}async conduitEvents(e,r={}){let n=new URLSearchParams;r.since&&n.set("since",r.since),r.limit&&r.limit>0&&n.set("limit",String(Math.floor(r.limit)));let s=n.toString()?`?${n.toString()}`:"";return(await this.request("GET",`/v1/conduits/${encodeURIComponent(e)}/events${s}`)).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));let n=r.toString();return this.request("GET",`/v1/learnings/pending${n?`?${n}`:""}`)}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}:{}})}retryBinding(e){return this.request("POST",`/v1/bindings/${encodeURIComponent(e)}/retry`)}configExport(){return this.request("GET","/v1/config/export")}configPlan(e){return this.request("POST","/v1/config/plan",{bundle:e})}configApply(e){return this.request("POST","/v1/config/apply",{bundle:e})}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)}`)}releaseStatus(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/status`)}releaseRollback(e){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/rollback`)}},pr="TURBOBASE_REGISTRY_URL",cs="TURBOBASE_REGISTRY_TOKEN";Jr=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=ed(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 s={Authorization:`Bearer ${this.token}`,Accept:"application/json"};n!==void 0&&(s["Content-Type"]="application/json");let o=await this.fetchImpl(`${this.registryUrl}${r}`,{method:e,headers:s,...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await o.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!o.ok){let l=Xl(a);throw new pe(`${e} ${r} \u2192 ${o.status}${l?`: ${l}`:""}`,o.status,a)}return a}async list(){return(await this.request("GET","/extensions")).extensions??[]}fetchBundle(e,r){let n=r?`?version=${encodeURIComponent(r)}`:"";return this.request("GET",`/extensions/${encodeURIComponent(e)}${n}`)}publish(e){return this.request("POST","/extensions",{name:e.name,version:e.version,kind:e.kind,bundle:e.bundle,...e.manifest?{manifest:e.manifest}:{}})}}});function gg(t){if(mg.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function bg(){return{name:"extension-self-contained-fence",setup(t){t.onResolve({filter:/.*/},e=>e.kind==="entry-point"?null:gg(e.path)?{path:e.path,namespace:"extension-sdk"}:{errors:[{text:`extension ${e.path.startsWith(".")||e.path.startsWith("/")?`imports a sibling/local file ('${e.path}')`:e.path.startsWith("node:")||vg(e.path)?`imports a Node builtin ('${e.path}')`:`imports an external module ('${e.path}')`} \u2014 sandboxed extensions must be self-contained. The ONLY allowed import is the SDK factory ('@/sync/hooks' or '@turbobase/extensions'); inline everything else into the extension file.`}]}),t.onLoad({filter:/.*/,namespace:"extension-sdk"},()=>({contents:yg,loader:"js"}))}}}function vg(t){let e=t.startsWith("node:")?t.slice(5):t;return wg.has(e.split("/")[0])}function td(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 _g(){try{return(await import("esbuild")).build}catch(t){throw td("esbuild",t)}}async function Sg(){try{return(await import("isolated-vm")).default}catch(t){throw td("isolated-vm",t)}}async function ls(t){let e=await _g(),r;try{r=await e({stdin:{contents:t,loader:"ts",resolveDir:process.cwd(),sourcefile:"extension.ts"},bundle:!0,write:!1,format:"iife",globalName:"__tb_extension_module",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[bg()]})}catch(n){let o=n.errors?.map(i=>i.text).filter(Boolean).join("; ");throw new oi(o||`extension bundle failed: ${String(n)}`)}return r.outputFiles?.[0]?.text??""}async function Yr(t,e,r={}){let n=r.timeoutMs??200,s=r.memoryLimitMb??16,o=r.member??"run",i={patches:[],logs:[]},a=await Sg(),l=new a.Isolate({memoryLimit:s});try{let u=await l.createContext(),p=u.global,d=new a.Callback(N=>{let D=JSON.parse(String(N));i.rejection||(i.rejection=D)}),h=new a.Callback(N=>{i.patches.push(JSON.parse(String(N)))}),g=new a.Callback(N=>{let D=JSON.parse(String(N));i.logs.push(D)}),v=new a.Callback(N=>{i.result=JSON.parse(String(N))});await p.set("__tb_reject",d),await p.set("__tb_patch",h),await p.set("__tb_log",g),await p.set("__tb_result",v),await p.set("__tb_ctx_json",JSON.stringify($g(e)));let _=kg(t,o),P=await(await l.compileScript(_)).run(u,{timeout:n,promise:!0});return o==="when"?{effects:i,whenResult:!!P}:{effects:i}}finally{l.isDisposed||l.dispose()}}function $g(t){return{recordType:t.recordType,event:t.event,direction:t.direction,origin:t.origin,source:t.source,payload:t.payload??null,prior:t.prior??null,user:t.user??null,tenantConfig:t.tenantConfig??{},metadata:t.metadata??null,bindings:t.bindings??null,atlasLinks:t.atlasLinks??null}}function kg(t,e){return`
|
|
21
|
+
`}var Sg,ed=N(()=>{Qo();ri();ri();Qo();Sg=["/**"," * 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(`
|
|
22
|
+
`)});var ni=N(()=>{rs();Kl();Wl();Yl();ed()});import{homedir as _g}from"node:os";import{join as td}from"node:path";import{promises as si}from"node:fs";function Ge(t){return t.trim().replace(/\/+$/,"")}function nd(){let t=process.env.TURBOBASE_HOME??td(_g(),".turbobase");return{dir:t,file:td(t,"credentials")}}function rd(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function Zr(){let{file:t}=nd(),e;try{let o=await si.readFile(t,"utf8");e=JSON.parse(o)}catch(o){if(o.code==="ENOENT")return{tenants:{}};throw o}if(!e||typeof e!="object")return{tenants:{}};let r=e;if(r.tenants&&typeof r.tenants=="object"){let o={};for(let[a,l]of Object.entries(r.tenants))rd(l)&&(o[a]={token:l.token,updatedAt:l.updatedAt});return{active:typeof r.active=="string"&&o[r.active]?r.active:void 0,tenants:o}}let n={};for(let[o,i]of Object.entries(r))rd(i)&&(n[o]={token:i.token,updatedAt:i.updatedAt});return{active:$g(n),tenants:n}}function $g(t){let e,r="";for(let[n,s]of Object.entries(t))(!e||String(s.updatedAt)>r)&&(e=n,r=String(s.updatedAt));return e}async function oi(t){let{dir:e,file:r}=nd();await si.mkdir(e,{recursive:!0,mode:448}),await si.writeFile(r,JSON.stringify(t,null,2)+`
|
|
23
|
+
`,{mode:384})}async function sd(t){let e=Ge(t.baseUrl),r=await Zr(),n=new Date().toISOString();return r.tenants[e]={token:t.token,updatedAt:n},r.active=e,await oi(r),{baseUrl:e,token:t.token,updatedAt:n}}async function ht(t){let e=await Zr();if(t){let o=Ge(t),i=e.tenants[o];return i?{baseUrl:o,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 s=e.tenants[n];return{baseUrl:n,token:s.token,updatedAt:s.updatedAt}}async function cs(t){let e=Ge(t),r=await Zr(),n=r.tenants[e];return n?(r.active=e,await oi(r),{baseUrl:e,token:n.token,updatedAt:n.updatedAt}):null}async function ii(t){let e=await Zr(),r=t?Ge(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 oi(e),r}async function Ct(){let t=await Zr();return Object.entries(t.tenants).map(([e,r])=>({baseUrl:e,token:r.token,updatedAt:r.updatedAt}))}var ls=N(()=>{});function od(t){if(typeof t=="string")return t.trim().slice(0,200);if(!t||typeof t!="object")return"";let e=t,r=typeof e.message=="string"&&e.message?e.message:e.error;return typeof r=="string"?r.trim().slice(0,200):""}function id(t){return t.replace(/\/+$/,"")}function ai(t=process.env){let e=(t[hr]??"").trim(),r=(t[ds]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function ci(t){let e;try{e=new URL(t)}catch{return`${hr} 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:`${hr} 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 ue,K,hr,ds,Yr,mr=N(()=>{ue=class extends Error{constructor(r,n,s){super(r);this.status=n;this.body=s;this.name="ApiError"}status;body};K=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=id(e.baseUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("ExtensionsApi: no fetch implementation available");this.fetchImpl=r}async request(e,r,n,s){let o=await this.fetchImpl(`${this.baseUrl}${r}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/json",...n!==void 0?{"Content-Type":"application/json"}:{},...s??{}},...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await o.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!o.ok){let l=od(a);throw new ue(`${e} ${r} \u2192 ${o.status}${l?`: ${l}`:""}`,o.status,a)}return a}deploy(e){return this.request("POST","/v1/extensions",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli",...e.connectionId?{connectionId:e.connectionId}:{}})}async list(e){let r=e?`?kind=${encodeURIComponent(e)}`:"";return(await this.request("GET",`/v1/extensions${r}`)).extensions??[]}test(e){return this.request("POST","/v1/extensions/test",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli"})}async logs(e,r){let n=r&&r>0?`?limit=${Math.floor(r)}`:"";return(await this.request("GET",`/v1/extensions/${encodeURIComponent(e)}/logs${n}`)).logs??[]}async catalogRecords(){return(await this.request("GET","/v1/catalog/records")).records??[]}async conduitEvents(e,r={}){let n=new URLSearchParams;r.since&&n.set("since",r.since),r.limit&&r.limit>0&&n.set("limit",String(Math.floor(r.limit)));let s=n.toString()?`?${n.toString()}`:"";return(await this.request("GET",`/v1/conduits/${encodeURIComponent(e)}/events${s}`)).events??[]}async bindings(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/bindings${n}`)).bindings??[]}async appsList(){return(await this.request("GET","/v1/apps")).apps??[]}appsCreate(e){return this.request("POST","/v1/apps",{slug:e.slug,name:e.name??e.slug,description:e.description})}appsPull(e){return this.request("GET",`/v1/apps/${encodeURIComponent(e)}/pull`)}appPullContext(e){return this.request("GET",`/v1/apps/proposals/${encodeURIComponent(e)}/pull-context`)}appsPush(e,r,n={}){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/push`,{files:r,...n.note?{note:n.note}:{},...n.meta?{meta:n.meta}:{}},n.proposalId?{"x-proposal-id":n.proposalId}:void 0)}learningsPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.section&&r.set("section",e.section),e.limit!==void 0&&r.set("limit",String(e.limit)),e.group===!1&&r.set("group","false");let n=r.toString();return this.request("GET",`/v1/learnings/pending${n?`?${n}`:""}`)}rulesPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.limit!==void 0&&r.set("limit",String(e.limit));let n=r.toString();return this.request("GET",`/v1/learnings/rules-pending${n?`?${n}`:""}`)}rulesPush(e,r={}){return this.request("POST","/v1/learnings/push-rules",{planToken:e,...r.app?{app:r.app}:{},...r.limit!==void 0?{limit:r.limit}:{}})}learningsPushKb(e,r={}){return this.request("POST","/v1/learnings/push-kb",{planToken:e,...r.app?{app:r.app}:{},...r.section?{section:r.section}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{}})}retryBinding(e){return this.request("POST",`/v1/bindings/${encodeURIComponent(e)}/retry`)}configExport(){return this.request("GET","/v1/config/export")}configPlan(e){return this.request("POST","/v1/config/plan",{bundle:e})}configApply(e){return this.request("POST","/v1/config/apply",{bundle:e})}async tablesList(){return(await this.request("GET","/v1/tables")).tables??[]}tablesPlan(e){return this.request("POST","/v1/tables/plan",e)}tablesApply(e){return this.request("POST","/v1/tables/apply",e)}tablesDrop(e,r){return this.request("DELETE",`/v1/tables/${encodeURIComponent(e)}?confirm=${encodeURIComponent(r)}`)}async guardrailsList(){return(await this.request("GET","/v1/guardrails")).guardrails??[]}async guardrailCreate(e){return(await this.request("POST","/v1/guardrails",e)).guardrail}async guardrailUpdate(e,r){return(await this.request("PATCH",`/v1/guardrails/${encodeURIComponent(e)}`,r)).guardrail}guardrailDelete(e){return this.request("DELETE",`/v1/guardrails/${encodeURIComponent(e)}`)}guardrailTest(e){return this.request("POST","/v1/guardrails/test",e)}releaseDeploy(e){return this.request("POST","/v1/releases/deploy",{...e.solutionId?{solutionId:e.solutionId}:{},target:e.target,...e.approvedBy?{approvedBy:e.approvedBy}:{},...e.files?{files:e.files}:{},...e.gitRepo?{gitRepo:e.gitRepo}:{},...e.gitRef?{gitRef:e.gitRef}:{},...e.gitSha?{gitSha:e.gitSha}:{},...e.prUrl?{prUrl:e.prUrl}:{}})}async releaseList(){return(await this.request("GET","/v1/releases")).releases??[]}releaseGet(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}`)}releaseStatus(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/status`)}releaseRollback(e){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/rollback`)}},hr="TURBOBASE_REGISTRY_URL",ds="TURBOBASE_REGISTRY_TOKEN";Yr=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=id(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 s={Authorization:`Bearer ${this.token}`,Accept:"application/json"};n!==void 0&&(s["Content-Type"]="application/json");let o=await this.fetchImpl(`${this.registryUrl}${r}`,{method:e,headers:s,...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await o.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!o.ok){let l=od(a);throw new ue(`${e} ${r} \u2192 ${o.status}${l?`: ${l}`:""}`,o.status,a)}return a}async list(){return(await this.request("GET","/extensions")).extensions??[]}fetchBundle(e,r){let n=r?`?version=${encodeURIComponent(r)}`:"";return this.request("GET",`/extensions/${encodeURIComponent(e)}${n}`)}publish(e){return this.request("POST","/extensions",{name:e.name,version:e.version,kind:e.kind,bundle:e.bundle,...e.manifest?{manifest:e.manifest}:{}})}}});function xg(t){if(kg.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function Rg(){return{name:"extension-self-contained-fence",setup(t){t.onResolve({filter:/.*/},e=>e.kind==="entry-point"?null:xg(e.path)?{path:e.path,namespace:"extension-sdk"}:{errors:[{text:`extension ${e.path.startsWith(".")||e.path.startsWith("/")?`imports a sibling/local file ('${e.path}')`:e.path.startsWith("node:")||Pg(e.path)?`imports a Node builtin ('${e.path}')`:`imports an external module ('${e.path}')`} \u2014 sandboxed extensions must be self-contained. The ONLY allowed import is the SDK factory ('@/sync/hooks' or '@turbobase/extensions'); inline everything else into the extension file.`}]}),t.onLoad({filter:/.*/,namespace:"extension-sdk"},()=>({contents:Tg,loader:"js"}))}}}function Pg(t){let e=t.startsWith("node:")?t.slice(5):t;return Eg.has(e.split("/")[0])}function ad(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 Ag(){try{return(await import("esbuild")).build}catch(t){throw ad("esbuild",t)}}async function Ig(){try{return(await import("isolated-vm")).default}catch(t){throw ad("isolated-vm",t)}}async function us(t){let e=await Ag(),r;try{r=await e({stdin:{contents:t,loader:"ts",resolveDir:process.cwd(),sourcefile:"extension.ts"},bundle:!0,write:!1,format:"iife",globalName:"__tb_extension_module",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[Rg()]})}catch(n){let o=n.errors?.map(i=>i.text).filter(Boolean).join("; ");throw new li(o||`extension bundle failed: ${String(n)}`)}return r.outputFiles?.[0]?.text??""}async function Qr(t,e,r={}){let n=r.timeoutMs??200,s=r.memoryLimitMb??16,o=r.member??"run",i={patches:[],logs:[]},a=await Ig(),l=new a.Isolate({memoryLimit:s});try{let d=await l.createContext(),u=d.global,h=new a.Callback(A=>{let z=JSON.parse(String(A));i.rejection||(i.rejection=z)}),v=new a.Callback(A=>{i.patches.push(JSON.parse(String(A)))}),g=new a.Callback(A=>{let z=JSON.parse(String(A));i.logs.push(z)}),w=new a.Callback(A=>{i.result=JSON.parse(String(A))});await u.set("__tb_reject",h),await u.set("__tb_patch",v),await u.set("__tb_log",g),await u.set("__tb_result",w),await u.set("__tb_ctx_json",JSON.stringify(Cg(e)));let $=Og(t,o),E=await(await l.compileScript($)).run(d,{timeout:n,promise:!0});return o==="when"?{effects:i,whenResult:!!E}:{effects:i}}finally{l.isDisposed||l.dispose()}}function Cg(t){return{recordType:t.recordType,event:t.event,direction:t.direction,origin:t.origin,source:t.source,payload:t.payload??null,prior:t.prior??null,user:t.user??null,tenantConfig:t.tenantConfig??{},metadata:t.metadata??null,bindings:t.bindings??null,atlasLinks:t.atlasLinks??null}}function Og(t,e){return`
|
|
24
24
|
"use strict";
|
|
25
25
|
(async () => {
|
|
26
26
|
const __tb_ctx = JSON.parse(__tb_ctx_json);
|
|
@@ -89,36 +89,36 @@ ${s.join(`
|
|
|
89
89
|
${e==="transform"?"__tb_result(JSON.stringify(out == null ? null : out));":""}
|
|
90
90
|
return ${e==="when"?"out":"undefined"};
|
|
91
91
|
})()
|
|
92
|
-
`}var
|
|
92
|
+
`}var kg,Tg,li,Eg,di=N(()=>{kg=new Set(["@/sync/hooks","@/sync/hooks/index.js","@/sync/conduits","@/sync/conduits/index.js","@turbobase/extensions","@turbobase/extensions/hook","@turbobase/extensions/conduit"]);Tg=`
|
|
93
93
|
export const defineHook = (def) => def;
|
|
94
94
|
export const defineConduit = (def) => def;
|
|
95
95
|
export default defineHook;
|
|
96
|
-
`,
|
|
96
|
+
`,li=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};Eg=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 ui}from"node:fs";import{join as Ng}from"node:path";function jg(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 zg(t,e,r){let n=e.name??r,s=e.expect??"pass";try{let{effects:o}=await Qr(t,jg(e.context)),i=o.rejection?"reject":"pass";return{name:n,expected:s,observed:i,pass:i===s,rejection:o.rejection,patchCount:o.patches.length}}catch(o){return{name:n,expected:s,observed:"pass",pass:!1,patchCount:0,error:o instanceof Error?o.message:String(o)}}}async function ps(t,e){let r=await us(t),n=[];for(let s=0;s<e.length;s+=1)n.push(await zg(r,e[s],`sample[${s}]`));return n}async function Xr(t){let e;try{e=await ui.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 s=await ui.readFile(Ng(t,n),"utf8"),o=JSON.parse(s),i=Array.isArray(o)?o:[o];for(let a=0;a<i.length;a+=1){let l=i[a];r.push({file:n,fixture:{...l,name:l.name??`${n}${i.length>1?`#${a}`:""}`}})}}return r}function en(t){return ui.readFile(t,"utf8")}var pi=N(()=>{di()});function jt(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function fy(t){let e=t.recordType;if(!e)throw new Ye("record type is required (e.g. --record=salesOrder)");let r=t.event??"before_save",n=t.template??"require-field",s=t.source,o=s?`
|
|
97
97
|
source: ${JSON.stringify(s)},`:"",i,a;if(n==="blank")i=`
|
|
98
98
|
run: (ctx) => {
|
|
99
99
|
// Validate or mutate ctx.payload here. Reject with ctx.reject({...}); mutate
|
|
100
100
|
// with ctx.patch({...}); observe with ctx.log('info', '...').
|
|
101
|
-
},`,a="custom";else if(n==="require-field"){let
|
|
101
|
+
},`,a="custom";else if(n==="require-field"){let v=t.field;if(!v)throw new Ye("require-field template needs --field=<name>");i=`
|
|
102
102
|
run: (ctx) => {
|
|
103
|
-
const v = ctx.payload[${JSON.stringify(
|
|
103
|
+
const v = ctx.payload[${JSON.stringify(v)}];
|
|
104
104
|
if (v === undefined || v === null || v === '') {
|
|
105
105
|
ctx.reject({
|
|
106
106
|
code: 'MANDATORY_FIELD_MISSING',
|
|
107
|
-
field: ${JSON.stringify(
|
|
108
|
-
message: ${JSON.stringify(`${
|
|
107
|
+
field: ${JSON.stringify(v)},
|
|
108
|
+
message: ${JSON.stringify(`${v} is required`)},
|
|
109
109
|
});
|
|
110
110
|
}
|
|
111
|
-
},`,a=`require-field-${
|
|
111
|
+
},`,a=`require-field-${v}`}else if(n==="enforce-format"){let v=t.field;if(!v)throw new Ye("enforce-format template needs --field=<name>");if(!t.regex)throw new Ye("enforce-format template needs --regex=<pattern>");i=`
|
|
112
112
|
run: (ctx) => {
|
|
113
|
-
const v = ctx.payload[${JSON.stringify(
|
|
113
|
+
const v = ctx.payload[${JSON.stringify(v)}];
|
|
114
114
|
if (typeof v === 'string' && v && !/${t.regex}/.test(v)) {
|
|
115
115
|
ctx.reject({
|
|
116
116
|
code: 'INVALID_FORMAT',
|
|
117
|
-
field: ${JSON.stringify(
|
|
118
|
-
message: ${JSON.stringify(`${
|
|
117
|
+
field: ${JSON.stringify(v)},
|
|
118
|
+
message: ${JSON.stringify(`${v} does not match expected format`)},
|
|
119
119
|
});
|
|
120
120
|
}
|
|
121
|
-
},`,a=`enforce-format-${
|
|
121
|
+
},`,a=`enforce-format-${v}`}else throw new Ye(`unsupported template: ${n}. Supported: require-field | enforce-format | blank.`);let l=t.id??`custom:${e}:${a}${t.regex?`-${jt(t.regex).slice(0,24)}`:""}`,u=`/**
|
|
122
122
|
* ${t.description??`${a} on ${e}.${r}`}
|
|
123
123
|
*
|
|
124
124
|
* Scaffolded by \`turbobase ext new hook\`. Edit freely, then \`turbobase ext test\` and
|
|
@@ -131,7 +131,7 @@ export default defineHook<Record<string, unknown>>({
|
|
|
131
131
|
recordType: ${JSON.stringify(e)},
|
|
132
132
|
event: ${JSON.stringify(r)},${o}${i}
|
|
133
133
|
});
|
|
134
|
-
`;return{relativePath:`hooks/${e}/${r}.${a}.ts`,content:
|
|
134
|
+
`;return{relativePath:`hooks/${e}/${r}.${a}.ts`,content:u}}function hy(t){let e=t.recordType;if(!e)throw new Ye("record type is required (e.g. --record=order)");let r=t.source;if(!r)throw new Ye("--source is required (the origin source, e.g. --source=shopify)");let n=t.to;if(!n)throw new Ye("--to is required (the target source, e.g. --to=netsuite)");if(r===n)throw new Ye(`a conduit must bridge two DIFFERENT sources (got --source=${r} --to=${n}); use \`turbobase ext new hook\` for an intra-source transform`);let s=t.toRecordType??e,o=t.event??"after_canonicalize_inbound",i=t.id??`${jt(r)}2${jt(n)}:${jt(e)}`,l=`/**
|
|
135
135
|
* ${t.description??`Bridge ${r} ${e} \u2192 ${n} ${s} (${o}).`}
|
|
136
136
|
*
|
|
137
137
|
* Scaffolded by \`turbobase ext new conduit\`. A conduit is a PURE canonical\u2192canonical
|
|
@@ -174,7 +174,7 @@ export default defineConduit<Record<string, unknown>>({
|
|
|
174
174
|
},
|
|
175
175
|
idempotencyKey: (ctx) => ${JSON.stringify(`${i}:`)} + ctx.externalId,
|
|
176
176
|
});
|
|
177
|
-
`;return{relativePath:`conduits/${
|
|
177
|
+
`;return{relativePath:`conduits/${jt(r)}-${jt(e)}-to-${jt(n)}-${jt(s)}.ts`,content:l}}function wr(t,e){let r=my[t];if(!r)throw new Ye(`unknown extension kind '${t}'. Scaffoldable kinds: ${Cd.join(", ")}.`);return r(e)}var Cd,Ye,my,wi=N(()=>{Cd=["hook","conduit"];Ye=class extends Error{};my={hook:fy,conduit:hy}});function Nb(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 jb(t){return du[Nb(t)%du.length]}function zb(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 uu(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function pu(t,e){let[r,n]=jb(t),s=uu(zb(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${uu(e)}">
|
|
178
178
|
<defs>
|
|
179
179
|
<linearGradient id="tile" x1="0" y1="0" x2="1" y2="1">
|
|
180
180
|
<stop offset="0" stop-color="${r}"/>
|
|
@@ -184,9 +184,9 @@ export default defineConduit<Record<string, unknown>>({
|
|
|
184
184
|
<rect width="64" height="64" rx="14" fill="url(#tile)"/>
|
|
185
185
|
<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">${s}</text>
|
|
186
186
|
</svg>
|
|
187
|
-
`}var
|
|
188
|
-
`}function
|
|
189
|
-
`}function
|
|
187
|
+
`}var du,fu=N(()=>{du=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var hu,mu=N(()=>{hu=Object.freeze({instance:!0,platform:!0,share:"inherit"})});var $u={};ql($u,{MAIN_TSX:()=>Su,STYLES_CSS:()=>_u,TSCONFIG:()=>wu,TURBOBASE_CLIENT:()=>gu,indexHtml:()=>vu,instanceOriginFromEnv:()=>Bb,packageJson:()=>yu,scaffoldAppFiles:()=>Hb,starterApp:()=>Kb,viteConfig:()=>bu});function Ub(t){let e={name:t.title},r=(t.description??"").trim().slice(0,Lb);return r&&(e.description=r),e.icon="favicon.svg",e.learnings={...hu},JSON.stringify(e,null,2)+`
|
|
188
|
+
`}function yu(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview"},dependencies:{react:"^18.3.1","react-dom":"^18.3.1"},devDependencies:{"@types/react":"^18.3.3","@types/react-dom":"^18.3.0","@vitejs/plugin-react":"^4.3.1",typescript:"^5.5.3",vite:"^5.4.0"}},null,2)}
|
|
189
|
+
`}function Mb(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 Bb(t=process.env){let e=(t.TENANT_SLUG??"").trim(),r=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!r))return`https://${e}.${r}`}function bu(t,e={}){let r=Mb(e.instanceOrigin);return`import { defineConfig } from 'vite';
|
|
190
190
|
import react from '@vitejs/plugin-react';
|
|
191
191
|
|
|
192
192
|
// A same-origin static SPA served at /a/${t}. \`base\` MUST match that mount
|
|
@@ -200,8 +200,8 @@ import react from '@vitejs/plugin-react';
|
|
|
200
200
|
// you sign in, and the cookies land on localhost:3000. Override the targets
|
|
201
201
|
// with SUPABASE_URL / TURBOBASE_API_URL without editing this file (Vite reads
|
|
202
202
|
// them at boot; restart the dev server after changing one).
|
|
203
|
-
const TENANT = process.env.SUPABASE_URL || '${r??
|
|
204
|
-
const API = process.env.TURBOBASE_API_URL || '${r??
|
|
203
|
+
const TENANT = process.env.SUPABASE_URL || '${r??Db}'; // /rest + the Realtime WS
|
|
204
|
+
const API = process.env.TURBOBASE_API_URL || '${r??qb}'; // /v1, /auth, /login, /_app
|
|
205
205
|
|
|
206
206
|
// Where this bundle's assets are requested from. \`turbobase apps deploy\` sets
|
|
207
207
|
// this to /_tb/app-assets/<build-id>/ so the asset URLs name the BUILD, not the
|
|
@@ -233,7 +233,7 @@ export default defineConfig({
|
|
|
233
233
|
},
|
|
234
234
|
build: { outDir: 'dist' },
|
|
235
235
|
});
|
|
236
|
-
`}function
|
|
236
|
+
`}function vu(t){return`<!doctype html>
|
|
237
237
|
<html lang="en">
|
|
238
238
|
<head>
|
|
239
239
|
<meta charset="UTF-8" />
|
|
@@ -246,7 +246,7 @@ export default defineConfig({
|
|
|
246
246
|
<script type="module" src="/src/main.tsx"></script>
|
|
247
247
|
</body>
|
|
248
248
|
</html>
|
|
249
|
-
`}function
|
|
249
|
+
`}function Hb(t){return{"package.json":yu(t.slug),"vite.config.ts":bu(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":Fb,"tsconfig.json":wu,"index.html":vu(t.title),"public/turbobase.json":Ub(t),"public/favicon.svg":pu(t.slug,t.title),"src/main.tsx":Su,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":gu,"src/styles.css":_u,"README.md":`# ${t.title}
|
|
250
250
|
|
|
251
251
|
\`\`\`sh
|
|
252
252
|
npm install
|
|
@@ -267,7 +267,7 @@ every read comes back "permission denied", which looks like an RLS problem.
|
|
|
267
267
|
|
|
268
268
|
\`CLAUDE.md\` + \`.mcp.json\` wire Claude Code to this instance. \`.mcp.json\` holds a
|
|
269
269
|
live access token and is gitignored \u2014 keep it that way.
|
|
270
|
-
`}}function
|
|
270
|
+
`}}function Kb(t){return`import React from 'react';
|
|
271
271
|
import { select } from './lib/turbobase';
|
|
272
272
|
|
|
273
273
|
/** Swap for any record type \u2014 GET /v1/catalog/records lists what this instance has. */
|
|
@@ -293,7 +293,7 @@ export default function App() {
|
|
|
293
293
|
</main>
|
|
294
294
|
);
|
|
295
295
|
}
|
|
296
|
-
`}var
|
|
296
|
+
`}var Lb,gu,Db,qb,Fb,wu,Su,_u,ku=N(()=>{fu();mu();Lb=200;gu=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
|
|
297
297
|
// Reads go through PostgREST (RLS-scoped); writes go through POST /v1/data/<recordType>.
|
|
298
298
|
// A cold first paint that fans out many reads should use batch() \u2014 ONE request
|
|
299
299
|
// that multiplexes them, sidestepping the per-request rate limiter.
|
|
@@ -686,7 +686,7 @@ export interface Page<T = unknown> {
|
|
|
686
686
|
nextCursor: string | null;
|
|
687
687
|
}
|
|
688
688
|
|
|
689
|
-
/** Opaque cursor payload \u2014 the same compact { t, k, v, h } shape
|
|
689
|
+
/** Opaque cursor payload \u2014 the same compact { t, k, v, h } shape Turbobase's
|
|
690
690
|
* server-side cursors use (table, sort key, last value, query hash). */
|
|
691
691
|
interface CursorToken {
|
|
692
692
|
t: string;
|
|
@@ -849,7 +849,7 @@ export async function selectPage<T = unknown>(
|
|
|
849
849
|
}
|
|
850
850
|
return { rows, nextCursor };
|
|
851
851
|
}
|
|
852
|
-
`;
|
|
852
|
+
`;Db="http://localhost:54331",qb="http://localhost:4100";Fb=`node_modules/
|
|
853
853
|
dist/
|
|
854
854
|
build/
|
|
855
855
|
|
|
@@ -861,8 +861,8 @@ build/
|
|
|
861
861
|
!.env.example
|
|
862
862
|
|
|
863
863
|
.DS_Store
|
|
864
|
-
`,
|
|
865
|
-
`;
|
|
864
|
+
`,wu=`${JSON.stringify({compilerOptions:{target:"ES2022",lib:["ES2022","DOM","DOM.Iterable"],module:"ESNext",moduleResolution:"bundler",jsx:"react-jsx",strict:!0,skipLibCheck:!0,noEmit:!0},include:["src"]},null,2)}
|
|
865
|
+
`;Su=`import React from 'react';
|
|
866
866
|
import { createRoot } from 'react-dom/client';
|
|
867
867
|
import App from './App';
|
|
868
868
|
import './styles.css';
|
|
@@ -872,62 +872,239 @@ createRoot(document.getElementById('root')!).render(
|
|
|
872
872
|
<App />
|
|
873
873
|
</React.StrictMode>,
|
|
874
874
|
);
|
|
875
|
-
`,
|
|
875
|
+
`,_u=`:root { color-scheme: light; font-family: ui-sans-serif, system-ui, sans-serif; }
|
|
876
876
|
* { box-sizing: border-box; }
|
|
877
877
|
body { margin: 0; background: #f8fafc; color: #0f172a; }
|
|
878
|
-
`});import*as
|
|
879
|
-
`);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function bu(t){return t.description}function wu(t){if(ft(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function wr(t){if(ft(t)){let o=t._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.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 ln=O(()=>{});import*as c from"zod/v4";function zu(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Lu(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Ci,vu,Ot,_s,_e,_u,Su,uE,Ob,Nb,Oi,He,dn,$u,ke,Ye,Qe,xe,Ss,ku,Ni,xu,Tu,ji,un,M,zi,Ru,Eu,pE,$s,jb,ks,zb,pn,vr,Pu,Lb,Db,Mb,qb,Ub,Bb,Li,Fb,Hb,Di,xs,Kb,Vb,Ts,Gb,fn,hn,Wb,mn,_r,Jb,gn,Rs,Es,Ps,fE,As,Is,Cs,Au,Iu,Cu,Mi,Ou,yn,Sr,Nu,Zb,Os,Yb,Ns,Qb,qi,Xb,js,ew,tw,rw,nw,sw,ow,iw,aw,cw,lw,zs,dw,uw,Ls,Ui,Bi,Fi,pw,fw,hw,Hi,mw,gw,yw,bw,ww,ju,Ds,vw,Ms,hE,_w,$r,Sw,mE,bn,$w,Ki,kw,xw,Tw,Rw,Ew,Pw,Aw,vs,Iw,Cw,Ow,wn,Vi,Nw,jw,zw,Lw,Dw,Mw,qw,Uw,Bw,Fw,Hw,Kw,Vw,Gw,Ww,Jw,Zw,Yw,kr,Qw,Xw,ev,qs,tv,rv,nv,Gi,sv,gE,yE,bE,wE,vE,_E,z,Ii,xr=O(()=>{Ci="2025-11-25",vu=[Ci,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ot="io.modelcontextprotocol/related-task",_s="2.0",_e=c.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),_u=c.union([c.string(),c.number().int()]),Su=c.string(),uE=c.looseObject({ttl:c.number().optional(),pollInterval:c.number().optional()}),Ob=c.object({ttl:c.number().optional()}),Nb=c.object({taskId:c.string()}),Oi=c.looseObject({progressToken:_u.optional(),[Ot]:Nb.optional()}),He=c.object({_meta:Oi.optional()}),dn=He.extend({task:Ob.optional()}),$u=t=>dn.safeParse(t).success,ke=c.object({method:c.string(),params:He.loose().optional()}),Ye=c.object({_meta:Oi.optional()}),Qe=c.object({method:c.string(),params:Ye.loose().optional()}),xe=c.looseObject({_meta:Oi.optional()}),Ss=c.union([c.string(),c.number().int()]),ku=c.object({jsonrpc:c.literal(_s),id:Ss,...ke.shape}).strict(),Ni=t=>ku.safeParse(t).success,xu=c.object({jsonrpc:c.literal(_s),...Qe.shape}).strict(),Tu=t=>xu.safeParse(t).success,ji=c.object({jsonrpc:c.literal(_s),id:Ss,result:xe}).strict(),un=t=>ji.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"})(M||(M={}));zi=c.object({jsonrpc:c.literal(_s),id:Ss.optional(),error:c.object({code:c.number().int(),message:c.string(),data:c.unknown().optional()})}).strict(),Ru=t=>zi.safeParse(t).success,Eu=c.union([ku,xu,ji,zi]),pE=c.union([ji,zi]),$s=xe.strict(),jb=Ye.extend({requestId:Ss.optional(),reason:c.string().optional()}),ks=Qe.extend({method:c.literal("notifications/cancelled"),params:jb}),zb=c.object({src:c.string(),mimeType:c.string().optional(),sizes:c.array(c.string()).optional(),theme:c.enum(["light","dark"]).optional()}),pn=c.object({icons:c.array(zb).optional()}),vr=c.object({name:c.string(),title:c.string().optional()}),Pu=vr.extend({...vr.shape,...pn.shape,version:c.string(),websiteUrl:c.string().optional(),description:c.string().optional()}),Lb=c.intersection(c.object({applyDefaults:c.boolean().optional()}),c.record(c.string(),c.unknown())),Db=c.preprocess(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,c.intersection(c.object({form:Lb.optional(),url:_e.optional()}),c.record(c.string(),c.unknown()).optional())),Mb=c.looseObject({list:_e.optional(),cancel:_e.optional(),requests:c.looseObject({sampling:c.looseObject({createMessage:_e.optional()}).optional(),elicitation:c.looseObject({create:_e.optional()}).optional()}).optional()}),qb=c.looseObject({list:_e.optional(),cancel:_e.optional(),requests:c.looseObject({tools:c.looseObject({call:_e.optional()}).optional()}).optional()}),Ub=c.object({experimental:c.record(c.string(),_e).optional(),sampling:c.object({context:_e.optional(),tools:_e.optional()}).optional(),elicitation:Db.optional(),roots:c.object({listChanged:c.boolean().optional()}).optional(),tasks:Mb.optional(),extensions:c.record(c.string(),_e).optional()}),Bb=He.extend({protocolVersion:c.string(),capabilities:Ub,clientInfo:Pu}),Li=ke.extend({method:c.literal("initialize"),params:Bb}),Fb=c.object({experimental:c.record(c.string(),_e).optional(),logging:_e.optional(),completions:_e.optional(),prompts:c.object({listChanged:c.boolean().optional()}).optional(),resources:c.object({subscribe:c.boolean().optional(),listChanged:c.boolean().optional()}).optional(),tools:c.object({listChanged:c.boolean().optional()}).optional(),tasks:qb.optional(),extensions:c.record(c.string(),_e).optional()}),Hb=xe.extend({protocolVersion:c.string(),capabilities:Fb,serverInfo:Pu,instructions:c.string().optional()}),Di=Qe.extend({method:c.literal("notifications/initialized"),params:Ye.optional()}),xs=ke.extend({method:c.literal("ping"),params:He.optional()}),Kb=c.object({progress:c.number(),total:c.optional(c.number()),message:c.optional(c.string())}),Vb=c.object({...Ye.shape,...Kb.shape,progressToken:_u}),Ts=Qe.extend({method:c.literal("notifications/progress"),params:Vb}),Gb=He.extend({cursor:Su.optional()}),fn=ke.extend({params:Gb.optional()}),hn=xe.extend({nextCursor:Su.optional()}),Wb=c.enum(["working","input_required","completed","failed","cancelled"]),mn=c.object({taskId:c.string(),status:Wb,ttl:c.union([c.number(),c.null()]),createdAt:c.string(),lastUpdatedAt:c.string(),pollInterval:c.optional(c.number()),statusMessage:c.optional(c.string())}),_r=xe.extend({task:mn}),Jb=Ye.merge(mn),gn=Qe.extend({method:c.literal("notifications/tasks/status"),params:Jb}),Rs=ke.extend({method:c.literal("tasks/get"),params:He.extend({taskId:c.string()})}),Es=xe.merge(mn),Ps=ke.extend({method:c.literal("tasks/result"),params:He.extend({taskId:c.string()})}),fE=xe.loose(),As=fn.extend({method:c.literal("tasks/list")}),Is=hn.extend({tasks:c.array(mn)}),Cs=ke.extend({method:c.literal("tasks/cancel"),params:He.extend({taskId:c.string()})}),Au=xe.merge(mn),Iu=c.object({uri:c.string(),mimeType:c.optional(c.string()),_meta:c.record(c.string(),c.unknown()).optional()}),Cu=Iu.extend({text:c.string()}),Mi=c.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Ou=Iu.extend({blob:Mi}),yn=c.enum(["user","assistant"]),Sr=c.object({audience:c.array(yn).optional(),priority:c.number().min(0).max(1).optional(),lastModified:c.iso.datetime({offset:!0}).optional()}),Nu=c.object({...vr.shape,...pn.shape,uri:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),size:c.optional(c.number()),annotations:Sr.optional(),_meta:c.optional(c.looseObject({}))}),Zb=c.object({...vr.shape,...pn.shape,uriTemplate:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),annotations:Sr.optional(),_meta:c.optional(c.looseObject({}))}),Os=fn.extend({method:c.literal("resources/list")}),Yb=hn.extend({resources:c.array(Nu)}),Ns=fn.extend({method:c.literal("resources/templates/list")}),Qb=hn.extend({resourceTemplates:c.array(Zb)}),qi=He.extend({uri:c.string()}),Xb=qi,js=ke.extend({method:c.literal("resources/read"),params:Xb}),ew=xe.extend({contents:c.array(c.union([Cu,Ou]))}),tw=Qe.extend({method:c.literal("notifications/resources/list_changed"),params:Ye.optional()}),rw=qi,nw=ke.extend({method:c.literal("resources/subscribe"),params:rw}),sw=qi,ow=ke.extend({method:c.literal("resources/unsubscribe"),params:sw}),iw=Ye.extend({uri:c.string()}),aw=Qe.extend({method:c.literal("notifications/resources/updated"),params:iw}),cw=c.object({name:c.string(),description:c.optional(c.string()),required:c.optional(c.boolean())}),lw=c.object({...vr.shape,...pn.shape,description:c.optional(c.string()),arguments:c.optional(c.array(cw)),_meta:c.optional(c.looseObject({}))}),zs=fn.extend({method:c.literal("prompts/list")}),dw=hn.extend({prompts:c.array(lw)}),uw=He.extend({name:c.string(),arguments:c.record(c.string(),c.string()).optional()}),Ls=ke.extend({method:c.literal("prompts/get"),params:uw}),Ui=c.object({type:c.literal("text"),text:c.string(),annotations:Sr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Bi=c.object({type:c.literal("image"),data:Mi,mimeType:c.string(),annotations:Sr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Fi=c.object({type:c.literal("audio"),data:Mi,mimeType:c.string(),annotations:Sr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),pw=c.object({type:c.literal("tool_use"),name:c.string(),id:c.string(),input:c.record(c.string(),c.unknown()),_meta:c.record(c.string(),c.unknown()).optional()}),fw=c.object({type:c.literal("resource"),resource:c.union([Cu,Ou]),annotations:Sr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),hw=Nu.extend({type:c.literal("resource_link")}),Hi=c.union([Ui,Bi,Fi,hw,fw]),mw=c.object({role:yn,content:Hi}),gw=xe.extend({description:c.string().optional(),messages:c.array(mw)}),yw=Qe.extend({method:c.literal("notifications/prompts/list_changed"),params:Ye.optional()}),bw=c.object({title:c.string().optional(),readOnlyHint:c.boolean().optional(),destructiveHint:c.boolean().optional(),idempotentHint:c.boolean().optional(),openWorldHint:c.boolean().optional()}),ww=c.object({taskSupport:c.enum(["required","optional","forbidden"]).optional()}),ju=c.object({...vr.shape,...pn.shape,description:c.string().optional(),inputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),_e).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()),outputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),_e).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()).optional(),annotations:bw.optional(),execution:ww.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Ds=fn.extend({method:c.literal("tools/list")}),vw=hn.extend({tools:c.array(ju)}),Ms=xe.extend({content:c.array(Hi).default([]),structuredContent:c.record(c.string(),c.unknown()).optional(),isError:c.boolean().optional()}),hE=Ms.or(xe.extend({toolResult:c.unknown()})),_w=dn.extend({name:c.string(),arguments:c.record(c.string(),c.unknown()).optional()}),$r=ke.extend({method:c.literal("tools/call"),params:_w}),Sw=Qe.extend({method:c.literal("notifications/tools/list_changed"),params:Ye.optional()}),mE=c.object({autoRefresh:c.boolean().default(!0),debounceMs:c.number().int().nonnegative().default(300)}),bn=c.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),$w=He.extend({level:bn}),Ki=ke.extend({method:c.literal("logging/setLevel"),params:$w}),kw=Ye.extend({level:bn,logger:c.string().optional(),data:c.unknown()}),xw=Qe.extend({method:c.literal("notifications/message"),params:kw}),Tw=c.object({name:c.string().optional()}),Rw=c.object({hints:c.array(Tw).optional(),costPriority:c.number().min(0).max(1).optional(),speedPriority:c.number().min(0).max(1).optional(),intelligencePriority:c.number().min(0).max(1).optional()}),Ew=c.object({mode:c.enum(["auto","required","none"]).optional()}),Pw=c.object({type:c.literal("tool_result"),toolUseId:c.string().describe("The unique identifier for the corresponding tool call."),content:c.array(Hi).default([]),structuredContent:c.object({}).loose().optional(),isError:c.boolean().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Aw=c.discriminatedUnion("type",[Ui,Bi,Fi]),vs=c.discriminatedUnion("type",[Ui,Bi,Fi,pw,Pw]),Iw=c.object({role:yn,content:c.union([vs,c.array(vs)]),_meta:c.record(c.string(),c.unknown()).optional()}),Cw=dn.extend({messages:c.array(Iw),modelPreferences:Rw.optional(),systemPrompt:c.string().optional(),includeContext:c.enum(["none","thisServer","allServers"]).optional(),temperature:c.number().optional(),maxTokens:c.number().int(),stopSequences:c.array(c.string()).optional(),metadata:_e.optional(),tools:c.array(ju).optional(),toolChoice:Ew.optional()}),Ow=ke.extend({method:c.literal("sampling/createMessage"),params:Cw}),wn=xe.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens"]).or(c.string())),role:yn,content:Aw}),Vi=xe.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(c.string())),role:yn,content:c.union([vs,c.array(vs)])}),Nw=c.object({type:c.literal("boolean"),title:c.string().optional(),description:c.string().optional(),default:c.boolean().optional()}),jw=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),minLength:c.number().optional(),maxLength:c.number().optional(),format:c.enum(["email","uri","date","date-time"]).optional(),default:c.string().optional()}),zw=c.object({type:c.enum(["number","integer"]),title:c.string().optional(),description:c.string().optional(),minimum:c.number().optional(),maximum:c.number().optional(),default:c.number().optional()}),Lw=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),enum:c.array(c.string()),default:c.string().optional()}),Dw=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),oneOf:c.array(c.object({const:c.string(),title:c.string()})),default:c.string().optional()}),Mw=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),enum:c.array(c.string()),enumNames:c.array(c.string()).optional(),default:c.string().optional()}),qw=c.union([Lw,Dw]),Uw=c.object({type:c.literal("array"),title:c.string().optional(),description:c.string().optional(),minItems:c.number().optional(),maxItems:c.number().optional(),items:c.object({type:c.literal("string"),enum:c.array(c.string())}),default:c.array(c.string()).optional()}),Bw=c.object({type:c.literal("array"),title:c.string().optional(),description:c.string().optional(),minItems:c.number().optional(),maxItems:c.number().optional(),items:c.object({anyOf:c.array(c.object({const:c.string(),title:c.string()}))}),default:c.array(c.string()).optional()}),Fw=c.union([Uw,Bw]),Hw=c.union([Mw,qw,Fw]),Kw=c.union([Hw,Nw,jw,zw]),Vw=dn.extend({mode:c.literal("form").optional(),message:c.string(),requestedSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),Kw),required:c.array(c.string()).optional()})}),Gw=dn.extend({mode:c.literal("url"),message:c.string(),elicitationId:c.string(),url:c.string().url()}),Ww=c.union([Vw,Gw]),Jw=ke.extend({method:c.literal("elicitation/create"),params:Ww}),Zw=Ye.extend({elicitationId:c.string()}),Yw=Qe.extend({method:c.literal("notifications/elicitation/complete"),params:Zw}),kr=xe.extend({action:c.enum(["accept","decline","cancel"]),content:c.preprocess(t=>t===null?void 0:t,c.record(c.string(),c.union([c.string(),c.number(),c.boolean(),c.array(c.string())])).optional())}),Qw=c.object({type:c.literal("ref/resource"),uri:c.string()}),Xw=c.object({type:c.literal("ref/prompt"),name:c.string()}),ev=He.extend({ref:c.union([Xw,Qw]),argument:c.object({name:c.string(),value:c.string()}),context:c.object({arguments:c.record(c.string(),c.string()).optional()}).optional()}),qs=ke.extend({method:c.literal("completion/complete"),params:ev});tv=xe.extend({completion:c.looseObject({values:c.array(c.string()).max(100),total:c.optional(c.number().int()),hasMore:c.optional(c.boolean())})}),rv=c.object({uri:c.string().startsWith("file://"),name:c.string().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),nv=ke.extend({method:c.literal("roots/list"),params:He.optional()}),Gi=xe.extend({roots:c.array(rv)}),sv=Qe.extend({method:c.literal("notifications/roots/list_changed"),params:Ye.optional()}),gE=c.union([xs,Li,qs,Ki,Ls,zs,Os,Ns,js,nw,ow,$r,Ds,Rs,Ps,As,Cs]),yE=c.union([ks,Ts,Di,sv,gn]),bE=c.union([$s,wn,Vi,kr,Gi,Es,Is,_r]),wE=c.union([xs,Ow,Jw,nv,Rs,Ps,As,Cs]),vE=c.union([ks,Ts,xw,aw,tw,Sw,yw,gn,Yw]),_E=c.union([$s,Hb,tv,gw,dw,Yb,Qb,ew,Ms,vw,Es,Is,_r]),z=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===M.UrlElicitationRequired&&n){let s=n;if(s.elicitations)return new Ii(s.elicitations,r)}return new t(e,r,n)}},Ii=class extends z{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(M.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Nt(t){return t==="completed"||t==="failed"||t==="cancelled"}var Du=O(()=>{});var qu,Mu,Uu,Us=O(()=>{qu=Symbol("Let zodToJsonSchema decide on which parser to use"),Mu={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"},Uu=t=>typeof t=="string"?{...Mu,name:t}:{...Mu,...t}});var Bu,Wi=O(()=>{Us();Bu=t=>{let e=Uu(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,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function Ji(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ee(t,e,r,n,s){t[e]=r,Ji(t,e,n,s)}var jt=O(()=>{});var Bs,Fs=O(()=>{Bs=(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 ge(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Bs(e,t.currentPath):e.join("/")}}var Xe=O(()=>{Fs()});import{ZodFirstPartyTypeKind as ov}from"zod/v3";function Fu(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==ov.ZodAny&&(r.items=U(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ee(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ee(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ee(r,"minItems",t.exactLength.value,t.exactLength.message,e),ee(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var Zi=O(()=>{jt();ve()});function Hu(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?ee(r,"minimum",n.value,n.message,e):ee(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ee(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ee(r,"maximum",n.value,n.message,e):ee(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ee(r,"maximum",n.value,n.message,e));break;case"multipleOf":ee(r,"multipleOf",n.value,n.message,e);break}return r}var Yi=O(()=>{jt()});function Ku(){return{type:"boolean"}}var Qi=O(()=>{});function Hs(t,e){return U(t.type._def,e)}var Ks=O(()=>{ve()});var Vu,Xi=O(()=>{ve();Vu=(t,e)=>U(t.innerType._def,e)});function ea(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>ea(t,e,s))};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 iv(t,e)}}var iv,ta=O(()=>{jt();iv=(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":ee(r,"minimum",n.value,n.message,e);break;case"max":ee(r,"maximum",n.value,n.message,e);break}return r}});function Gu(t,e){return{...U(t.innerType._def,e),default:t.defaultValue()}}var ra=O(()=>{ve()});function Wu(t,e){return e.effectStrategy==="input"?U(t.schema._def,e):ge(e)}var na=O(()=>{ve();Xe()});function Ju(t){return{type:"string",enum:Array.from(t.values)}}var sa=O(()=>{});function Zu(t,e){let r=[U(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),U(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return r.forEach(o=>{if(av(o))s.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let i=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:a,...l}=o;i=l}else n=void 0;s.push(i)}}),s.length?{allOf:s,...n}:void 0}var av,oa=O(()=>{ve();av=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function Yu(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 ia=O(()=>{});function Vs(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ee(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ee(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":it(r,"email",n.message,e);break;case"format:idn-email":it(r,"idn-email",n.message,e);break;case"pattern:zod":Ne(r,ot.email,n.message,e);break}break;case"url":it(r,"uri",n.message,e);break;case"uuid":it(r,"uuid",n.message,e);break;case"regex":Ne(r,n.regex,n.message,e);break;case"cuid":Ne(r,ot.cuid,n.message,e);break;case"cuid2":Ne(r,ot.cuid2,n.message,e);break;case"startsWith":Ne(r,RegExp(`^${ca(n.value,e)}`),n.message,e);break;case"endsWith":Ne(r,RegExp(`${ca(n.value,e)}$`),n.message,e);break;case"datetime":it(r,"date-time",n.message,e);break;case"date":it(r,"date",n.message,e);break;case"time":it(r,"time",n.message,e);break;case"duration":it(r,"duration",n.message,e);break;case"length":ee(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ee(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Ne(r,RegExp(ca(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&it(r,"ipv4",n.message,e),n.version!=="v4"&&it(r,"ipv6",n.message,e);break}case"base64url":Ne(r,ot.base64url,n.message,e);break;case"jwt":Ne(r,ot.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Ne(r,ot.ipv4Cidr,n.message,e),n.version!=="v4"&&Ne(r,ot.ipv6Cidr,n.message,e);break}case"emoji":Ne(r,ot.emoji(),n.message,e);break;case"ulid":{Ne(r,ot.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{it(r,"binary",n.message,e);break}case"contentEncoding:base64":{ee(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Ne(r,ot.base64,n.message,e);break}}break}case"nanoid":Ne(r,ot.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function ca(t,e){return e.patternStrategy==="escape"?lv(t):t}function lv(t){let e="";for(let r=0;r<t.length;r++)cv.has(t[r])||(e+="\\"),e+=t[r];return e}function it(t,e,r,n){t.format||t.anyOf?.some(s=>s.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}}})):ee(t,"format",e,r,n)}function Ne(t,e,r,n){t.pattern||t.allOf?.some(s=>s.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:Qu(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ee(t,"pattern",Qu(e,n),r,n)}function Qu(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,s="",o=!1,i=!1,a=!1;for(let l=0;l<n.length;l++){if(o){s+=n[l],o=!1;continue}if(r.i){if(i){if(n[l].match(/[a-z]/)){a?(s+=n[l],s+=`${n[l-2]}-${n[l]}`.toUpperCase(),a=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(s+=n[l],a=!0):s+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){s+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(r.m){if(n[l]==="^"){s+=`(^|(?<=[\r
|
|
878
|
+
`});import*as xu from"zod/v3";import*as er from"zod/v4-mini";function mt(t){return!!t._zod}function tr(t){let e=Object.values(t);if(e.length===0)return er.object({});let r=e.every(mt),n=e.every(s=>!mt(s));if(r)return er.object(t);if(n)return xu.object(t);throw new Error("Mixed Zod versions detected in object shape.")}function zt(t,e){return mt(t)?er.safeParse(t,e):t.safeParse(e)}async function vs(t,e){return mt(t)?await er.safeParseAsync(t,e):await t.safeParseAsync(e)}function Lt(t){if(!t)return;let e;if(mt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function vr(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(s=>typeof s=="object"&&s!==null&&(s._def!==void 0||s._zod!==void 0||typeof s.parse=="function")))return tr(t)}}if(mt(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 Vb(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function Ss(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 ${Vb(e.path)}`:e.message).join(`
|
|
879
|
+
`);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function Tu(t){return t.description}function Ru(t){if(mt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Sr(t){if(mt(t)){let o=t._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.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 ln=N(()=>{});import*as c from"zod/v4";function Hu(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Ku(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var zi,Eu,Ut,$s,$e,Pu,Au,IE,Gb,Wb,Li,Ke,dn,Iu,xe,Qe,Xe,Te,ks,Cu,Ui,Ou,Nu,Di,un,q,qi,ju,zu,CE,xs,Jb,Ts,Zb,pn,_r,Lu,Yb,Qb,Xb,ew,tw,rw,Mi,nw,sw,Bi,Rs,ow,iw,Es,aw,fn,hn,cw,mn,$r,lw,gn,Ps,As,Is,OE,Cs,Os,Ns,Uu,Du,qu,Fi,Mu,yn,kr,Bu,dw,js,uw,zs,pw,Hi,fw,Ls,hw,mw,gw,yw,bw,ww,vw,Sw,_w,$w,Us,kw,xw,Ds,Ki,Vi,Gi,Tw,Rw,Ew,Wi,Pw,Aw,Iw,Cw,Ow,Fu,qs,Nw,Ms,NE,jw,xr,zw,jE,bn,Lw,Ji,Uw,Dw,qw,Mw,Bw,Fw,Hw,_s,Kw,Vw,Gw,wn,Zi,Ww,Jw,Zw,Yw,Qw,Xw,ev,tv,rv,nv,sv,ov,iv,av,cv,lv,dv,uv,Tr,pv,fv,hv,Bs,mv,gv,yv,Yi,bv,zE,LE,UE,DE,qE,ME,L,ji,Rr=N(()=>{zi="2025-11-25",Eu=[zi,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ut="io.modelcontextprotocol/related-task",$s="2.0",$e=c.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Pu=c.union([c.string(),c.number().int()]),Au=c.string(),IE=c.looseObject({ttl:c.number().optional(),pollInterval:c.number().optional()}),Gb=c.object({ttl:c.number().optional()}),Wb=c.object({taskId:c.string()}),Li=c.looseObject({progressToken:Pu.optional(),[Ut]:Wb.optional()}),Ke=c.object({_meta:Li.optional()}),dn=Ke.extend({task:Gb.optional()}),Iu=t=>dn.safeParse(t).success,xe=c.object({method:c.string(),params:Ke.loose().optional()}),Qe=c.object({_meta:Li.optional()}),Xe=c.object({method:c.string(),params:Qe.loose().optional()}),Te=c.looseObject({_meta:Li.optional()}),ks=c.union([c.string(),c.number().int()]),Cu=c.object({jsonrpc:c.literal($s),id:ks,...xe.shape}).strict(),Ui=t=>Cu.safeParse(t).success,Ou=c.object({jsonrpc:c.literal($s),...Xe.shape}).strict(),Nu=t=>Ou.safeParse(t).success,Di=c.object({jsonrpc:c.literal($s),id:ks,result:Te}).strict(),un=t=>Di.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(q||(q={}));qi=c.object({jsonrpc:c.literal($s),id:ks.optional(),error:c.object({code:c.number().int(),message:c.string(),data:c.unknown().optional()})}).strict(),ju=t=>qi.safeParse(t).success,zu=c.union([Cu,Ou,Di,qi]),CE=c.union([Di,qi]),xs=Te.strict(),Jb=Qe.extend({requestId:ks.optional(),reason:c.string().optional()}),Ts=Xe.extend({method:c.literal("notifications/cancelled"),params:Jb}),Zb=c.object({src:c.string(),mimeType:c.string().optional(),sizes:c.array(c.string()).optional(),theme:c.enum(["light","dark"]).optional()}),pn=c.object({icons:c.array(Zb).optional()}),_r=c.object({name:c.string(),title:c.string().optional()}),Lu=_r.extend({..._r.shape,...pn.shape,version:c.string(),websiteUrl:c.string().optional(),description:c.string().optional()}),Yb=c.intersection(c.object({applyDefaults:c.boolean().optional()}),c.record(c.string(),c.unknown())),Qb=c.preprocess(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,c.intersection(c.object({form:Yb.optional(),url:$e.optional()}),c.record(c.string(),c.unknown()).optional())),Xb=c.looseObject({list:$e.optional(),cancel:$e.optional(),requests:c.looseObject({sampling:c.looseObject({createMessage:$e.optional()}).optional(),elicitation:c.looseObject({create:$e.optional()}).optional()}).optional()}),ew=c.looseObject({list:$e.optional(),cancel:$e.optional(),requests:c.looseObject({tools:c.looseObject({call:$e.optional()}).optional()}).optional()}),tw=c.object({experimental:c.record(c.string(),$e).optional(),sampling:c.object({context:$e.optional(),tools:$e.optional()}).optional(),elicitation:Qb.optional(),roots:c.object({listChanged:c.boolean().optional()}).optional(),tasks:Xb.optional(),extensions:c.record(c.string(),$e).optional()}),rw=Ke.extend({protocolVersion:c.string(),capabilities:tw,clientInfo:Lu}),Mi=xe.extend({method:c.literal("initialize"),params:rw}),nw=c.object({experimental:c.record(c.string(),$e).optional(),logging:$e.optional(),completions:$e.optional(),prompts:c.object({listChanged:c.boolean().optional()}).optional(),resources:c.object({subscribe:c.boolean().optional(),listChanged:c.boolean().optional()}).optional(),tools:c.object({listChanged:c.boolean().optional()}).optional(),tasks:ew.optional(),extensions:c.record(c.string(),$e).optional()}),sw=Te.extend({protocolVersion:c.string(),capabilities:nw,serverInfo:Lu,instructions:c.string().optional()}),Bi=Xe.extend({method:c.literal("notifications/initialized"),params:Qe.optional()}),Rs=xe.extend({method:c.literal("ping"),params:Ke.optional()}),ow=c.object({progress:c.number(),total:c.optional(c.number()),message:c.optional(c.string())}),iw=c.object({...Qe.shape,...ow.shape,progressToken:Pu}),Es=Xe.extend({method:c.literal("notifications/progress"),params:iw}),aw=Ke.extend({cursor:Au.optional()}),fn=xe.extend({params:aw.optional()}),hn=Te.extend({nextCursor:Au.optional()}),cw=c.enum(["working","input_required","completed","failed","cancelled"]),mn=c.object({taskId:c.string(),status:cw,ttl:c.union([c.number(),c.null()]),createdAt:c.string(),lastUpdatedAt:c.string(),pollInterval:c.optional(c.number()),statusMessage:c.optional(c.string())}),$r=Te.extend({task:mn}),lw=Qe.merge(mn),gn=Xe.extend({method:c.literal("notifications/tasks/status"),params:lw}),Ps=xe.extend({method:c.literal("tasks/get"),params:Ke.extend({taskId:c.string()})}),As=Te.merge(mn),Is=xe.extend({method:c.literal("tasks/result"),params:Ke.extend({taskId:c.string()})}),OE=Te.loose(),Cs=fn.extend({method:c.literal("tasks/list")}),Os=hn.extend({tasks:c.array(mn)}),Ns=xe.extend({method:c.literal("tasks/cancel"),params:Ke.extend({taskId:c.string()})}),Uu=Te.merge(mn),Du=c.object({uri:c.string(),mimeType:c.optional(c.string()),_meta:c.record(c.string(),c.unknown()).optional()}),qu=Du.extend({text:c.string()}),Fi=c.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Mu=Du.extend({blob:Fi}),yn=c.enum(["user","assistant"]),kr=c.object({audience:c.array(yn).optional(),priority:c.number().min(0).max(1).optional(),lastModified:c.iso.datetime({offset:!0}).optional()}),Bu=c.object({..._r.shape,...pn.shape,uri:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),size:c.optional(c.number()),annotations:kr.optional(),_meta:c.optional(c.looseObject({}))}),dw=c.object({..._r.shape,...pn.shape,uriTemplate:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),annotations:kr.optional(),_meta:c.optional(c.looseObject({}))}),js=fn.extend({method:c.literal("resources/list")}),uw=hn.extend({resources:c.array(Bu)}),zs=fn.extend({method:c.literal("resources/templates/list")}),pw=hn.extend({resourceTemplates:c.array(dw)}),Hi=Ke.extend({uri:c.string()}),fw=Hi,Ls=xe.extend({method:c.literal("resources/read"),params:fw}),hw=Te.extend({contents:c.array(c.union([qu,Mu]))}),mw=Xe.extend({method:c.literal("notifications/resources/list_changed"),params:Qe.optional()}),gw=Hi,yw=xe.extend({method:c.literal("resources/subscribe"),params:gw}),bw=Hi,ww=xe.extend({method:c.literal("resources/unsubscribe"),params:bw}),vw=Qe.extend({uri:c.string()}),Sw=Xe.extend({method:c.literal("notifications/resources/updated"),params:vw}),_w=c.object({name:c.string(),description:c.optional(c.string()),required:c.optional(c.boolean())}),$w=c.object({..._r.shape,...pn.shape,description:c.optional(c.string()),arguments:c.optional(c.array(_w)),_meta:c.optional(c.looseObject({}))}),Us=fn.extend({method:c.literal("prompts/list")}),kw=hn.extend({prompts:c.array($w)}),xw=Ke.extend({name:c.string(),arguments:c.record(c.string(),c.string()).optional()}),Ds=xe.extend({method:c.literal("prompts/get"),params:xw}),Ki=c.object({type:c.literal("text"),text:c.string(),annotations:kr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Vi=c.object({type:c.literal("image"),data:Fi,mimeType:c.string(),annotations:kr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Gi=c.object({type:c.literal("audio"),data:Fi,mimeType:c.string(),annotations:kr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Tw=c.object({type:c.literal("tool_use"),name:c.string(),id:c.string(),input:c.record(c.string(),c.unknown()),_meta:c.record(c.string(),c.unknown()).optional()}),Rw=c.object({type:c.literal("resource"),resource:c.union([qu,Mu]),annotations:kr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Ew=Bu.extend({type:c.literal("resource_link")}),Wi=c.union([Ki,Vi,Gi,Ew,Rw]),Pw=c.object({role:yn,content:Wi}),Aw=Te.extend({description:c.string().optional(),messages:c.array(Pw)}),Iw=Xe.extend({method:c.literal("notifications/prompts/list_changed"),params:Qe.optional()}),Cw=c.object({title:c.string().optional(),readOnlyHint:c.boolean().optional(),destructiveHint:c.boolean().optional(),idempotentHint:c.boolean().optional(),openWorldHint:c.boolean().optional()}),Ow=c.object({taskSupport:c.enum(["required","optional","forbidden"]).optional()}),Fu=c.object({..._r.shape,...pn.shape,description:c.string().optional(),inputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),$e).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()),outputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),$e).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()).optional(),annotations:Cw.optional(),execution:Ow.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),qs=fn.extend({method:c.literal("tools/list")}),Nw=hn.extend({tools:c.array(Fu)}),Ms=Te.extend({content:c.array(Wi).default([]),structuredContent:c.record(c.string(),c.unknown()).optional(),isError:c.boolean().optional()}),NE=Ms.or(Te.extend({toolResult:c.unknown()})),jw=dn.extend({name:c.string(),arguments:c.record(c.string(),c.unknown()).optional()}),xr=xe.extend({method:c.literal("tools/call"),params:jw}),zw=Xe.extend({method:c.literal("notifications/tools/list_changed"),params:Qe.optional()}),jE=c.object({autoRefresh:c.boolean().default(!0),debounceMs:c.number().int().nonnegative().default(300)}),bn=c.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),Lw=Ke.extend({level:bn}),Ji=xe.extend({method:c.literal("logging/setLevel"),params:Lw}),Uw=Qe.extend({level:bn,logger:c.string().optional(),data:c.unknown()}),Dw=Xe.extend({method:c.literal("notifications/message"),params:Uw}),qw=c.object({name:c.string().optional()}),Mw=c.object({hints:c.array(qw).optional(),costPriority:c.number().min(0).max(1).optional(),speedPriority:c.number().min(0).max(1).optional(),intelligencePriority:c.number().min(0).max(1).optional()}),Bw=c.object({mode:c.enum(["auto","required","none"]).optional()}),Fw=c.object({type:c.literal("tool_result"),toolUseId:c.string().describe("The unique identifier for the corresponding tool call."),content:c.array(Wi).default([]),structuredContent:c.object({}).loose().optional(),isError:c.boolean().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Hw=c.discriminatedUnion("type",[Ki,Vi,Gi]),_s=c.discriminatedUnion("type",[Ki,Vi,Gi,Tw,Fw]),Kw=c.object({role:yn,content:c.union([_s,c.array(_s)]),_meta:c.record(c.string(),c.unknown()).optional()}),Vw=dn.extend({messages:c.array(Kw),modelPreferences:Mw.optional(),systemPrompt:c.string().optional(),includeContext:c.enum(["none","thisServer","allServers"]).optional(),temperature:c.number().optional(),maxTokens:c.number().int(),stopSequences:c.array(c.string()).optional(),metadata:$e.optional(),tools:c.array(Fu).optional(),toolChoice:Bw.optional()}),Gw=xe.extend({method:c.literal("sampling/createMessage"),params:Vw}),wn=Te.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens"]).or(c.string())),role:yn,content:Hw}),Zi=Te.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(c.string())),role:yn,content:c.union([_s,c.array(_s)])}),Ww=c.object({type:c.literal("boolean"),title:c.string().optional(),description:c.string().optional(),default:c.boolean().optional()}),Jw=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),minLength:c.number().optional(),maxLength:c.number().optional(),format:c.enum(["email","uri","date","date-time"]).optional(),default:c.string().optional()}),Zw=c.object({type:c.enum(["number","integer"]),title:c.string().optional(),description:c.string().optional(),minimum:c.number().optional(),maximum:c.number().optional(),default:c.number().optional()}),Yw=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),enum:c.array(c.string()),default:c.string().optional()}),Qw=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),oneOf:c.array(c.object({const:c.string(),title:c.string()})),default:c.string().optional()}),Xw=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),enum:c.array(c.string()),enumNames:c.array(c.string()).optional(),default:c.string().optional()}),ev=c.union([Yw,Qw]),tv=c.object({type:c.literal("array"),title:c.string().optional(),description:c.string().optional(),minItems:c.number().optional(),maxItems:c.number().optional(),items:c.object({type:c.literal("string"),enum:c.array(c.string())}),default:c.array(c.string()).optional()}),rv=c.object({type:c.literal("array"),title:c.string().optional(),description:c.string().optional(),minItems:c.number().optional(),maxItems:c.number().optional(),items:c.object({anyOf:c.array(c.object({const:c.string(),title:c.string()}))}),default:c.array(c.string()).optional()}),nv=c.union([tv,rv]),sv=c.union([Xw,ev,nv]),ov=c.union([sv,Ww,Jw,Zw]),iv=dn.extend({mode:c.literal("form").optional(),message:c.string(),requestedSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),ov),required:c.array(c.string()).optional()})}),av=dn.extend({mode:c.literal("url"),message:c.string(),elicitationId:c.string(),url:c.string().url()}),cv=c.union([iv,av]),lv=xe.extend({method:c.literal("elicitation/create"),params:cv}),dv=Qe.extend({elicitationId:c.string()}),uv=Xe.extend({method:c.literal("notifications/elicitation/complete"),params:dv}),Tr=Te.extend({action:c.enum(["accept","decline","cancel"]),content:c.preprocess(t=>t===null?void 0:t,c.record(c.string(),c.union([c.string(),c.number(),c.boolean(),c.array(c.string())])).optional())}),pv=c.object({type:c.literal("ref/resource"),uri:c.string()}),fv=c.object({type:c.literal("ref/prompt"),name:c.string()}),hv=Ke.extend({ref:c.union([fv,pv]),argument:c.object({name:c.string(),value:c.string()}),context:c.object({arguments:c.record(c.string(),c.string()).optional()}).optional()}),Bs=xe.extend({method:c.literal("completion/complete"),params:hv});mv=Te.extend({completion:c.looseObject({values:c.array(c.string()).max(100),total:c.optional(c.number().int()),hasMore:c.optional(c.boolean())})}),gv=c.object({uri:c.string().startsWith("file://"),name:c.string().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),yv=xe.extend({method:c.literal("roots/list"),params:Ke.optional()}),Yi=Te.extend({roots:c.array(gv)}),bv=Xe.extend({method:c.literal("notifications/roots/list_changed"),params:Qe.optional()}),zE=c.union([Rs,Mi,Bs,Ji,Ds,Us,js,zs,Ls,yw,ww,xr,qs,Ps,Is,Cs,Ns]),LE=c.union([Ts,Es,Bi,bv,gn]),UE=c.union([xs,wn,Zi,Tr,Yi,As,Os,$r]),DE=c.union([Rs,Gw,lv,yv,Ps,Is,Cs,Ns]),qE=c.union([Ts,Es,Dw,Sw,mw,zw,Iw,gn,uv]),ME=c.union([xs,sw,mv,Aw,kw,uw,pw,hw,Ms,Nw,As,Os,$r]),L=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===q.UrlElicitationRequired&&n){let s=n;if(s.elicitations)return new ji(s.elicitations,r)}return new t(e,r,n)}},ji=class extends L{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(q.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Dt(t){return t==="completed"||t==="failed"||t==="cancelled"}var Vu=N(()=>{});var Wu,Gu,Ju,Fs=N(()=>{Wu=Symbol("Let zodToJsonSchema decide on which parser to use"),Gu={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"},Ju=t=>typeof t=="string"?{...Gu,name:t}:{...Gu,...t}});var Zu,Qi=N(()=>{Fs();Zu=t=>{let e=Ju(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,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function Xi(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function re(t,e,r,n,s){t[e]=r,Xi(t,e,n,s)}var qt=N(()=>{});var Hs,Ks=N(()=>{Hs=(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 be(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Hs(e,t.currentPath):e.join("/")}}var et=N(()=>{Ks()});import{ZodFirstPartyTypeKind as wv}from"zod/v3";function Yu(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==wv.ZodAny&&(r.items=B(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&re(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&re(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(re(r,"minItems",t.exactLength.value,t.exactLength.message,e),re(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var ea=N(()=>{qt();_e()});function Qu(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?re(r,"minimum",n.value,n.message,e):re(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),re(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?re(r,"maximum",n.value,n.message,e):re(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),re(r,"maximum",n.value,n.message,e));break;case"multipleOf":re(r,"multipleOf",n.value,n.message,e);break}return r}var ta=N(()=>{qt()});function Xu(){return{type:"boolean"}}var ra=N(()=>{});function Vs(t,e){return B(t.type._def,e)}var Gs=N(()=>{_e()});var ep,na=N(()=>{_e();ep=(t,e)=>B(t.innerType._def,e)});function sa(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>sa(t,e,s))};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 vv(t,e)}}var vv,oa=N(()=>{qt();vv=(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":re(r,"minimum",n.value,n.message,e);break;case"max":re(r,"maximum",n.value,n.message,e);break}return r}});function tp(t,e){return{...B(t.innerType._def,e),default:t.defaultValue()}}var ia=N(()=>{_e()});function rp(t,e){return e.effectStrategy==="input"?B(t.schema._def,e):be(e)}var aa=N(()=>{_e();et()});function np(t){return{type:"string",enum:Array.from(t.values)}}var ca=N(()=>{});function sp(t,e){let r=[B(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),B(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return r.forEach(o=>{if(Sv(o))s.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let i=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:a,...l}=o;i=l}else n=void 0;s.push(i)}}),s.length?{allOf:s,...n}:void 0}var Sv,la=N(()=>{_e();Sv=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function op(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 da=N(()=>{});function Ws(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":re(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":re(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":at(r,"email",n.message,e);break;case"format:idn-email":at(r,"idn-email",n.message,e);break;case"pattern:zod":je(r,it.email,n.message,e);break}break;case"url":at(r,"uri",n.message,e);break;case"uuid":at(r,"uuid",n.message,e);break;case"regex":je(r,n.regex,n.message,e);break;case"cuid":je(r,it.cuid,n.message,e);break;case"cuid2":je(r,it.cuid2,n.message,e);break;case"startsWith":je(r,RegExp(`^${pa(n.value,e)}`),n.message,e);break;case"endsWith":je(r,RegExp(`${pa(n.value,e)}$`),n.message,e);break;case"datetime":at(r,"date-time",n.message,e);break;case"date":at(r,"date",n.message,e);break;case"time":at(r,"time",n.message,e);break;case"duration":at(r,"duration",n.message,e);break;case"length":re(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),re(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{je(r,RegExp(pa(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&at(r,"ipv4",n.message,e),n.version!=="v4"&&at(r,"ipv6",n.message,e);break}case"base64url":je(r,it.base64url,n.message,e);break;case"jwt":je(r,it.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&je(r,it.ipv4Cidr,n.message,e),n.version!=="v4"&&je(r,it.ipv6Cidr,n.message,e);break}case"emoji":je(r,it.emoji(),n.message,e);break;case"ulid":{je(r,it.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{at(r,"binary",n.message,e);break}case"contentEncoding:base64":{re(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{je(r,it.base64,n.message,e);break}}break}case"nanoid":je(r,it.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function pa(t,e){return e.patternStrategy==="escape"?$v(t):t}function $v(t){let e="";for(let r=0;r<t.length;r++)_v.has(t[r])||(e+="\\"),e+=t[r];return e}function at(t,e,r,n){t.format||t.anyOf?.some(s=>s.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}}})):re(t,"format",e,r,n)}function je(t,e,r,n){t.pattern||t.allOf?.some(s=>s.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:ip(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):re(t,"pattern",ip(e,n),r,n)}function ip(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,s="",o=!1,i=!1,a=!1;for(let l=0;l<n.length;l++){if(o){s+=n[l],o=!1;continue}if(r.i){if(i){if(n[l].match(/[a-z]/)){a?(s+=n[l],s+=`${n[l-2]}-${n[l]}`.toUpperCase(),a=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(s+=n[l],a=!0):s+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){s+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(r.m){if(n[l]==="^"){s+=`(^|(?<=[\r
|
|
880
880
|
]))`;continue}else if(n[l]==="$"){s+=`($|(?=[\r
|
|
881
881
|
]))`;continue}}if(r.s&&n[l]==="."){s+=i?`${n[l]}\r
|
|
882
882
|
`:`[${n[l]}\r
|
|
883
|
-
]`;continue}s+=n[l],n[l]==="\\"?o=!0:i&&n[l]==="]"?i=!1:!i&&n[l]==="["&&(i=!0)}try{new RegExp(s)}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 s}var aa,ot,cv,Gs=O(()=>{jt();ot={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:()=>(aa===void 0&&(aa=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),aa),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-_]*$/};cv=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});import{ZodFirstPartyTypeKind as vn}from"zod/v3";function Ws(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===vn.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,s)=>({...n,[s]:U(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??ge(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:U(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===vn.ZodString&&t.keyType._def.checks?.length){let{type:n,...s}=Vs(t.keyType._def,e);return{...r,propertyNames:s}}else{if(t.keyType?._def.typeName===vn.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===vn.ZodBranded&&t.keyType._def.type._def.typeName===vn.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...s}=Hs(t.keyType._def,e);return{...r,propertyNames:s}}}return r}var Js=O(()=>{ve();Gs();Ks();Xe()});function Xu(t,e){if(e.mapStrategy==="record")return Ws(t,e);let r=U(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||ge(e),n=U(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||ge(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var la=O(()=>{ve();Js();Xe()});function ep(t){let e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}var da=O(()=>{});function tp(t){return t.target==="openAi"?void 0:{not:ge({...t,currentPath:[...t.currentPath,"not"]})}}var ua=O(()=>{Xe()});function rp(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var pa=O(()=>{});function sp(t,e){if(e.target==="openApi3")return np(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in _n&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((s,o)=>{let i=_n[o._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((s,o)=>{let i=typeof o._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];default:return s}},[]);if(n.length===r.length){let s=n.filter((o,i,a)=>a.indexOf(o)===i);return{type:s.length>1?s:s[0],enum:r.reduce((o,i)=>o.includes(i._def.value)?o:[...o,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return np(t,e)}var _n,np,Zs=O(()=>{ve();_n={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};np=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>U(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function op(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:_n[t.innerType._def.typeName],nullable:!0}:{type:[_n[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=U(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=U(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var fa=O(()=>{ve();Zs()});function ip(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",Ji(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ee(r,"minimum",n.value,n.message,e):ee(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ee(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ee(r,"maximum",n.value,n.message,e):ee(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ee(r,"maximum",n.value,n.message,e));break;case"multipleOf":ee(r,"multipleOf",n.value,n.message,e);break}return r}var ha=O(()=>{jt()});function ap(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},s=[],o=t.shape();for(let a in o){let l=o[a];if(l===void 0||l._def===void 0)continue;let u=uv(l);u&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),u=!1);let p=U(l._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});p!==void 0&&(n.properties[a]=p,u||s.push(a))}s.length&&(n.required=s);let i=dv(t,e);return i!==void 0&&(n.additionalProperties=i),n}function dv(t,e){if(t.catchall._def.typeName!=="ZodNever")return U(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 uv(t){try{return t.isOptional()}catch{return!0}}var ma=O(()=>{ve()});var cp,ga=O(()=>{ve();Xe();cp=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return U(t.innerType._def,e);let r=U(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:ge(e)},r]}:ge(e)}});var lp,ya=O(()=>{ve();lp=(t,e)=>{if(e.pipeStrategy==="input")return U(t.in._def,e);if(e.pipeStrategy==="output")return U(t.out._def,e);let r=U(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=U(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}}});function dp(t,e){return U(t.type._def,e)}var ba=O(()=>{ve()});function up(t,e){let n={type:"array",uniqueItems:!0,items:U(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ee(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ee(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var wa=O(()=>{jt();ve()});function pp(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>U(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:U(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>U(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var va=O(()=>{ve()});function fp(t){return{not:ge(t)}}var _a=O(()=>{Xe()});function hp(t){return ge(t)}var Sa=O(()=>{Xe()});var mp,$a=O(()=>{ve();mp=(t,e)=>U(t.innerType._def,e)});import{ZodFirstPartyTypeKind as Y}from"zod/v3";var gp,ka=O(()=>{Xe();Zi();Yi();Qi();Ks();Xi();ta();ra();na();sa();oa();ia();la();da();ua();pa();fa();ha();ma();ga();ya();ba();Js();wa();Gs();va();_a();Zs();Sa();$a();gp=(t,e,r)=>{switch(e){case Y.ZodString:return Vs(t,r);case Y.ZodNumber:return ip(t,r);case Y.ZodObject:return ap(t,r);case Y.ZodBigInt:return Hu(t,r);case Y.ZodBoolean:return Ku();case Y.ZodDate:return ea(t,r);case Y.ZodUndefined:return fp(r);case Y.ZodNull:return rp(r);case Y.ZodArray:return Fu(t,r);case Y.ZodUnion:case Y.ZodDiscriminatedUnion:return sp(t,r);case Y.ZodIntersection:return Zu(t,r);case Y.ZodTuple:return pp(t,r);case Y.ZodRecord:return Ws(t,r);case Y.ZodLiteral:return Yu(t,r);case Y.ZodEnum:return Ju(t);case Y.ZodNativeEnum:return ep(t);case Y.ZodNullable:return op(t,r);case Y.ZodOptional:return cp(t,r);case Y.ZodMap:return Xu(t,r);case Y.ZodSet:return up(t,r);case Y.ZodLazy:return()=>t.getter()._def;case Y.ZodPromise:return dp(t,r);case Y.ZodNaN:case Y.ZodNever:return tp(r);case Y.ZodEffects:return Wu(t,r);case Y.ZodAny:return ge(r);case Y.ZodUnknown:return hp(r);case Y.ZodDefault:return Gu(t,r);case Y.ZodBranded:return Hs(t,r);case Y.ZodReadonly:return mp(t,r);case Y.ZodCatch:return Vu(t,r);case Y.ZodPipeline:return lp(t,r);case Y.ZodFunction:case Y.ZodVoid:case Y.ZodSymbol:return;default:return(n=>{})(e)}}});function U(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==qu)return a}if(n&&!r){let a=pv(n,e);if(a!==void 0)return a}let s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);let o=gp(t,t.typeName,e),i=typeof o=="function"?U(o(),e):o;if(i&&fv(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return s.jsonSchema=i,a}return s.jsonSchema=i,i}var pv,fv,ve=O(()=>{Us();ka();Fs();Xe();pv=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Bs(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`),ge(e)):e.$refStrategy==="seen"?ge(e):void 0}},fv=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var yp=O(()=>{});var xa,Ta=O(()=>{ve();Wi();Xe();xa=(t,e)=>{let r=Bu(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[u,p])=>({...l,[u]:U(p._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??ge(r)}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=U(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??ge(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(o.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=s===void 0?n?{...o,[r.definitionPath]:n}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:o}};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 bp=O(()=>{Us();Wi();jt();Fs();ve();yp();Xe();Zi();Yi();Qi();Ks();Xi();ta();ra();na();sa();oa();ia();la();da();ua();pa();fa();ha();ma();ga();ya();ba();$a();Js();wa();Gs();va();_a();Zs();Sa();ka();Ta();Ta()});import*as wp from"zod/v4-mini";function hv(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Ra(t,e){return ft(t)?wp.toJSONSchema(t,{target:hv(e?.target),io:e?.pipeStrategy??"input"}):xa(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Ea(t){let r=Ct(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=wr(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Pa(t,e){let r=It(t,e);if(!r.success)throw r.error;return r.data}var Aa=O(()=>{ln();bp()});function vp(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function _p(t,e){let r={...t};for(let n in e){let s=n,o=e[s];if(o===void 0)continue;let i=r[s];vp(i)&&vp(o)?r[s]={...i,...o}:r[s]=o}return r}var mv,Ys,Sp=O(()=>{ln();xr();Du();Aa();mv=6e4,Ys=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(ks,r=>{this._oncancel(r)}),this.setNotificationHandler(Ts,r=>{this._onprogress(r)}),this.setRequestHandler(xs,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Rs,async(r,n)=>{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new z(M.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(Ps,async(r,n)=>{let s=async()=>{let o=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(a.type==="response"||a.type==="error"){let l=a.message,u=l.id,p=this._requestResolvers.get(u);if(p)if(this._requestResolvers.delete(u),a.type==="response")p(l);else{let d=l,h=new z(d.error.code,d.error.message,d.error.data);p(h)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(o,n.sessionId);if(!i)throw new z(M.InvalidParams,`Task not found: ${o}`);if(!Nt(i.status))return await this._waitForTaskUpdate(o,n.signal),await s();if(Nt(i.status)){let a=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[Ot]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(As,async(r,n)=>{try{let{tasks:s,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:s,nextCursor:o,_meta:{}}}catch(s){throw new z(M.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(Cs,async(r,n)=>{try{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new z(M.InvalidParams,`Task not found: ${r.params.taskId}`);if(Nt(s.status))throw new z(M.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new z(M.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof z?s:new z(M.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,s,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:s})}_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),z.fromError(M.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=o=>{n?.(o),this._onerror(o)};let s=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{s?.(o,i),un(o)||Ru(o)?this._onresponse(o):Ni(o)?this._onrequest(o,i):Tu(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},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=z.fromError(M.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,s=this._transport,o=e.params?._meta?.[Ot]?.taskId;if(n===void 0){let p={jsonrpc:"2.0",id:e.id,error:{code:M.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:p,timestamp:Date.now()},s?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):s?.send(p).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=$u(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,u={signal:i.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async p=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};o&&(d.relatedTask={taskId:o}),await this.notification(p,d)},sendRequest:async(p,d,h)=>{if(i.signal.aborted)throw new z(M.ConnectionClosed,"Request was cancelled");let g={...h,relatedRequestId:e.id};o&&!g.relatedTask&&(g.relatedTask={taskId:o});let v=g.relatedTask?.taskId??o;return v&&l&&await l.updateTaskStatus(v,"input_required"),await this.request(p,d,g)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:o,taskStore:l,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async p=>{if(i.signal.aborted)return;let d={result:p,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:d,timestamp:Date.now()},s?.sessionId):await s?.send(d)},async p=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(p.code)?p.code:M.InternalError,message:p.message??"Internal error",...p.data!==void 0&&{data:p.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},s?.sessionId):await s?.send(d)}).catch(p=>this._onerror(new Error(`Failed to send response: ${p}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,s=Number(r),o=this._progressHandlers.get(s);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(s),a=this._timeoutInfo.get(s);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(l){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),i(l);return}o(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),un(e))n(e);else{let i=new z(e.error.code,e.error.message,e.error.data);n(i)}return}let s=this._responseHandlers.get(r);if(s===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 o=!1;if(un(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"&&(o=!0,this._taskProgressTokens.set(a.taskId,r))}}if(o||this._progressHandlers.delete(r),un(e))s(e);else{let i=z.fromError(e.error.code,e.error.message,e.error.data);s(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:s}=n??{};if(!s){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof z?i:new z(M.InternalError,String(i))}}return}let o;try{let i=await this.request(e,_r,n);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new z(M.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:a},Nt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:a.status==="failed"?yield{type:"error",error:new z(M.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new z(M.InternalError,`Task ${o} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)};return}let l=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,l)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof z?i:new z(M.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i,task:a,relatedTask:l}=n??{};return new Promise((u,p)=>{let d=N=>{p(N)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(N){d(N);return}n?.signal?.throwIfAborted();let h=this._requestMessageId++,g={...e,jsonrpc:"2.0",id:h};n?.onprogress&&(this._progressHandlers.set(h,n.onprogress),g.params={...e.params,_meta:{...e.params?._meta||{},progressToken:h}}),a&&(g.params={...g.params,task:a}),l&&(g.params={...g.params,_meta:{...g.params?._meta||{},[Ot]:l}});let v=N=>{this._responseHandlers.delete(h),this._progressHandlers.delete(h),this._cleanupTimeout(h),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:h,reason:String(N)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(Q=>this._onerror(new Error(`Failed to send cancellation: ${Q}`)));let D=N instanceof z?N:new z(M.RequestTimeout,String(N));p(D)};this._responseHandlers.set(h,N=>{if(!n?.signal?.aborted){if(N instanceof Error)return p(N);try{let D=It(r,N.result);D.success?u(D.data):p(D.error)}catch(D){p(D)}}}),n?.signal?.addEventListener("abort",()=>{v(n?.signal?.reason)});let _=n?.timeout??mv,T=()=>v(z.fromError(M.RequestTimeout,"Request timed out",{timeout:_}));this._setupTimeout(h,_,n?.maxTotalTimeout,T,n?.resetTimeoutOnProgress??!1);let P=l?.taskId;if(P){let N=D=>{let Q=this._responseHandlers.get(h);Q?Q(D):this._onerror(new Error(`Response handler missing for side-channeled request ${h}`))};this._requestResolvers.set(h,N),this._enqueueTaskMessage(P,{type:"request",message:g,timestamp:Date.now()}).catch(D=>{this._cleanupTimeout(h),p(D)})}else this._transport.send(g,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(N=>{this._cleanupTimeout(h),p(N)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Es,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},Is,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Au,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||{},[Ot]: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||{},[Ot]:r.relatedTask}}}),this._transport?.send(a,r).catch(l=>this._onerror(l))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Ot]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Ea(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{let i=Pa(e,s);return Promise.resolve(r(i,o))})}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=Ea(e);this._notificationHandlers.set(n,s=>{let o=Pa(e,s);return Promise.resolve(r(o))})}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 s=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,s)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let s of n)if(s.type==="request"&&Ni(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new z(M.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e);s?.pollInterval&&(n=s.pollInterval)}catch{}return new Promise((s,o)=>{if(r.aborted){o(new z(M.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(i),o(new z(M.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await n.createTask(s,e.id,{method:e.method,params:e.params},r)},getTask:async s=>{let o=await n.getTask(s,r);if(!o)throw new z(M.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(s,o,i)=>{await n.storeTaskResult(s,o,i,r);let a=await n.getTask(s,r);if(a){let l=gn.parse({method:"notifications/tasks/status",params:a});await this.notification(l),Nt(a.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>n.getTaskResult(s,r),updateTaskStatus:async(s,o,i)=>{let a=await n.getTask(s,r);if(!a)throw new z(M.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(Nt(a.status))throw new z(M.InvalidParams,`Cannot update task "${s}" from terminal status "${a.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(s,o,i,r);let l=await n.getTask(s,r);if(l){let u=gn.parse({method:"notifications/tasks/status",params:l});await this.notification(u),Nt(l.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}}});var kn=j(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.regexpCode=se.getEsmExportName=se.getProperty=se.safeStringify=se.stringify=se.strConcat=se.addCodeArg=se.str=se._=se.nil=se._Code=se.Name=se.IDENTIFIER=se._CodeOrName=void 0;var Sn=class{};se._CodeOrName=Sn;se.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var er=class extends Sn{constructor(e){if(super(),!se.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};se.Name=er;var et=class extends Sn{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 er&&(r[n.str]=(r[n.str]||0)+1),r),{})}};se._Code=et;se.nil=new et("");function $p(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Ca(r,e[n]),r.push(t[++n]);return new et(r)}se._=$p;var Ia=new et("+");function kp(t,...e){let r=[$n(t[0])],n=0;for(;n<e.length;)r.push(Ia),Ca(r,e[n]),r.push(Ia,$n(t[++n]));return gv(r),new et(r)}se.str=kp;function Ca(t,e){e instanceof et?t.push(...e._items):e instanceof er?t.push(e):t.push(wv(e))}se.addCodeArg=Ca;function gv(t){let e=1;for(;e<t.length-1;){if(t[e]===Ia){let r=yv(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function yv(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof er||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 er))return`"${t}${e.slice(1)}`}function bv(t,e){return e.emptyStr()?t:t.emptyStr()?e:kp`${t}${e}`}se.strConcat=bv;function wv(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:$n(Array.isArray(t)?t.join(","):t)}function vv(t){return new et($n(t))}se.stringify=vv;function $n(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}se.safeStringify=$n;function _v(t){return typeof t=="string"&&se.IDENTIFIER.test(t)?new et(`.${t}`):$p`[${t}]`}se.getProperty=_v;function Sv(t){if(typeof t=="string"&&se.IDENTIFIER.test(t))return new et(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}se.getEsmExportName=Sv;function $v(t){return new et(t.toString())}se.regexpCode=$v});var ja=j(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.ValueScope=Ue.ValueScopeName=Ue.Scope=Ue.varKinds=Ue.UsedValueState=void 0;var qe=kn(),Oa=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Qs;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Qs||(Ue.UsedValueState=Qs={}));Ue.varKinds={const:new qe.Name("const"),let:new qe.Name("let"),var:new qe.Name("var")};var Xs=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof qe.Name?e:this.name(e)}name(e){return new qe.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}}};Ue.Scope=Xs;var eo=class extends qe.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,qe._)`.${new qe.Name(r)}[${n}]`}};Ue.ValueScopeName=eo;var kv=(0,qe._)`\n`,Na=class extends Xs{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?kv:qe.nil}}get(){return this._scope}name(e){return new eo(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 s=this.toName(e),{prefix:o}=s,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[o];if(a){let p=a.get(i);if(p)return p}else a=this._values[o]=new Map;a.set(i,s);let l=this._scope[o]||(this._scope[o]=[]),u=l.length;return l[u]=r.ref,s.setValue(r,{property:o,itemIndex:u}),s}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,qe._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,s=>{if(s.value===void 0)throw new Error(`CodeGen: name "${s}" has no value`);return s.value.code},r,n)}_reduceValues(e,r,n={},s){let o=qe.nil;for(let i in e){let a=e[i];if(!a)continue;let l=n[i]=n[i]||new Map;a.forEach(u=>{if(l.has(u))return;l.set(u,Qs.Started);let p=r(u);if(p){let d=this.opts.es5?Ue.varKinds.var:Ue.varKinds.const;o=(0,qe._)`${o}${d} ${u} = ${p};${this.opts._n}`}else if(p=s?.(u))o=(0,qe._)`${o}${p}${this.opts._n}`;else throw new Oa(u);l.set(u,Qs.Completed)})}return o}};Ue.ValueScope=Na});var V=j(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.or=W.and=W.not=W.CodeGen=W.operators=W.varKinds=W.ValueScopeName=W.ValueScope=W.Scope=W.Name=W.regexpCode=W.stringify=W.getProperty=W.nil=W.strConcat=W.str=W._=void 0;var te=kn(),at=ja(),zt=kn();Object.defineProperty(W,"_",{enumerable:!0,get:function(){return zt._}});Object.defineProperty(W,"str",{enumerable:!0,get:function(){return zt.str}});Object.defineProperty(W,"strConcat",{enumerable:!0,get:function(){return zt.strConcat}});Object.defineProperty(W,"nil",{enumerable:!0,get:function(){return zt.nil}});Object.defineProperty(W,"getProperty",{enumerable:!0,get:function(){return zt.getProperty}});Object.defineProperty(W,"stringify",{enumerable:!0,get:function(){return zt.stringify}});Object.defineProperty(W,"regexpCode",{enumerable:!0,get:function(){return zt.regexpCode}});Object.defineProperty(W,"Name",{enumerable:!0,get:function(){return zt.Name}});var so=ja();Object.defineProperty(W,"Scope",{enumerable:!0,get:function(){return so.Scope}});Object.defineProperty(W,"ValueScope",{enumerable:!0,get:function(){return so.ValueScope}});Object.defineProperty(W,"ValueScopeName",{enumerable:!0,get:function(){return so.ValueScopeName}});Object.defineProperty(W,"varKinds",{enumerable:!0,get:function(){return so.varKinds}});W.operators={GT:new te._Code(">"),GTE:new te._Code(">="),LT:new te._Code("<"),LTE:new te._Code("<="),EQ:new te._Code("==="),NEQ:new te._Code("!=="),NOT:new te._Code("!"),OR:new te._Code("||"),AND:new te._Code("&&"),ADD:new te._Code("+")};var vt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},za=class extends vt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?at.varKinds.var:this.varKind,s=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${s};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Rr(this.rhs,e,r)),this}get names(){return this.rhs instanceof te._CodeOrName?this.rhs.names:{}}},to=class extends vt{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 te.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Rr(this.rhs,e,r),this}get names(){let e=this.lhs instanceof te.Name?{}:{...this.lhs.names};return no(e,this.rhs)}},La=class extends to{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Da=class extends vt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Ma=class extends vt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},qa=class extends vt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Ua=class extends vt{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=Rr(this.code,e,r),this}get names(){return this.code instanceof te._CodeOrName?this.code.names:{}}},xn=class extends vt{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,s=n.length;for(;s--;){let o=n[s];o.optimizeNames(e,r)||(xv(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>nr(e,r.names),{})}},_t=class extends xn{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Ba=class extends xn{},Tr=class extends _t{};Tr.kind="else";var tr=class t extends _t{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 Tr(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(xp(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=Rr(this.condition,e,r),this}get names(){let e=super.names;return no(e,this.condition),this.else&&nr(e,this.else.names),e}};tr.kind="if";var rr=class extends _t{};rr.kind="for";var Fa=class extends rr{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=Rr(this.iteration,e,r),this}get names(){return nr(super.names,this.iteration.names)}},Ha=class extends rr{constructor(e,r,n,s){super(),this.varKind=e,this.name=r,this.from=n,this.to=s}render(e){let r=e.es5?at.varKinds.var:this.varKind,{name:n,from:s,to:o}=this;return`for(${r} ${n}=${s}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=no(super.names,this.from);return no(e,this.to)}},ro=class extends rr{constructor(e,r,n,s){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=s}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=Rr(this.iterable,e,r),this}get names(){return nr(super.names,this.iterable.names)}},Tn=class extends _t{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)}};Tn.kind="func";var Rn=class extends xn{render(e){return"return "+super.render(e)}};Rn.kind="return";var Ka=class extends _t{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,s;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(s=this.finally)===null||s===void 0||s.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&nr(e,this.catch.names),this.finally&&nr(e,this.finally.names),e}},En=class extends _t{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};En.kind="catch";var Pn=class extends _t{render(e){return"finally"+super.render(e)}};Pn.kind="finally";var Va=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
884
|
-
`:""},this._extScope=e,this._scope=new at.Scope({parent:e}),this._nodes=[new Ba]}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,s){let o=this._scope.toName(r);return n!==void 0&&s&&(this._constants[o.str]=n),this._leafNode(new za(e,o,n)),o}const(e,r,n){return this._def(at.varKinds.const,e,r,n)}let(e,r,n){return this._def(at.varKinds.let,e,r,n)}var(e,r,n){return this._def(at.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new to(e,r,n))}add(e,r){return this._leafNode(new La(e,W.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==te.nil&&this._leafNode(new Ua(e)),this}object(...e){let r=["{"];for(let[n,s]of e)r.length>1&&r.push(","),r.push(n),(n!==s||this.opts.es5)&&(r.push(":"),(0,te.addCodeArg)(r,s));return r.push("}"),new te._Code(r)}if(e,r,n){if(this._blockNode(new tr(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 tr(e))}else(){return this._elseNode(new Tr)}endIf(){return this._endBlockNode(tr,Tr)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Fa(e),r)}forRange(e,r,n,s,o=this.opts.es5?at.varKinds.var:at.varKinds.let){let i=this._scope.toName(e);return this._for(new Ha(o,i,r,n),()=>s(i))}forOf(e,r,n,s=at.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=r instanceof te.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,te._)`${i}.length`,a=>{this.var(o,(0,te._)`${i}[${a}]`),n(o)})}return this._for(new ro("of",s,o,r),()=>n(o))}forIn(e,r,n,s=this.opts.es5?at.varKinds.var:at.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,te._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new ro("in",s,o,r),()=>n(o))}endFor(){return this._endBlockNode(rr)}label(e){return this._leafNode(new Da(e))}break(e){return this._leafNode(new Ma(e))}return(e){let r=new Rn;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Rn)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new Ka;if(this._blockNode(s),this.code(e),r){let o=this.name("e");this._currNode=s.catch=new En(o),r(o)}return n&&(this._currNode=s.finally=new Pn,this.code(n)),this._endBlockNode(En,Pn)}throw(e){return this._leafNode(new qa(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=te.nil,n,s){return this._blockNode(new Tn(e,r,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(Tn)}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 tr))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}};W.CodeGen=Va;function nr(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function no(t,e){return e instanceof te._CodeOrName?nr(t,e.names):t}function Rr(t,e,r){if(t instanceof te.Name)return n(t);if(!s(t))return t;return new te._Code(t._items.reduce((o,i)=>(i instanceof te.Name&&(i=n(i)),i instanceof te._Code?o.push(...i._items):o.push(i),o),[]));function n(o){let i=r[o.str];return i===void 0||e[o.str]!==1?o:(delete e[o.str],i)}function s(o){return o instanceof te._Code&&o._items.some(i=>i instanceof te.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function xv(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function xp(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,te._)`!${Ga(t)}`}W.not=xp;var Tv=Tp(W.operators.AND);function Rv(...t){return t.reduce(Tv)}W.and=Rv;var Ev=Tp(W.operators.OR);function Pv(...t){return t.reduce(Ev)}W.or=Pv;function Tp(t){return(e,r)=>e===te.nil?r:r===te.nil?e:(0,te._)`${Ga(e)} ${t} ${Ga(r)}`}function Ga(t){return t instanceof te.Name?t:(0,te._)`(${t})`}});var re=j(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.checkStrictMode=Z.getErrorPath=Z.Type=Z.useFunc=Z.setEvaluated=Z.evaluatedPropsToName=Z.mergeEvaluated=Z.eachItem=Z.unescapeJsonPointer=Z.escapeJsonPointer=Z.escapeFragment=Z.unescapeFragment=Z.schemaRefOrVal=Z.schemaHasRulesButRef=Z.schemaHasRules=Z.checkUnknownRules=Z.alwaysValidSchema=Z.toHash=void 0;var ue=V(),Av=kn();function Iv(t){let e={};for(let r of t)e[r]=!0;return e}Z.toHash=Iv;function Cv(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Pp(t,e),!Ap(e,t.self.RULES.all))}Z.alwaysValidSchema=Cv;function Pp(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let s=n.RULES.keywords;for(let o in e)s[o]||Op(t,`unknown keyword: "${o}"`)}Z.checkUnknownRules=Pp;function Ap(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}Z.schemaHasRules=Ap;function Ov(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}Z.schemaHasRulesButRef=Ov;function Nv({topSchemaRef:t,schemaPath:e},r,n,s){if(!s){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ue._)`${r}`}return(0,ue._)`${t}${e}${(0,ue.getProperty)(n)}`}Z.schemaRefOrVal=Nv;function jv(t){return Ip(decodeURIComponent(t))}Z.unescapeFragment=jv;function zv(t){return encodeURIComponent(Ja(t))}Z.escapeFragment=zv;function Ja(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}Z.escapeJsonPointer=Ja;function Ip(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}Z.unescapeJsonPointer=Ip;function Lv(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}Z.eachItem=Lv;function Rp({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(s,o,i,a)=>{let l=i===void 0?o:i instanceof ue.Name?(o instanceof ue.Name?t(s,o,i):e(s,o,i),i):o instanceof ue.Name?(e(s,i,o),o):r(o,i);return a===ue.Name&&!(l instanceof ue.Name)?n(s,l):l}}Z.mergeEvaluated={props:Rp({mergeNames:(t,e,r)=>t.if((0,ue._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,ue._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,ue._)`${r} || {}`).code((0,ue._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,ue._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,ue._)`${r} || {}`),Za(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Cp}),items:Rp({mergeNames:(t,e,r)=>t.if((0,ue._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,ue._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,ue._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,ue._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Cp(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,ue._)`{}`);return e!==void 0&&Za(t,r,e),r}Z.evaluatedPropsToName=Cp;function Za(t,e,r){Object.keys(r).forEach(n=>t.assign((0,ue._)`${e}${(0,ue.getProperty)(n)}`,!0))}Z.setEvaluated=Za;var Ep={};function Dv(t,e){return t.scopeValue("func",{ref:e,code:Ep[e.code]||(Ep[e.code]=new Av._Code(e.code))})}Z.useFunc=Dv;var Wa;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Wa||(Z.Type=Wa={}));function Mv(t,e,r){if(t instanceof ue.Name){let n=e===Wa.Num;return r?n?(0,ue._)`"[" + ${t} + "]"`:(0,ue._)`"['" + ${t} + "']"`:n?(0,ue._)`"/" + ${t}`:(0,ue._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ue.getProperty)(t).toString():"/"+Ja(t)}Z.getErrorPath=Mv;function Op(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}Z.checkStrictMode=Op});var St=j(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});var Pe=V(),qv={data:new Pe.Name("data"),valCxt:new Pe.Name("valCxt"),instancePath:new Pe.Name("instancePath"),parentData:new Pe.Name("parentData"),parentDataProperty:new Pe.Name("parentDataProperty"),rootData:new Pe.Name("rootData"),dynamicAnchors:new Pe.Name("dynamicAnchors"),vErrors:new Pe.Name("vErrors"),errors:new Pe.Name("errors"),this:new Pe.Name("this"),self:new Pe.Name("self"),scope:new Pe.Name("scope"),json:new Pe.Name("json"),jsonPos:new Pe.Name("jsonPos"),jsonLen:new Pe.Name("jsonLen"),jsonPart:new Pe.Name("jsonPart")};Ya.default=qv});var An=j(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.extendErrors=Ae.resetErrorsCount=Ae.reportExtraError=Ae.reportError=Ae.keyword$DataError=Ae.keywordError=void 0;var ne=V(),oo=re(),je=St();Ae.keywordError={message:({keyword:t})=>(0,ne.str)`must pass "${t}" keyword validation`};Ae.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ne.str)`"${t}" keyword must be ${e} ($data)`:(0,ne.str)`"${t}" keyword is invalid ($data)`};function Uv(t,e=Ae.keywordError,r,n){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,l=zp(t,e,r);n??(i||a)?Np(o,l):jp(s,(0,ne._)`[${l}]`)}Ae.reportError=Uv;function Bv(t,e=Ae.keywordError,r){let{it:n}=t,{gen:s,compositeRule:o,allErrors:i}=n,a=zp(t,e,r);Np(s,a),o||i||jp(n,je.default.vErrors)}Ae.reportExtraError=Bv;function Fv(t,e){t.assign(je.default.errors,e),t.if((0,ne._)`${je.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ne._)`${je.default.vErrors}.length`,e),()=>t.assign(je.default.vErrors,null)))}Ae.resetErrorsCount=Fv;function Hv({gen:t,keyword:e,schemaValue:r,data:n,errsCount:s,it:o}){if(s===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",s,je.default.errors,a=>{t.const(i,(0,ne._)`${je.default.vErrors}[${a}]`),t.if((0,ne._)`${i}.instancePath === undefined`,()=>t.assign((0,ne._)`${i}.instancePath`,(0,ne.strConcat)(je.default.instancePath,o.errorPath))),t.assign((0,ne._)`${i}.schemaPath`,(0,ne.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,ne._)`${i}.schema`,r),t.assign((0,ne._)`${i}.data`,n))})}Ae.extendErrors=Hv;function Np(t,e){let r=t.const("err",e);t.if((0,ne._)`${je.default.vErrors} === null`,()=>t.assign(je.default.vErrors,(0,ne._)`[${r}]`),(0,ne._)`${je.default.vErrors}.push(${r})`),t.code((0,ne._)`${je.default.errors}++`)}function jp(t,e){let{gen:r,validateName:n,schemaEnv:s}=t;s.$async?r.throw((0,ne._)`new ${t.ValidationError}(${e})`):(r.assign((0,ne._)`${n}.errors`,e),r.return(!1))}var sr={keyword:new ne.Name("keyword"),schemaPath:new ne.Name("schemaPath"),params:new ne.Name("params"),propertyName:new ne.Name("propertyName"),message:new ne.Name("message"),schema:new ne.Name("schema"),parentSchema:new ne.Name("parentSchema")};function zp(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,ne._)`{}`:Kv(t,e,r)}function Kv(t,e,r={}){let{gen:n,it:s}=t,o=[Vv(s,r),Gv(t,r)];return Wv(t,e,o),n.object(...o)}function Vv({errorPath:t},{instancePath:e}){let r=e?(0,ne.str)`${t}${(0,oo.getErrorPath)(e,oo.Type.Str)}`:t;return[je.default.instancePath,(0,ne.strConcat)(je.default.instancePath,r)]}function Gv({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let s=n?e:(0,ne.str)`${e}/${t}`;return r&&(s=(0,ne.str)`${s}${(0,oo.getErrorPath)(r,oo.Type.Str)}`),[sr.schemaPath,s]}function Wv(t,{params:e,message:r},n){let{keyword:s,data:o,schemaValue:i,it:a}=t,{opts:l,propertyName:u,topSchemaRef:p,schemaPath:d}=a;n.push([sr.keyword,s],[sr.params,typeof e=="function"?e(t):e||(0,ne._)`{}`]),l.messages&&n.push([sr.message,typeof r=="function"?r(t):r]),l.verbose&&n.push([sr.schema,i],[sr.parentSchema,(0,ne._)`${p}${d}`],[je.default.data,o]),u&&n.push([sr.propertyName,u])}});var Dp=j(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.boolOrEmptySchema=Er.topBoolOrEmptySchema=void 0;var Jv=An(),Zv=V(),Yv=St(),Qv={message:"boolean schema is false"};function Xv(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Lp(t,!1):typeof r=="object"&&r.$async===!0?e.return(Yv.default.data):(e.assign((0,Zv._)`${n}.errors`,null),e.return(!0))}Er.topBoolOrEmptySchema=Xv;function e_(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Lp(t)):r.var(e,!0)}Er.boolOrEmptySchema=e_;function Lp(t,e){let{gen:r,data:n}=t,s={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,Jv.reportError)(s,Qv,void 0,e)}});var Qa=j(Pr=>{"use strict";Object.defineProperty(Pr,"__esModule",{value:!0});Pr.getRules=Pr.isJSONType=void 0;var t_=["string","number","integer","boolean","null","object","array"],r_=new Set(t_);function n_(t){return typeof t=="string"&&r_.has(t)}Pr.isJSONType=n_;function s_(){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:{}}}Pr.getRules=s_});var Xa=j(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.shouldUseRule=Lt.shouldUseGroup=Lt.schemaHasRulesForType=void 0;function o_({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Mp(t,n)}Lt.schemaHasRulesForType=o_;function Mp(t,e){return e.rules.some(r=>qp(t,r))}Lt.shouldUseGroup=Mp;function qp(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))}Lt.shouldUseRule=qp});var In=j(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.reportTypeError=Ie.checkDataTypes=Ie.checkDataType=Ie.coerceAndCheckDataType=Ie.getJSONTypes=Ie.getSchemaTypes=Ie.DataType=void 0;var i_=Qa(),a_=Xa(),c_=An(),K=V(),Up=re(),Ar;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Ar||(Ie.DataType=Ar={}));function l_(t){let e=Bp(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}Ie.getSchemaTypes=l_;function Bp(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(i_.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ie.getJSONTypes=Bp;function d_(t,e){let{gen:r,data:n,opts:s}=t,o=u_(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,a_.schemaHasRulesForType)(t,e[0]));if(i){let a=tc(e,n,s.strictNumbers,Ar.Wrong);r.if(a,()=>{o.length?p_(t,e,o):rc(t)})}return i}Ie.coerceAndCheckDataType=d_;var Fp=new Set(["string","number","integer","boolean","null"]);function u_(t,e){return e?t.filter(r=>Fp.has(r)||e==="array"&&r==="array"):[]}function p_(t,e,r){let{gen:n,data:s,opts:o}=t,i=n.let("dataType",(0,K._)`typeof ${s}`),a=n.let("coerced",(0,K._)`undefined`);o.coerceTypes==="array"&&n.if((0,K._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,(0,K._)`${s}[0]`).assign(i,(0,K._)`typeof ${s}`).if(tc(e,s,o.strictNumbers),()=>n.assign(a,s))),n.if((0,K._)`${a} !== undefined`);for(let u of r)(Fp.has(u)||u==="array"&&o.coerceTypes==="array")&&l(u);n.else(),rc(t),n.endIf(),n.if((0,K._)`${a} !== undefined`,()=>{n.assign(s,a),f_(t,a)});function l(u){switch(u){case"string":n.elseIf((0,K._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,K._)`"" + ${s}`).elseIf((0,K._)`${s} === null`).assign(a,(0,K._)`""`);return;case"number":n.elseIf((0,K._)`${i} == "boolean" || ${s} === null
|
|
885
|
-
|| (${i} == "string" && ${s} && ${s} == +${s})`).assign(a,(0,
|
|
886
|
-
|| (${i} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(a,(0,
|
|
887
|
-
|| ${i} === "boolean" || ${s} === null`).assign(a,(0,K._)`[${s}]`)}}}function f_({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,K._)`${e} !== undefined`,()=>t.assign((0,K._)`${e}[${r}]`,n))}function ec(t,e,r,n=Ar.Correct){let s=n===Ar.Correct?K.operators.EQ:K.operators.NEQ,o;switch(t){case"null":return(0,K._)`${e} ${s} null`;case"array":o=(0,K._)`Array.isArray(${e})`;break;case"object":o=(0,K._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,K._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,K._)`typeof ${e} ${s} ${t}`}return n===Ar.Correct?o:(0,K.not)(o);function i(a=K.nil){return(0,K.and)((0,K._)`typeof ${e} == "number"`,a,r?(0,K._)`isFinite(${e})`:K.nil)}}Ie.checkDataType=ec;function tc(t,e,r,n){if(t.length===1)return ec(t[0],e,r,n);let s,o=(0,Up.toHash)(t);if(o.array&&o.object){let i=(0,K._)`typeof ${e} != "object"`;s=o.null?i:(0,K._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=K.nil;o.number&&delete o.integer;for(let i in o)s=(0,K.and)(s,ec(i,e,r,n));return s}Ie.checkDataTypes=tc;var h_={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,K._)`{type: ${t}}`:(0,K._)`{type: ${e}}`};function rc(t){let e=m_(t);(0,c_.reportError)(e,h_)}Ie.reportTypeError=rc;function m_(t){let{gen:e,data:r,schema:n}=t,s=(0,Up.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var Kp=j(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});io.assignDefaults=void 0;var Ir=V(),g_=re();function y_(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)Hp(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,o)=>Hp(t,o,s.default))}io.assignDefaults=y_;function Hp(t,e,r){let{gen:n,compositeRule:s,data:o,opts:i}=t;if(r===void 0)return;let a=(0,Ir._)`${o}${(0,Ir.getProperty)(e)}`;if(s){(0,g_.checkStrictMode)(t,`default is ignored for: ${a}`);return}let l=(0,Ir._)`${a} === undefined`;i.useDefaults==="empty"&&(l=(0,Ir._)`${l} || ${a} === null || ${a} === ""`),n.if(l,(0,Ir._)`${a} = ${(0,Ir.stringify)(r)}`)}});var tt=j(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.validateUnion=de.validateArray=de.usePattern=de.callValidateCode=de.schemaProperties=de.allSchemaProperties=de.noPropertyInData=de.propertyInData=de.isOwnProperty=de.hasPropFunc=de.reportMissingProp=de.checkMissingProp=de.checkReportMissingProp=void 0;var fe=V(),nc=re(),Dt=St(),b_=re();function w_(t,e){let{gen:r,data:n,it:s}=t;r.if(oc(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,fe._)`${e}`},!0),t.error()})}de.checkReportMissingProp=w_;function v_({gen:t,data:e,it:{opts:r}},n,s){return(0,fe.or)(...n.map(o=>(0,fe.and)(oc(t,e,o,r.ownProperties),(0,fe._)`${s} = ${o}`)))}de.checkMissingProp=v_;function __(t,e){t.setParams({missingProperty:e},!0),t.error()}de.reportMissingProp=__;function Vp(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,fe._)`Object.prototype.hasOwnProperty`})}de.hasPropFunc=Vp;function sc(t,e,r){return(0,fe._)`${Vp(t)}.call(${e}, ${r})`}de.isOwnProperty=sc;function S_(t,e,r,n){let s=(0,fe._)`${e}${(0,fe.getProperty)(r)} !== undefined`;return n?(0,fe._)`${s} && ${sc(t,e,r)}`:s}de.propertyInData=S_;function oc(t,e,r,n){let s=(0,fe._)`${e}${(0,fe.getProperty)(r)} === undefined`;return n?(0,fe.or)(s,(0,fe.not)(sc(t,e,r))):s}de.noPropertyInData=oc;function Gp(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}de.allSchemaProperties=Gp;function $_(t,e){return Gp(e).filter(r=>!(0,nc.alwaysValidSchema)(t,e[r]))}de.schemaProperties=$_;function k_({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:o},it:i},a,l,u){let p=u?(0,fe._)`${t}, ${e}, ${n}${s}`:e,d=[[Dt.default.instancePath,(0,fe.strConcat)(Dt.default.instancePath,o)],[Dt.default.parentData,i.parentData],[Dt.default.parentDataProperty,i.parentDataProperty],[Dt.default.rootData,Dt.default.rootData]];i.opts.dynamicRef&&d.push([Dt.default.dynamicAnchors,Dt.default.dynamicAnchors]);let h=(0,fe._)`${p}, ${r.object(...d)}`;return l!==fe.nil?(0,fe._)`${a}.call(${l}, ${h})`:(0,fe._)`${a}(${h})`}de.callValidateCode=k_;var x_=(0,fe._)`new RegExp`;function T_({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:s}=e.code,o=s(r,n);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,fe._)`${s.code==="new RegExp"?x_:(0,b_.useFunc)(t,s)}(${r}, ${n})`})}de.usePattern=T_;function R_(t){let{gen:e,data:r,keyword:n,it:s}=t,o=e.name("valid");if(s.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(o,!0),i(()=>e.break()),o;function i(a){let l=e.const("len",(0,fe._)`${r}.length`);e.forRange("i",0,l,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:nc.Type.Num},o),e.if((0,fe.not)(o),a)})}}de.validateArray=R_;function E_(t){let{gen:e,schema:r,keyword:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0,nc.alwaysValidSchema)(s,l))&&!s.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((l,u)=>{let p=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,fe._)`${i} || ${a}`),t.mergeValidEvaluated(p,a)||e.if((0,fe.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}de.validateUnion=E_});var Zp=j(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.validateKeywordUsage=ht.validSchemaType=ht.funcKeywordCode=ht.macroKeywordCode=void 0;var ze=V(),or=St(),P_=tt(),A_=An();function I_(t,e){let{gen:r,keyword:n,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),l=Jp(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:ze.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}ht.macroKeywordCode=I_;function C_(t,e){var r;let{gen:n,keyword:s,schema:o,parentSchema:i,$data:a,it:l}=t;N_(l,e);let u=!a&&e.compile?e.compile.call(l.self,o,i,l):e.validate,p=Jp(n,s,u),d=n.let("valid");t.block$data(d,h),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function h(){if(e.errors===!1)_(),e.modifying&&Wp(t),T(()=>t.error());else{let P=e.async?g():v();e.modifying&&Wp(t),T(()=>O_(t,P))}}function g(){let P=n.let("ruleErrs",null);return n.try(()=>_((0,ze._)`await `),N=>n.assign(d,!1).if((0,ze._)`${N} instanceof ${l.ValidationError}`,()=>n.assign(P,(0,ze._)`${N}.errors`),()=>n.throw(N))),P}function v(){let P=(0,ze._)`${p}.errors`;return n.assign(P,null),_(ze.nil),P}function _(P=e.async?(0,ze._)`await `:ze.nil){let N=l.opts.passContext?or.default.this:or.default.self,D=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,ze._)`${P}${(0,P_.callValidateCode)(t,p,N,D)}`,e.modifying)}function T(P){var N;n.if((0,ze.not)((N=e.valid)!==null&&N!==void 0?N:d),P)}}ht.funcKeywordCode=C_;function Wp(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,ze._)`${n.parentData}[${n.parentDataProperty}]`))}function O_(t,e){let{gen:r}=t;r.if((0,ze._)`Array.isArray(${e})`,()=>{r.assign(or.default.vErrors,(0,ze._)`${or.default.vErrors} === null ? ${e} : ${or.default.vErrors}.concat(${e})`).assign(or.default.errors,(0,ze._)`${or.default.vErrors}.length`),(0,A_.extendErrors)(t)},()=>t.error())}function N_({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Jp(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,ze.stringify)(r)})}function j_(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")}ht.validSchemaType=j_;function z_({schema:t,opts:e,self:r,errSchemaPath:n},s,o){if(Array.isArray(s.keyword)?!s.keyword.includes(o):s.keyword!==o)throw new Error("ajv implementation error");let i=s.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${o}: ${i.join(",")}`);if(s.validateSchema&&!s.validateSchema(t[o])){let l=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}ht.validateKeywordUsage=z_});var Qp=j(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.extendSubschemaMode=Mt.extendSubschemaData=Mt.getSubschema=void 0;var mt=V(),Yp=re();function L_(t,{keyword:e,schemaProp:r,schema:n,schemaPath:s,errSchemaPath:o,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,mt._)`${t.schemaPath}${(0,mt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,mt._)`${t.schemaPath}${(0,mt.getProperty)(e)}${(0,mt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Yp.escapeFragment)(r)}`}}if(n!==void 0){if(s===void 0||o===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:s,topSchemaRef:i,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}Mt.getSubschema=L_;function D_(t,e,{dataProp:r,dataPropType:n,data:s,dataTypes:o,propertyName:i}){if(s!==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:u,dataPathArr:p,opts:d}=e,h=a.let("data",(0,mt._)`${e.data}${(0,mt.getProperty)(r)}`,!0);l(h),t.errorPath=(0,mt.str)`${u}${(0,Yp.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,mt._)`${r}`,t.dataPathArr=[...p,t.parentDataProperty]}if(s!==void 0){let u=s instanceof mt.Name?s:a.let("data",s,!0);l(u),i!==void 0&&(t.propertyName=i)}o&&(t.dataTypes=o);function l(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}Mt.extendSubschemaData=D_;function M_(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:s,allErrors:o}){n!==void 0&&(t.compositeRule=n),s!==void 0&&(t.createErrors=s),o!==void 0&&(t.allErrors=o),t.jtdDiscriminator=e,t.jtdMetadata=r}Mt.extendSubschemaMode=M_});var ic=j((LI,Xp)=>{"use strict";Xp.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,s,o;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(s=n;s--!==0;)if(!t(e[s],r[s]))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(o=Object.keys(e),n=o.length,n!==Object.keys(r).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[s]))return!1;for(s=n;s--!==0;){var i=o[s];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var tf=j((DI,ef)=>{"use strict";var qt=ef.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},s=r.post||function(){};ao(e,n,s,t,"",t)};qt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};qt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};qt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};qt.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 ao(t,e,r,n,s,o,i,a,l,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,s,o,i,a,l,u);for(var p in n){var d=n[p];if(Array.isArray(d)){if(p in qt.arrayKeywords)for(var h=0;h<d.length;h++)ao(t,e,r,d[h],s+"/"+p+"/"+h,o,s,p,n,h)}else if(p in qt.propsKeywords){if(d&&typeof d=="object")for(var g in d)ao(t,e,r,d[g],s+"/"+p+"/"+q_(g),o,s,p,n,g)}else(p in qt.keywords||t.allKeys&&!(p in qt.skipKeywords))&&ao(t,e,r,d,s+"/"+p,o,s,p,n)}r(n,s,o,i,a,l,u)}}function q_(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Cn=j(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.getSchemaRefs=Be.resolveUrl=Be.normalizeId=Be._getFullPath=Be.getFullPath=Be.inlineRef=void 0;var U_=re(),B_=ic(),F_=tf(),H_=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function K_(t,e=!0){return typeof t=="boolean"?!0:e===!0?!ac(t):e?rf(t)<=e:!1}Be.inlineRef=K_;var V_=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function ac(t){for(let e in t){if(V_.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(ac)||typeof r=="object"&&ac(r))return!0}return!1}function rf(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!H_.has(r)&&(typeof t[r]=="object"&&(0,U_.eachItem)(t[r],n=>e+=rf(n)),e===1/0))return 1/0}return e}function nf(t,e="",r){r!==!1&&(e=Cr(e));let n=t.parse(e);return sf(t,n)}Be.getFullPath=nf;function sf(t,e){return t.serialize(e).split("#")[0]+"#"}Be._getFullPath=sf;var G_=/#\/?$/;function Cr(t){return t?t.replace(G_,""):""}Be.normalizeId=Cr;function W_(t,e,r){return r=Cr(r),t.resolve(e,r)}Be.resolveUrl=W_;var J_=/^[a-z_][-a-z0-9._]*$/i;function Z_(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=Cr(t[r]||e),o={"":s},i=nf(n,s,!1),a={},l=new Set;return F_(t,{allKeys:!0},(d,h,g,v)=>{if(v===void 0)return;let _=i+h,T=o[v];typeof d[r]=="string"&&(T=P.call(this,d[r])),N.call(this,d.$anchor),N.call(this,d.$dynamicAnchor),o[h]=T;function P(D){let Q=this.opts.uriResolver.resolve;if(D=Cr(T?Q(T,D):D),l.has(D))throw p(D);l.add(D);let B=this.refs[D];return typeof B=="string"&&(B=this.refs[B]),typeof B=="object"?u(d,B.schema,D):D!==Cr(_)&&(D[0]==="#"?(u(d,a[D],D),a[D]=d):this.refs[D]=_),D}function N(D){if(typeof D=="string"){if(!J_.test(D))throw new Error(`invalid anchor "${D}"`);P.call(this,`#${D}`)}}}),a;function u(d,h,g){if(h!==void 0&&!B_(d,h))throw p(g)}function p(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Be.getSchemaRefs=Z_});var jn=j(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.getData=Ut.KeywordCxt=Ut.validateFunctionCode=void 0;var df=Dp(),of=In(),lc=Xa(),co=In(),Y_=Kp(),Nn=Zp(),cc=Qp(),L=V(),F=St(),Q_=Cn(),$t=re(),On=An();function X_(t){if(ff(t)&&(hf(t),pf(t))){rS(t);return}uf(t,()=>(0,df.topBoolOrEmptySchema)(t))}Ut.validateFunctionCode=X_;function uf({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},o){s.code.es5?t.func(e,(0,L._)`${F.default.data}, ${F.default.valCxt}`,n.$async,()=>{t.code((0,L._)`"use strict"; ${af(r,s)}`),tS(t,s),t.code(o)}):t.func(e,(0,L._)`${F.default.data}, ${eS(s)}`,n.$async,()=>t.code(af(r,s)).code(o))}function eS(t){return(0,L._)`{${F.default.instancePath}="", ${F.default.parentData}, ${F.default.parentDataProperty}, ${F.default.rootData}=${F.default.data}${t.dynamicRef?(0,L._)`, ${F.default.dynamicAnchors}={}`:L.nil}}={}`}function tS(t,e){t.if(F.default.valCxt,()=>{t.var(F.default.instancePath,(0,L._)`${F.default.valCxt}.${F.default.instancePath}`),t.var(F.default.parentData,(0,L._)`${F.default.valCxt}.${F.default.parentData}`),t.var(F.default.parentDataProperty,(0,L._)`${F.default.valCxt}.${F.default.parentDataProperty}`),t.var(F.default.rootData,(0,L._)`${F.default.valCxt}.${F.default.rootData}`),e.dynamicRef&&t.var(F.default.dynamicAnchors,(0,L._)`${F.default.valCxt}.${F.default.dynamicAnchors}`)},()=>{t.var(F.default.instancePath,(0,L._)`""`),t.var(F.default.parentData,(0,L._)`undefined`),t.var(F.default.parentDataProperty,(0,L._)`undefined`),t.var(F.default.rootData,F.default.data),e.dynamicRef&&t.var(F.default.dynamicAnchors,(0,L._)`{}`)})}function rS(t){let{schema:e,opts:r,gen:n}=t;uf(t,()=>{r.$comment&&e.$comment&&gf(t),aS(t),n.let(F.default.vErrors,null),n.let(F.default.errors,0),r.unevaluated&&nS(t),mf(t),dS(t)})}function nS(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,L._)`${r}.evaluated`),e.if((0,L._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,L._)`${t.evaluated}.props`,(0,L._)`undefined`)),e.if((0,L._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,L._)`${t.evaluated}.items`,(0,L._)`undefined`))}function af(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,L._)`/*# sourceURL=${r} */`:L.nil}function sS(t,e){if(ff(t)&&(hf(t),pf(t))){oS(t,e);return}(0,df.boolOrEmptySchema)(t,e)}function pf({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 ff(t){return typeof t.schema!="boolean"}function oS(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&gf(t),cS(t),lS(t);let o=n.const("_errs",F.default.errors);mf(t,o),n.var(e,(0,L._)`${o} === ${F.default.errors}`)}function hf(t){(0,$t.checkUnknownRules)(t),iS(t)}function mf(t,e){if(t.opts.jtd)return cf(t,[],!1,e);let r=(0,of.getSchemaTypes)(t.schema),n=(0,of.coerceAndCheckDataType)(t,r);cf(t,r,!n,e)}function iS(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,$t.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function aS(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,$t.checkStrictMode)(t,"default is ignored in the schema root")}function cS(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,Q_.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function lS(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function gf({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){let o=r.$comment;if(s.$comment===!0)t.code((0,L._)`${F.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,L.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,L._)`${F.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function dS(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:o}=t;r.$async?e.if((0,L._)`${F.default.errors} === 0`,()=>e.return(F.default.data),()=>e.throw((0,L._)`new ${s}(${F.default.vErrors})`)):(e.assign((0,L._)`${n}.errors`,F.default.vErrors),o.unevaluated&&uS(t),e.return((0,L._)`${F.default.errors} === 0`))}function uS({gen:t,evaluated:e,props:r,items:n}){r instanceof L.Name&&t.assign((0,L._)`${e}.props`,r),n instanceof L.Name&&t.assign((0,L._)`${e}.items`,n)}function cf(t,e,r,n){let{gen:s,schema:o,data:i,allErrors:a,opts:l,self:u}=t,{RULES:p}=u;if(o.$ref&&(l.ignoreKeywordsWithRef||!(0,$t.schemaHasRulesButRef)(o,p))){s.block(()=>bf(t,"$ref",p.all.$ref.definition));return}l.jtd||pS(t,e),s.block(()=>{for(let h of p.rules)d(h);d(p.post)});function d(h){(0,lc.shouldUseGroup)(o,h)&&(h.type?(s.if((0,co.checkDataType)(h.type,i,l.strictNumbers)),lf(t,h),e.length===1&&e[0]===h.type&&r&&(s.else(),(0,co.reportTypeError)(t)),s.endIf()):lf(t,h),a||s.if((0,L._)`${F.default.errors} === ${n||0}`))}}function lf(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,Y_.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,lc.shouldUseRule)(n,o)&&bf(t,o.keyword,o.definition,e.type)})}function pS(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(fS(t,e),t.opts.allowUnionTypes||hS(t,e),mS(t,t.dataTypes))}function fS(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{yf(t.dataTypes,r)||dc(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),yS(t,e)}}function hS(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&dc(t,"use allowUnionTypes to allow union type keyword")}function mS(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,lc.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>gS(e,i))&&dc(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function gS(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function yf(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function yS(t,e){let r=[];for(let n of t.dataTypes)yf(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function dc(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,$t.checkStrictMode)(t,e,t.opts.strictTypes)}var lo=class{constructor(e,r,n){if((0,Nn.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,$t.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",wf(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Nn.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",F.default.errors))}result(e,r,n){this.failResult((0,L.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,L.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,L._)`${r} !== undefined && (${(0,L.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?On.reportExtraError:On.reportError)(this,this.def.error,r)}$dataError(){(0,On.reportError)(this,this.def.$dataError||On.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,On.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=L.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=L.nil,r=L.nil){if(!this.$data)return;let{gen:n,schemaCode:s,schemaType:o,def:i}=this;n.if((0,L.or)((0,L._)`${s} === undefined`,r)),e!==L.nil&&n.assign(e,!0),(o.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==L.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:s,it:o}=this;return(0,L.or)(i(),a());function i(){if(n.length){if(!(r instanceof L.Name))throw new Error("ajv implementation error");let l=Array.isArray(n)?n:[n];return(0,L._)`${(0,co.checkDataTypes)(l,r,o.opts.strictNumbers,co.DataType.Wrong)}`}return L.nil}function a(){if(s.validateSchema){let l=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,L._)`!${l}(${r})`}return L.nil}}subschema(e,r){let n=(0,cc.getSubschema)(this.it,e);(0,cc.extendSubschemaData)(n,this.it,e),(0,cc.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return sS(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=$t.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=$t.mergeEvaluated.items(s,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:s}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return s.if(r,()=>this.mergeEvaluated(e,L.Name)),!0}};Ut.KeywordCxt=lo;function bf(t,e,r,n){let s=new lo(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,Nn.funcKeywordCode)(s,r):"macro"in r?(0,Nn.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,Nn.funcKeywordCode)(s,r)}var bS=/^\/(?:[^~]|~0|~1)*$/,wS=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function wf(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,o;if(t==="")return F.default.rootData;if(t[0]==="/"){if(!bS.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=F.default.rootData}else{let u=wS.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let p=+u[1];if(s=u[2],s==="#"){if(p>=e)throw new Error(l("property/index",p));return n[e-p]}if(p>e)throw new Error(l("data",p));if(o=r[e-p],!s)return o}let i=o,a=s.split("/");for(let u of a)u&&(o=(0,L._)`${o}${(0,L.getProperty)((0,$t.unescapeJsonPointer)(u))}`,i=(0,L._)`${i} && ${o}`);return i;function l(u,p){return`Cannot access ${u} ${p} levels up, current level is ${e}`}}Ut.getData=wf});var uo=j(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});var uc=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};pc.default=uc});var zn=j(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});var fc=Cn(),hc=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,fc.resolveUrl)(e,r,n),this.missingSchema=(0,fc.normalizeId)((0,fc.getFullPath)(e,this.missingRef))}};mc.default=hc});var fo=j(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.resolveSchema=rt.getCompilingSchema=rt.resolveRef=rt.compileSchema=rt.SchemaEnv=void 0;var ct=V(),vS=uo(),ir=St(),lt=Cn(),vf=re(),_S=jn(),Or=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,lt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};rt.SchemaEnv=Or;function yc(t){let e=_f.call(this,t);if(e)return e;let r=(0,lt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new ct.CodeGen(this.scope,{es5:n,lines:s,ownProperties:o}),a;t.$async&&(a=i.scopeValue("Error",{ref:vS.default,code:(0,ct._)`require("ajv/dist/runtime/validation_error").default`}));let l=i.scopeName("validate");t.validateName=l;let u={gen:i,allErrors:this.opts.allErrors,data:ir.default.data,parentData:ir.default.parentData,parentDataProperty:ir.default.parentDataProperty,dataNames:[ir.default.data],dataPathArr:[ct.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,ct.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:ct.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,ct._)`""`,opts:this.opts,self:this},p;try{this._compilations.add(t),(0,_S.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();p=`${i.scopeRefs(ir.default.scope)}return ${d}`,this.opts.code.process&&(p=this.opts.code.process(p,t));let g=new Function(`${ir.default.self}`,`${ir.default.scope}`,p)(this,this.scope.get());if(this.scope.value(l,{ref:g}),g.errors=null,g.schema=t.schema,g.schemaEnv=t,t.$async&&(g.$async=!0),this.opts.code.source===!0&&(g.source={validateName:l,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:v,items:_}=u;g.evaluated={props:v instanceof ct.Name?void 0:v,items:_ instanceof ct.Name?void 0:_,dynamicProps:v instanceof ct.Name,dynamicItems:_ instanceof ct.Name},g.source&&(g.source.evaluated=(0,ct.stringify)(g.evaluated))}return t.validate=g,t}catch(d){throw delete t.validate,delete t.validateName,p&&this.logger.error("Error compiling schema, function code:",p),d}finally{this._compilations.delete(t)}}rt.compileSchema=yc;function SS(t,e,r){var n;r=(0,lt.resolveUrl)(this.opts.uriResolver,e,r);let s=t.refs[r];if(s)return s;let o=xS.call(this,t,r);if(o===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(o=new Or({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=$S.call(this,o)}rt.resolveRef=SS;function $S(t){return(0,lt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:yc.call(this,t)}function _f(t){for(let e of this._compilations)if(kS(e,t))return e}rt.getCompilingSchema=_f;function kS(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function xS(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||po.call(this,t,e)}function po(t,e){let r=this.opts.uriResolver.parse(e),n=(0,lt._getFullPath)(this.opts.uriResolver,r),s=(0,lt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return gc.call(this,r,t);let o=(0,lt.normalizeId)(n),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=po.call(this,t,i);return typeof a?.schema!="object"?void 0:gc.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||yc.call(this,i),o===(0,lt.normalizeId)(e)){let{schema:a}=i,{schemaId:l}=this.opts,u=a[l];return u&&(s=(0,lt.resolveUrl)(this.opts.uriResolver,s,u)),new Or({schema:a,schemaId:l,root:t,baseId:s})}return gc.call(this,r,i)}}rt.resolveSchema=po;var TS=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function gc(t,{baseId:e,schema:r,root:n}){var s;if(((s=t.fragment)===null||s===void 0?void 0:s[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let l=r[(0,vf.unescapeFragment)(a)];if(l===void 0)return;r=l;let u=typeof r=="object"&&r[this.opts.schemaId];!TS.has(a)&&u&&(e=(0,lt.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,vf.schemaHasRulesButRef)(r,this.RULES)){let a=(0,lt.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=po.call(this,n,a)}let{schemaId:i}=this.opts;if(o=o||new Or({schema:r,schemaId:i,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var Sf=j((HI,RS)=>{RS.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 vc=j((KI,Ef)=>{"use strict";var ES=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),kf=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),bc=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),xf=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),PS=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function wc(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 AS=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function $f(t){return t.length=0,!0}function IS(t,e,r){if(t.length){let n=wc(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function CS(t){let e=0,r={error:!1,address:"",zone:""},n=[],s=[],o=!1,i=!1,a=IS;for(let l=0;l<t.length;l++){let u=t[l];if(!(u==="["||u==="]"))if(u===":"){if(o===!0&&(i=!0),!a(s,n,r))break;if(++e>7){r.error=!0;break}l>0&&t[l-1]===":"&&(o=!0),n.push(":");continue}else if(u==="%"){if(!a(s,n,r))break;a=$f}else{s.push(u);continue}}return s.length&&(a===$f?r.zone=s.join(""):i?n.push(s.join("")):n.push(wc(s))),r.address=n.join(""),r}function Tf(t){if(OS(t,":")<2)return{host:t,isIPV6:!1};let e=CS(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 OS(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function NS(t){let e=t,r=[],n=-1,s=0;for(;s=e.length;){if(s===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(s===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(s===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 jS={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},zS=/[@/?#:]/g,LS=/[@/?#]/g;function Rf(t,e){let r=e?LS:zS;return r.lastIndex=0,t.replace(r,n=>jS[n])}function DS(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 s=t.slice(n+1,n+3);if(bc(s)){let o=s.toUpperCase(),i=String.fromCharCode(parseInt(o,16));e&&xf(i)?r+=i:r+="%"+o,n+=2;continue}}r+=t[n]}return r}function MS(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(bc(n)){let s=n.toUpperCase(),o=String.fromCharCode(parseInt(s,16));o!=="."&&xf(o)?e+=o:e+="%"+s,r+=2;continue}}PS(t[r])?e+=t[r]:e+=escape(t[r])}return e}function qS(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(bc(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function US(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!kf(r)){let n=Tf(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Rf(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}Ef.exports={nonSimpleDomain:AS,recomposeAuthority:US,reescapeHostDelimiters:Rf,normalizePercentEncoding:DS,normalizePathEncoding:MS,escapePreservingEscapes:qS,removeDotSegments:NS,isIPv4:kf,isUUID:ES,normalizeIPv6:Tf,stringArrayToHexStripped:wc}});var Of=j((VI,Cf)=>{"use strict";var{isUUID:BS}=vc(),FS=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,HS=["http","https","ws","wss","urn","urn:uuid"];function KS(t){return HS.indexOf(t)!==-1}function _c(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 Pf(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Af(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 VS(t){return t.secure=_c(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function GS(t){if((t.port===(_c(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 WS(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(FS);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let s=`${n}:${e.nid||t.nid}`,o=Sc(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function JS(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(),s=`${r}:${e.nid||n}`,o=Sc(s);o&&(t=o.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function ZS(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!BS(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function YS(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var If={scheme:"http",domainHost:!0,parse:Pf,serialize:Af},QS={scheme:"https",domainHost:If.domainHost,parse:Pf,serialize:Af},ho={scheme:"ws",domainHost:!0,parse:VS,serialize:GS},XS={scheme:"wss",domainHost:ho.domainHost,parse:ho.parse,serialize:ho.serialize},e$={scheme:"urn",parse:WS,serialize:JS,skipNormalize:!0},t$={scheme:"urn:uuid",parse:ZS,serialize:YS,skipNormalize:!0},mo={http:If,https:QS,ws:ho,wss:XS,urn:e$,"urn:uuid":t$};Object.setPrototypeOf(mo,null);function Sc(t){return t&&(mo[t]||mo[t.toLowerCase()])||void 0}Cf.exports={wsIsSecure:_c,SCHEMES:mo,isValidSchemeName:KS,getSchemeHandler:Sc}});var Mf=j((GI,go)=>{"use strict";var{normalizeIPv6:r$,removeDotSegments:Ln,recomposeAuthority:n$,normalizePercentEncoding:s$,normalizePathEncoding:o$,escapePreservingEscapes:i$,reescapeHostDelimiters:a$,isIPv4:c$,nonSimpleDomain:l$}=vc(),{SCHEMES:d$,getSchemeHandler:jf}=Of();function u$(t,e){return typeof t=="string"?t=y$(t,e):typeof t=="object"&&(t=Nr(ar(t,e),e)),t}function p$(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},s=zf(Nr(t,n),Nr(e,n),n,!0);return n.skipEscape=!0,ar(s,n)}function zf(t,e,r,n){let s={};return n||(t=Nr(ar(t,r),r),e=Nr(ar(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(s.scheme=e.scheme,s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=Ln(e.path||""),s.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=Ln(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=Ln(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?s.path="/"+e.path:t.path?s.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:s.path=e.path,s.path=Ln(s.path)),s.query=e.query):(s.path=t.path,e.query!==void 0?s.query=e.query:s.query=t.query),s.userinfo=t.userinfo,s.host=t.host,s.port=t.port),s.scheme=t.scheme),s.fragment=e.fragment,s}function f$(t,e,r){let n=Nf(t,r),s=Nf(e,r);return n!==void 0&&s!==void 0&&n.toLowerCase()===s.toLowerCase()}function ar(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),s=[],o=jf(n.scheme||r.scheme);o&&o.serialize&&o.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=s$(r.path):(r.path=i$(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&s.push(r.scheme,":");let i=n$(r);if(i!==void 0&&(n.reference!=="suffix"&&s.push("//"),s.push(i),r.path&&r.path[0]!=="/"&&s.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!o||!o.absolutePath)&&(a=Ln(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),s.push(a)}return r.query!==void 0&&s.push("?",r.query),r.fragment!==void 0&&s.push("#",r.fragment),s.join("")}var h$=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,m$=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/;function g$(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 Lf(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},s=!1,o=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let i=t.match(m$);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",s=!0);let a=t.match(h$);if(a){n.scheme=a[1],n.userinfo=a[3],n.host=a[4],n.port=parseInt(a[5],10),n.path=a[6]||"",n.query=a[7],n.fragment=a[8],isNaN(n.port)&&(n.port=a[5]);let l=g$(n,a);if(l!==void 0&&(n.error=n.error||l,s=!0),n.host)if(c$(n.host)===!1){let d=r$(n.host);n.host=d.host.toLowerCase(),o=d.isIPV6}else o=!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=jf(r.scheme||n.scheme);if(!r.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(r.domainHost||u&&u.domainHost)&&o===!1&&l$(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=a$(unescape(n.host),o))),n.path&&(n.path=o$(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:s}}function Nr(t,e){return Lf(t,e).parsed}function y$(t,e){return Df(t,e).normalized}function Df(t,e){let{parsed:r,malformedAuthorityOrPort:n}=Lf(t,e);return{normalized:n?t:ar(r,e),malformedAuthorityOrPort:n}}function Nf(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Df(t,e);return n?void 0:r}if(typeof t=="object")return ar(t,e)}var $c={SCHEMES:d$,normalize:u$,resolve:p$,resolveComponent:zf,equal:f$,serialize:ar,parse:Nr};go.exports=$c;go.exports.default=$c;go.exports.fastUri=$c});var Uf=j(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var qf=Mf();qf.code='require("ajv/dist/runtime/uri").default';kc.default=qf});var Jf=j(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.CodeGen=Te.Name=Te.nil=Te.stringify=Te.str=Te._=Te.KeywordCxt=void 0;var b$=jn();Object.defineProperty(Te,"KeywordCxt",{enumerable:!0,get:function(){return b$.KeywordCxt}});var jr=V();Object.defineProperty(Te,"_",{enumerable:!0,get:function(){return jr._}});Object.defineProperty(Te,"str",{enumerable:!0,get:function(){return jr.str}});Object.defineProperty(Te,"stringify",{enumerable:!0,get:function(){return jr.stringify}});Object.defineProperty(Te,"nil",{enumerable:!0,get:function(){return jr.nil}});Object.defineProperty(Te,"Name",{enumerable:!0,get:function(){return jr.Name}});Object.defineProperty(Te,"CodeGen",{enumerable:!0,get:function(){return jr.CodeGen}});var w$=uo(),Vf=zn(),v$=Qa(),Dn=fo(),_$=V(),Mn=Cn(),yo=In(),Tc=re(),Bf=Sf(),S$=Uf(),Gf=(t,e)=>new RegExp(t,e);Gf.code="new RegExp";var $$=["removeAdditional","useDefaults","coerceTypes"],k$=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),x$={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."},T$={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Ff=200;function R$(t){var e,r,n,s,o,i,a,l,u,p,d,h,g,v,_,T,P,N,D,Q,B,Le,Ee,ur,Kr;let kt=t.strict,Vr=(e=t.code)===null||e===void 0?void 0:e.optimize,Vt=Vr===!0||Vr===void 0?1:Vr||0,Gt=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Gf,f=(s=t.uriResolver)!==null&&s!==void 0?s:S$.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:kt)!==null&&i!==void 0?i:!0,strictNumbers:(l=(a=t.strictNumbers)!==null&&a!==void 0?a:kt)!==null&&l!==void 0?l:!0,strictTypes:(p=(u=t.strictTypes)!==null&&u!==void 0?u:kt)!==null&&p!==void 0?p:"log",strictTuples:(h=(d=t.strictTuples)!==null&&d!==void 0?d:kt)!==null&&h!==void 0?h:"log",strictRequired:(v=(g=t.strictRequired)!==null&&g!==void 0?g:kt)!==null&&v!==void 0?v:!1,code:t.code?{...t.code,optimize:Vt,regExp:Gt}:{optimize:Vt,regExp:Gt},loopRequired:(_=t.loopRequired)!==null&&_!==void 0?_:Ff,loopEnum:(T=t.loopEnum)!==null&&T!==void 0?T:Ff,meta:(P=t.meta)!==null&&P!==void 0?P:!0,messages:(N=t.messages)!==null&&N!==void 0?N:!0,inlineRefs:(D=t.inlineRefs)!==null&&D!==void 0?D:!0,schemaId:(Q=t.schemaId)!==null&&Q!==void 0?Q:"$id",addUsedSchema:(B=t.addUsedSchema)!==null&&B!==void 0?B:!0,validateSchema:(Le=t.validateSchema)!==null&&Le!==void 0?Le:!0,validateFormats:(Ee=t.validateFormats)!==null&&Ee!==void 0?Ee:!0,unicodeRegExp:(ur=t.unicodeRegExp)!==null&&ur!==void 0?ur:!0,int32range:(Kr=t.int32range)!==null&&Kr!==void 0?Kr:!0,uriResolver:f}}var qn=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,...R$(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new _$.ValueScope({scope:{},prefixes:k$,es5:r,lines:n}),this.logger=O$(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,v$.getRules)(),Hf.call(this,x$,e,"NOT SUPPORTED"),Hf.call(this,T$,e,"DEPRECATED","warn"),this._metaOpts=I$.call(this),e.formats&&P$.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&A$.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),E$.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=Bf;n==="id"&&(s={...Bf},s.id=s.$id,delete s.$id),r&&e&&this.addMetaSchema(s,s[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 s=n(r);return"$async"in n||(this.errors=n.errors),s}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 s.call(this,e,r);async function s(p,d){await o.call(this,p.$schema);let h=this._addSchema(p,d);return h.validate||i.call(this,h)}async function o(p){p&&!this.getSchema(p)&&await s.call(this,{$ref:p},!0)}async function i(p){try{return this._compileSchemaEnv(p)}catch(d){if(!(d instanceof Vf.default))throw d;return a.call(this,d),await l.call(this,d.missingSchema),i.call(this,p)}}function a({missingSchema:p,missingRef:d}){if(this.refs[p])throw new Error(`AnySchema ${p} is loaded but ${d} cannot be resolved`)}async function l(p){let d=await u.call(this,p);this.refs[p]||await o.call(this,d.$schema),this.refs[p]||this.addSchema(d,p,r)}async function u(p){let d=this._loading[p];if(d)return d;try{return await(this._loading[p]=n(p))}finally{delete this._loading[p]}}}addSchema(e,r,n,s=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,s);return this}let o;if(typeof e=="object"){let{schemaId:i}=this.opts;if(o=e[i],o!==void 0&&typeof o!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Mn.normalizeId)(r||o),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,s,!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 s=this.validate(n,e);if(!s&&r){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return s}getSchema(e){let r;for(;typeof(r=Kf.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new Dn.SchemaEnv({schema:{},schemaId:n});if(r=Dn.resolveSchema.call(this,s,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=Kf.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,Mn.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(j$.call(this,n,r),!r)return(0,Tc.eachItem)(n,o=>xc.call(this,o)),this;L$.call(this,r);let s={...r,type:(0,yo.getJSONTypes)(r.type),schemaType:(0,yo.getJSONTypes)(r.schemaType)};return(0,Tc.eachItem)(n,s.type.length===0?o=>xc.call(this,o,s):o=>s.type.forEach(i=>xc.call(this,o,s,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 s=n.rules.findIndex(o=>o.keyword===e);s>=0&&n.rules.splice(s,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(s=>`${n}${s.instancePath} ${s.message}`).reduce((s,o)=>s+r+o)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let s of r){let o=s.split("/").slice(1),i=e;for(let a of o)i=i[a];for(let a in n){let l=n[a];if(typeof l!="object")continue;let{$data:u}=l.definition,p=i[a];u&&p&&(i[a]=Wf(p))}}return e}_removeAllSchemas(e,r){for(let n in e){let s=e[n];(!r||r.test(n))&&(typeof s=="string"?delete e[n]:s&&!s.meta&&(this._cache.delete(s.schema),delete e[n]))}}_addSchema(e,r,n,s=this.opts.validateSchema,o=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 l=this._cache.get(e);if(l!==void 0)return l;n=(0,Mn.normalizeId)(i||n);let u=Mn.getSchemaRefs.call(this,e,n);return l=new Dn.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(l.schema,l),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=l),s&&this.validateSchema(e,!0),l}_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):Dn.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{Dn.compileSchema.call(this,e)}finally{this.opts=r}}};qn.ValidationError=w$.default;qn.MissingRefError=Vf.default;Te.default=qn;function Hf(t,e,r,n="error"){for(let s in t){let o=s;o in e&&this.logger[n](`${r}: option ${s}. ${t[o]}`)}}function Kf(t){return t=(0,Mn.normalizeId)(t),this.schemas[t]||this.refs[t]}function E$(){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 P$(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function A$(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 I$(){let t={...this.opts};for(let e of $$)delete t[e];return t}var C$={log(){},warn(){},error(){}};function O$(t){if(t===!1)return C$;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var N$=/^[a-z_$][a-z0-9_$:-]*$/i;function j$(t,e){let{RULES:r}=this;if((0,Tc.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!N$.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function xc(t,e,r){var n;let s=e?.post;if(r&&s)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,i=s?o.post:o.rules.find(({type:l})=>l===r);if(i||(i={type:r,rules:[]},o.rules.push(i)),o.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,yo.getJSONTypes)(e.type),schemaType:(0,yo.getJSONTypes)(e.schemaType)}};e.before?z$.call(this,i,a,e.before):i.rules.push(a),o.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(l=>this.addKeyword(l))}function z$(t,e,r){let n=t.rules.findIndex(s=>s.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function L$(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Wf(e)),t.validateSchema=this.compile(e,!0))}var D$={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Wf(t){return{anyOf:[t,D$]}}});var Zf=j(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});var M$={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Rc.default=M$});var eh=j(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.callRef=cr.getValidate=void 0;var q$=zn(),Yf=tt(),Fe=V(),zr=St(),Qf=fo(),bo=re(),U$={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:s,schemaEnv:o,validateName:i,opts:a,self:l}=n,{root:u}=o;if((r==="#"||r==="#/")&&s===u.baseId)return d();let p=Qf.resolveRef.call(l,u,s,r);if(p===void 0)throw new q$.default(n.opts.uriResolver,s,r);if(p instanceof Qf.SchemaEnv)return h(p);return g(p);function d(){if(o===u)return wo(t,i,o,o.$async);let v=e.scopeValue("root",{ref:u});return wo(t,(0,Fe._)`${v}.validate`,u,u.$async)}function h(v){let _=Xf(t,v);wo(t,_,v,v.$async)}function g(v){let _=e.scopeValue("schema",a.code.source===!0?{ref:v,code:(0,Fe.stringify)(v)}:{ref:v}),T=e.name("valid"),P=t.subschema({schema:v,dataTypes:[],schemaPath:Fe.nil,topSchemaRef:_,errSchemaPath:r},T);t.mergeEvaluated(P),t.ok(T)}}};function Xf(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Fe._)`${r.scopeValue("wrapper",{ref:e})}.validate`}cr.getValidate=Xf;function wo(t,e,r,n){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:l}=o,u=l.passContext?zr.default.this:Fe.nil;n?p():d();function p(){if(!a.$async)throw new Error("async schema referenced by sync schema");let v=s.let("valid");s.try(()=>{s.code((0,Fe._)`await ${(0,Yf.callValidateCode)(t,e,u)}`),g(e),i||s.assign(v,!0)},_=>{s.if((0,Fe._)`!(${_} instanceof ${o.ValidationError})`,()=>s.throw(_)),h(_),i||s.assign(v,!1)}),t.ok(v)}function d(){t.result((0,Yf.callValidateCode)(t,e,u),()=>g(e),()=>h(e))}function h(v){let _=(0,Fe._)`${v}.errors`;s.assign(zr.default.vErrors,(0,Fe._)`${zr.default.vErrors} === null ? ${_} : ${zr.default.vErrors}.concat(${_})`),s.assign(zr.default.errors,(0,Fe._)`${zr.default.vErrors}.length`)}function g(v){var _;if(!o.opts.unevaluated)return;let T=(_=r?.validate)===null||_===void 0?void 0:_.evaluated;if(o.props!==!0)if(T&&!T.dynamicProps)T.props!==void 0&&(o.props=bo.mergeEvaluated.props(s,T.props,o.props));else{let P=s.var("props",(0,Fe._)`${v}.evaluated.props`);o.props=bo.mergeEvaluated.props(s,P,o.props,Fe.Name)}if(o.items!==!0)if(T&&!T.dynamicItems)T.items!==void 0&&(o.items=bo.mergeEvaluated.items(s,T.items,o.items));else{let P=s.var("items",(0,Fe._)`${v}.evaluated.items`);o.items=bo.mergeEvaluated.items(s,P,o.items,Fe.Name)}}}cr.callRef=wo;cr.default=U$});var th=j(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var B$=Zf(),F$=eh(),H$=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",B$.default,F$.default];Ec.default=H$});var rh=j(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});var vo=V(),Bt=vo.operators,_o={maximum:{okStr:"<=",ok:Bt.LTE,fail:Bt.GT},minimum:{okStr:">=",ok:Bt.GTE,fail:Bt.LT},exclusiveMaximum:{okStr:"<",ok:Bt.LT,fail:Bt.GTE},exclusiveMinimum:{okStr:">",ok:Bt.GT,fail:Bt.LTE}},K$={message:({keyword:t,schemaCode:e})=>(0,vo.str)`must be ${_o[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,vo._)`{comparison: ${_o[t].okStr}, limit: ${e}}`},V$={keyword:Object.keys(_o),type:"number",schemaType:"number",$data:!0,error:K$,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,vo._)`${r} ${_o[e].fail} ${n} || isNaN(${r})`)}};Pc.default=V$});var nh=j(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});var Un=V(),G$={message:({schemaCode:t})=>(0,Un.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Un._)`{multipleOf: ${t}}`},W$={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:G$,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,Un._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,Un._)`${i} !== parseInt(${i})`;t.fail$data((0,Un._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Ac.default=W$});var oh=j(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});function sh(t){let e=t.length,r=0,n=0,s;for(;n<e;)r++,s=t.charCodeAt(n++),s>=55296&&s<=56319&&n<e&&(s=t.charCodeAt(n),(s&64512)===56320&&n++);return r}Ic.default=sh;sh.code='require("ajv/dist/runtime/ucs2length").default'});var ih=j(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});var lr=V(),J$=re(),Z$=oh(),Y$={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,lr.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,lr._)`{limit: ${t}}`},Q$={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Y$,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,o=e==="maxLength"?lr.operators.GT:lr.operators.LT,i=s.opts.unicode===!1?(0,lr._)`${r}.length`:(0,lr._)`${(0,J$.useFunc)(t.gen,Z$.default)}(${r})`;t.fail$data((0,lr._)`${i} ${o} ${n}`)}};Cc.default=Q$});var ah=j(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});var X$=tt(),ek=re(),Lr=V(),tk={message:({schemaCode:t})=>(0,Lr.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Lr._)`{pattern: ${t}}`},rk={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:tk,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:l}=i.opts.code,u=l.code==="new RegExp"?(0,Lr._)`new RegExp`:(0,ek.useFunc)(e,l),p=e.let("valid");e.try(()=>e.assign(p,(0,Lr._)`${u}(${o}, ${a}).test(${r})`),()=>e.assign(p,!1)),t.fail$data((0,Lr._)`!${p}`)}else{let l=(0,X$.usePattern)(t,s);t.fail$data((0,Lr._)`!${l}.test(${r})`)}}};Oc.default=rk});var ch=j(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var Bn=V(),nk={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Bn.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Bn._)`{limit: ${t}}`},sk={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:nk,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?Bn.operators.GT:Bn.operators.LT;t.fail$data((0,Bn._)`Object.keys(${r}).length ${s} ${n}`)}};Nc.default=sk});var lh=j(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});var Fn=tt(),Hn=V(),ok=re(),ik={message:({params:{missingProperty:t}})=>(0,Hn.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Hn._)`{missingProperty: ${t}}`},ak={keyword:"required",type:"object",schemaType:"array",$data:!0,error:ik,code(t){let{gen:e,schema:r,schemaCode:n,data:s,$data:o,it:i}=t,{opts:a}=i;if(!o&&r.length===0)return;let l=r.length>=a.loopRequired;if(i.allErrors?u():p(),a.strictRequired){let g=t.parentSchema.properties,{definedProperties:v}=t.it;for(let _ of r)if(g?.[_]===void 0&&!v.has(_)){let T=i.schemaEnv.baseId+i.errSchemaPath,P=`required property "${_}" is not defined at "${T}" (strictRequired)`;(0,ok.checkStrictMode)(i,P,i.opts.strictRequired)}}function u(){if(l||o)t.block$data(Hn.nil,d);else for(let g of r)(0,Fn.checkReportMissingProp)(t,g)}function p(){let g=e.let("missing");if(l||o){let v=e.let("valid",!0);t.block$data(v,()=>h(g,v)),t.ok(v)}else e.if((0,Fn.checkMissingProp)(t,r,g)),(0,Fn.reportMissingProp)(t,g),e.else()}function d(){e.forOf("prop",n,g=>{t.setParams({missingProperty:g}),e.if((0,Fn.noPropertyInData)(e,s,g,a.ownProperties),()=>t.error())})}function h(g,v){t.setParams({missingProperty:g}),e.forOf(g,n,()=>{e.assign(v,(0,Fn.propertyInData)(e,s,g,a.ownProperties)),e.if((0,Hn.not)(v),()=>{t.error(),e.break()})},Hn.nil)}}};jc.default=ak});var dh=j(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var Kn=V(),ck={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Kn.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Kn._)`{limit: ${t}}`},lk={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:ck,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?Kn.operators.GT:Kn.operators.LT;t.fail$data((0,Kn._)`${r}.length ${s} ${n}`)}};zc.default=lk});var So=j(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});var uh=ic();uh.code='require("ajv/dist/runtime/equal").default';Lc.default=uh});var ph=j(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});var Dc=In(),Re=V(),dk=re(),uk=So(),pk={message:({params:{i:t,j:e}})=>(0,Re.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Re._)`{i: ${t}, j: ${e}}`},fk={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:pk,code(t){let{gen:e,data:r,$data:n,schema:s,parentSchema:o,schemaCode:i,it:a}=t;if(!n&&!s)return;let l=e.let("valid"),u=o.items?(0,Dc.getSchemaTypes)(o.items):[];t.block$data(l,p,(0,Re._)`${i} === false`),t.ok(l);function p(){let v=e.let("i",(0,Re._)`${r}.length`),_=e.let("j");t.setParams({i:v,j:_}),e.assign(l,!0),e.if((0,Re._)`${v} > 1`,()=>(d()?h:g)(v,_))}function d(){return u.length>0&&!u.some(v=>v==="object"||v==="array")}function h(v,_){let T=e.name("item"),P=(0,Dc.checkDataTypes)(u,T,a.opts.strictNumbers,Dc.DataType.Wrong),N=e.const("indices",(0,Re._)`{}`);e.for((0,Re._)`;${v}--;`,()=>{e.let(T,(0,Re._)`${r}[${v}]`),e.if(P,(0,Re._)`continue`),u.length>1&&e.if((0,Re._)`typeof ${T} == "string"`,(0,Re._)`${T} += "_"`),e.if((0,Re._)`typeof ${N}[${T}] == "number"`,()=>{e.assign(_,(0,Re._)`${N}[${T}]`),t.error(),e.assign(l,!1).break()}).code((0,Re._)`${N}[${T}] = ${v}`)})}function g(v,_){let T=(0,dk.useFunc)(e,uk.default),P=e.name("outer");e.label(P).for((0,Re._)`;${v}--;`,()=>e.for((0,Re._)`${_} = ${v}; ${_}--;`,()=>e.if((0,Re._)`${T}(${r}[${v}], ${r}[${_}])`,()=>{t.error(),e.assign(l,!1).break(P)})))}}};Mc.default=fk});var fh=j(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});var qc=V(),hk=re(),mk=So(),gk={message:"must be equal to constant",params:({schemaCode:t})=>(0,qc._)`{allowedValue: ${t}}`},yk={keyword:"const",$data:!0,error:gk,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,qc._)`!${(0,hk.useFunc)(e,mk.default)}(${r}, ${s})`):t.fail((0,qc._)`${o} !== ${r}`)}};Uc.default=yk});var hh=j(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var Vn=V(),bk=re(),wk=So(),vk={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Vn._)`{allowedValues: ${t}}`},_k={keyword:"enum",schemaType:"array",$data:!0,error:vk,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t;if(!n&&s.length===0)throw new Error("enum must have non-empty array");let a=s.length>=i.opts.loopEnum,l,u=()=>l??(l=(0,bk.useFunc)(e,wk.default)),p;if(a||n)p=e.let("valid"),t.block$data(p,d);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let g=e.const("vSchema",o);p=(0,Vn.or)(...s.map((v,_)=>h(g,_)))}t.pass(p);function d(){e.assign(p,!1),e.forOf("v",o,g=>e.if((0,Vn._)`${u()}(${r}, ${g})`,()=>e.assign(p,!0).break()))}function h(g,v){let _=s[v];return typeof _=="object"&&_!==null?(0,Vn._)`${u()}(${r}, ${g}[${v}])`:(0,Vn._)`${r} === ${_}`}}};Bc.default=_k});var mh=j(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});var Sk=rh(),$k=nh(),kk=ih(),xk=ah(),Tk=ch(),Rk=lh(),Ek=dh(),Pk=ph(),Ak=fh(),Ik=hh(),Ck=[Sk.default,$k.default,kk.default,xk.default,Tk.default,Rk.default,Ek.default,Pk.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Ak.default,Ik.default];Fc.default=Ck});var Kc=j(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.validateAdditionalItems=void 0;var dr=V(),Hc=re(),Ok={message:({params:{len:t}})=>(0,dr.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,dr._)`{limit: ${t}}`},Nk={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Ok,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Hc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}gh(t,n)}};function gh(t,e){let{gen:r,schema:n,data:s,keyword:o,it:i}=t;i.items=!0;let a=r.const("len",(0,dr._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,dr._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Hc.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,dr._)`${a} <= ${e.length}`);r.if((0,dr.not)(u),()=>l(u)),t.ok(u)}function l(u){r.forRange("i",e.length,a,p=>{t.subschema({keyword:o,dataProp:p,dataPropType:Hc.Type.Num},u),i.allErrors||r.if((0,dr.not)(u),()=>r.break())})}}Gn.validateAdditionalItems=gh;Gn.default=Nk});var Vc=j(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.validateTuple=void 0;var yh=V(),$o=re(),jk=tt(),zk={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return bh(t,"additionalItems",e);r.items=!0,!(0,$o.alwaysValidSchema)(r,e)&&t.ok((0,jk.validateArray)(t))}};function bh(t,e,r=t.schema){let{gen:n,parentSchema:s,data:o,keyword:i,it:a}=t;p(s),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=$o.mergeEvaluated.items(n,r.length,a.items));let l=n.name("valid"),u=n.const("len",(0,yh._)`${o}.length`);r.forEach((d,h)=>{(0,$o.alwaysValidSchema)(a,d)||(n.if((0,yh._)`${u} > ${h}`,()=>t.subschema({keyword:i,schemaProp:h,dataProp:h},l)),t.ok(l))});function p(d){let{opts:h,errSchemaPath:g}=a,v=r.length,_=v===d.minItems&&(v===d.maxItems||d[e]===!1);if(h.strictTuples&&!_){let T=`"${i}" is ${v}-tuple, but minItems or maxItems/${e} are not specified or different at path "${g}"`;(0,$o.checkStrictMode)(a,T,h.strictTuples)}}}Wn.validateTuple=bh;Wn.default=zk});var wh=j(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var Lk=Vc(),Dk={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,Lk.validateTuple)(t,"items")};Gc.default=Dk});var _h=j(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var vh=V(),Mk=re(),qk=tt(),Uk=Kc(),Bk={message:({params:{len:t}})=>(0,vh.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,vh._)`{limit: ${t}}`},Fk={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Bk,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,Mk.alwaysValidSchema)(n,e)&&(s?(0,Uk.validateAdditionalItems)(t,s):t.ok((0,qk.validateArray)(t)))}};Wc.default=Fk});var Sh=j(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});var nt=V(),ko=re(),Hk={message:({params:{min:t,max:e}})=>e===void 0?(0,nt.str)`must contain at least ${t} valid item(s)`:(0,nt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,nt._)`{minContains: ${t}}`:(0,nt._)`{minContains: ${t}, maxContains: ${e}}`},Kk={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Hk,code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t,i,a,{minContains:l,maxContains:u}=n;o.opts.next?(i=l===void 0?1:l,a=u):i=1;let p=e.const("len",(0,nt._)`${s}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,ko.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,ko.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,ko.alwaysValidSchema)(o,r)){let _=(0,nt._)`${p} >= ${i}`;a!==void 0&&(_=(0,nt._)`${_} && ${p} <= ${a}`),t.pass(_);return}o.items=!0;let d=e.name("valid");a===void 0&&i===1?g(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,nt._)`${s}.length > 0`,h)):(e.let(d,!1),h()),t.result(d,()=>t.reset());function h(){let _=e.name("_valid"),T=e.let("count",0);g(_,()=>e.if(_,()=>v(T)))}function g(_,T){e.forRange("i",0,p,P=>{t.subschema({keyword:"contains",dataProp:P,dataPropType:ko.Type.Num,compositeRule:!0},_),T()})}function v(_){e.code((0,nt._)`${_}++`),a===void 0?e.if((0,nt._)`${_} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,nt._)`${_} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,nt._)`${_} >= ${i}`,()=>e.assign(d,!0)))}}};Jc.default=Kk});var xh=j(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.validateSchemaDeps=gt.validatePropertyDeps=gt.error=void 0;var Zc=V(),Vk=re(),Jn=tt();gt.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Zc.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Zc._)`{property: ${t},
|
|
883
|
+
]`;continue}s+=n[l],n[l]==="\\"?o=!0:i&&n[l]==="]"?i=!1:!i&&n[l]==="["&&(i=!0)}try{new RegExp(s)}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 s}var ua,it,_v,Js=N(()=>{qt();it={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:()=>(ua===void 0&&(ua=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ua),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-_]*$/};_v=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});import{ZodFirstPartyTypeKind as vn}from"zod/v3";function Zs(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===vn.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,s)=>({...n,[s]:B(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??be(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:B(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===vn.ZodString&&t.keyType._def.checks?.length){let{type:n,...s}=Ws(t.keyType._def,e);return{...r,propertyNames:s}}else{if(t.keyType?._def.typeName===vn.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===vn.ZodBranded&&t.keyType._def.type._def.typeName===vn.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...s}=Vs(t.keyType._def,e);return{...r,propertyNames:s}}}return r}var Ys=N(()=>{_e();Js();Gs();et()});function ap(t,e){if(e.mapStrategy==="record")return Zs(t,e);let r=B(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||be(e),n=B(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||be(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var fa=N(()=>{_e();Ys();et()});function cp(t){let e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}var ha=N(()=>{});function lp(t){return t.target==="openAi"?void 0:{not:be({...t,currentPath:[...t.currentPath,"not"]})}}var ma=N(()=>{et()});function dp(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ga=N(()=>{});function pp(t,e){if(e.target==="openApi3")return up(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Sn&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((s,o)=>{let i=Sn[o._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((s,o)=>{let i=typeof o._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];default:return s}},[]);if(n.length===r.length){let s=n.filter((o,i,a)=>a.indexOf(o)===i);return{type:s.length>1?s:s[0],enum:r.reduce((o,i)=>o.includes(i._def.value)?o:[...o,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return up(t,e)}var Sn,up,Qs=N(()=>{_e();Sn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};up=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>B(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function fp(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:Sn[t.innerType._def.typeName],nullable:!0}:{type:[Sn[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=B(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=B(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var ya=N(()=>{_e();Qs()});function hp(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",Xi(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?re(r,"minimum",n.value,n.message,e):re(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),re(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?re(r,"maximum",n.value,n.message,e):re(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),re(r,"maximum",n.value,n.message,e));break;case"multipleOf":re(r,"multipleOf",n.value,n.message,e);break}return r}var ba=N(()=>{qt()});function mp(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},s=[],o=t.shape();for(let a in o){let l=o[a];if(l===void 0||l._def===void 0)continue;let d=xv(l);d&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),d=!1);let u=B(l._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});u!==void 0&&(n.properties[a]=u,d||s.push(a))}s.length&&(n.required=s);let i=kv(t,e);return i!==void 0&&(n.additionalProperties=i),n}function kv(t,e){if(t.catchall._def.typeName!=="ZodNever")return B(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 xv(t){try{return t.isOptional()}catch{return!0}}var wa=N(()=>{_e()});var gp,va=N(()=>{_e();et();gp=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return B(t.innerType._def,e);let r=B(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:be(e)},r]}:be(e)}});var yp,Sa=N(()=>{_e();yp=(t,e)=>{if(e.pipeStrategy==="input")return B(t.in._def,e);if(e.pipeStrategy==="output")return B(t.out._def,e);let r=B(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=B(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}}});function bp(t,e){return B(t.type._def,e)}var _a=N(()=>{_e()});function wp(t,e){let n={type:"array",uniqueItems:!0,items:B(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&re(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&re(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var $a=N(()=>{qt();_e()});function vp(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>B(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:B(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>B(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var ka=N(()=>{_e()});function Sp(t){return{not:be(t)}}var xa=N(()=>{et()});function _p(t){return be(t)}var Ta=N(()=>{et()});var $p,Ra=N(()=>{_e();$p=(t,e)=>B(t.innerType._def,e)});import{ZodFirstPartyTypeKind as X}from"zod/v3";var kp,Ea=N(()=>{et();ea();ta();ra();Gs();na();oa();ia();aa();ca();la();da();fa();ha();ma();ga();ya();ba();wa();va();Sa();_a();Ys();$a();Js();ka();xa();Qs();Ta();Ra();kp=(t,e,r)=>{switch(e){case X.ZodString:return Ws(t,r);case X.ZodNumber:return hp(t,r);case X.ZodObject:return mp(t,r);case X.ZodBigInt:return Qu(t,r);case X.ZodBoolean:return Xu();case X.ZodDate:return sa(t,r);case X.ZodUndefined:return Sp(r);case X.ZodNull:return dp(r);case X.ZodArray:return Yu(t,r);case X.ZodUnion:case X.ZodDiscriminatedUnion:return pp(t,r);case X.ZodIntersection:return sp(t,r);case X.ZodTuple:return vp(t,r);case X.ZodRecord:return Zs(t,r);case X.ZodLiteral:return op(t,r);case X.ZodEnum:return np(t);case X.ZodNativeEnum:return cp(t);case X.ZodNullable:return fp(t,r);case X.ZodOptional:return gp(t,r);case X.ZodMap:return ap(t,r);case X.ZodSet:return wp(t,r);case X.ZodLazy:return()=>t.getter()._def;case X.ZodPromise:return bp(t,r);case X.ZodNaN:case X.ZodNever:return lp(r);case X.ZodEffects:return rp(t,r);case X.ZodAny:return be(r);case X.ZodUnknown:return _p(r);case X.ZodDefault:return tp(t,r);case X.ZodBranded:return Vs(t,r);case X.ZodReadonly:return $p(t,r);case X.ZodCatch:return ep(t,r);case X.ZodPipeline:return yp(t,r);case X.ZodFunction:case X.ZodVoid:case X.ZodSymbol:return;default:return(n=>{})(e)}}});function B(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==Wu)return a}if(n&&!r){let a=Tv(n,e);if(a!==void 0)return a}let s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);let o=kp(t,t.typeName,e),i=typeof o=="function"?B(o(),e):o;if(i&&Rv(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return s.jsonSchema=i,a}return s.jsonSchema=i,i}var Tv,Rv,_e=N(()=>{Fs();Ea();Ks();et();Tv=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Hs(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`),be(e)):e.$refStrategy==="seen"?be(e):void 0}},Rv=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var xp=N(()=>{});var Pa,Aa=N(()=>{_e();Qi();et();Pa=(t,e)=>{let r=Zu(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[d,u])=>({...l,[d]:B(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,d]},!0)??be(r)}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=B(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??be(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(o.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=s===void 0?n?{...o,[r.definitionPath]:n}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:o}};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 Tp=N(()=>{Fs();Qi();qt();Ks();_e();xp();et();ea();ta();ra();Gs();na();oa();ia();aa();ca();la();da();fa();ha();ma();ga();ya();ba();wa();va();Sa();_a();Ra();Ys();$a();Js();ka();xa();Qs();Ta();Ea();Aa();Aa()});import*as Rp from"zod/v4-mini";function Ev(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Ia(t,e){return mt(t)?Rp.toJSONSchema(t,{target:Ev(e?.target),io:e?.pipeStrategy??"input"}):Pa(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Ca(t){let r=Lt(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Sr(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Oa(t,e){let r=zt(t,e);if(!r.success)throw r.error;return r.data}var Na=N(()=>{ln();Tp()});function Ep(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Pp(t,e){let r={...t};for(let n in e){let s=n,o=e[s];if(o===void 0)continue;let i=r[s];Ep(i)&&Ep(o)?r[s]={...i,...o}:r[s]=o}return r}var Pv,Xs,Ap=N(()=>{ln();Rr();Vu();Na();Pv=6e4,Xs=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(Ts,r=>{this._oncancel(r)}),this.setNotificationHandler(Es,r=>{this._onprogress(r)}),this.setRequestHandler(Rs,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ps,async(r,n)=>{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new L(q.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(Is,async(r,n)=>{let s=async()=>{let o=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(a.type==="response"||a.type==="error"){let l=a.message,d=l.id,u=this._requestResolvers.get(d);if(u)if(this._requestResolvers.delete(d),a.type==="response")u(l);else{let h=l,v=new L(h.error.code,h.error.message,h.error.data);u(v)}else{let h=a.type==="response"?"Response":"Error";this._onerror(new Error(`${h} handler missing for request ${d}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(o,n.sessionId);if(!i)throw new L(q.InvalidParams,`Task not found: ${o}`);if(!Dt(i.status))return await this._waitForTaskUpdate(o,n.signal),await s();if(Dt(i.status)){let a=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[Ut]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(Cs,async(r,n)=>{try{let{tasks:s,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:s,nextCursor:o,_meta:{}}}catch(s){throw new L(q.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(Ns,async(r,n)=>{try{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new L(q.InvalidParams,`Task not found: ${r.params.taskId}`);if(Dt(s.status))throw new L(q.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new L(q.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof L?s:new L(q.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,s,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:s})}_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),L.fromError(q.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=o=>{n?.(o),this._onerror(o)};let s=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{s?.(o,i),un(o)||ju(o)?this._onresponse(o):Ui(o)?this._onrequest(o,i):Nu(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},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=L.fromError(q.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,s=this._transport,o=e.params?._meta?.[Ut]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:q.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:u,timestamp:Date.now()},s?.sessionId).catch(h=>this._onerror(new Error(`Failed to enqueue error response: ${h}`))):s?.send(u).catch(h=>this._onerror(new Error(`Failed to send an error response: ${h}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=Iu(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,d={signal:i.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{if(i.signal.aborted)return;let h={relatedRequestId:e.id};o&&(h.relatedTask={taskId:o}),await this.notification(u,h)},sendRequest:async(u,h,v)=>{if(i.signal.aborted)throw new L(q.ConnectionClosed,"Request was cancelled");let g={...v,relatedRequestId:e.id};o&&!g.relatedTask&&(g.relatedTask={taskId:o});let w=g.relatedTask?.taskId??o;return w&&l&&await l.updateTaskStatus(w,"input_required"),await this.request(u,h,g)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:o,taskStore:l,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,d)).then(async u=>{if(i.signal.aborted)return;let h={result:u,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:h,timestamp:Date.now()},s?.sessionId):await s?.send(h)},async u=>{if(i.signal.aborted)return;let h={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:q.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:h,timestamp:Date.now()},s?.sessionId):await s?.send(h)}).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,s=Number(r),o=this._progressHandlers.get(s);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(s),a=this._timeoutInfo.get(s);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(l){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),i(l);return}o(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),un(e))n(e);else{let i=new L(e.error.code,e.error.message,e.error.data);n(i)}return}let s=this._responseHandlers.get(r);if(s===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 o=!1;if(un(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"&&(o=!0,this._taskProgressTokens.set(a.taskId,r))}}if(o||this._progressHandlers.delete(r),un(e))s(e);else{let i=L.fromError(e.error.code,e.error.message,e.error.data);s(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:s}=n??{};if(!s){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof L?i:new L(q.InternalError,String(i))}}return}let o;try{let i=await this.request(e,$r,n);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new L(q.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:a},Dt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:a.status==="failed"?yield{type:"error",error:new L(q.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new L(q.InternalError,`Task ${o} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)};return}let l=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(d=>setTimeout(d,l)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof L?i:new L(q.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i,task:a,relatedTask:l}=n??{};return new Promise((d,u)=>{let h=A=>{u(A)};if(!this._transport){h(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(A){h(A);return}n?.signal?.throwIfAborted();let v=this._requestMessageId++,g={...e,jsonrpc:"2.0",id:v};n?.onprogress&&(this._progressHandlers.set(v,n.onprogress),g.params={...e.params,_meta:{...e.params?._meta||{},progressToken:v}}),a&&(g.params={...g.params,task:a}),l&&(g.params={...g.params,_meta:{...g.params?._meta||{},[Ut]:l}});let w=A=>{this._responseHandlers.delete(v),this._progressHandlers.delete(v),this._cleanupTimeout(v),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:v,reason:String(A)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(ee=>this._onerror(new Error(`Failed to send cancellation: ${ee}`)));let z=A instanceof L?A:new L(q.RequestTimeout,String(A));u(z)};this._responseHandlers.set(v,A=>{if(!n?.signal?.aborted){if(A instanceof Error)return u(A);try{let z=zt(r,A.result);z.success?d(z.data):u(z.error)}catch(z){u(z)}}}),n?.signal?.addEventListener("abort",()=>{w(n?.signal?.reason)});let $=n?.timeout??Pv,R=()=>w(L.fromError(q.RequestTimeout,"Request timed out",{timeout:$}));this._setupTimeout(v,$,n?.maxTotalTimeout,R,n?.resetTimeoutOnProgress??!1);let E=l?.taskId;if(E){let A=z=>{let ee=this._responseHandlers.get(v);ee?ee(z):this._onerror(new Error(`Response handler missing for side-channeled request ${v}`))};this._requestResolvers.set(v,A),this._enqueueTaskMessage(E,{type:"request",message:g,timestamp:Date.now()}).catch(z=>{this._cleanupTimeout(v),u(z)})}else this._transport.send(g,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(A=>{this._cleanupTimeout(v),u(A)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},As,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},Os,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Uu,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||{},[Ut]: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||{},[Ut]:r.relatedTask}}}),this._transport?.send(a,r).catch(l=>this._onerror(l))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Ut]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Ca(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{let i=Oa(e,s);return Promise.resolve(r(i,o))})}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=Ca(e);this._notificationHandlers.set(n,s=>{let o=Oa(e,s);return Promise.resolve(r(o))})}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 s=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,s)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let s of n)if(s.type==="request"&&Ui(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new L(q.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e);s?.pollInterval&&(n=s.pollInterval)}catch{}return new Promise((s,o)=>{if(r.aborted){o(new L(q.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(i),o(new L(q.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await n.createTask(s,e.id,{method:e.method,params:e.params},r)},getTask:async s=>{let o=await n.getTask(s,r);if(!o)throw new L(q.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(s,o,i)=>{await n.storeTaskResult(s,o,i,r);let a=await n.getTask(s,r);if(a){let l=gn.parse({method:"notifications/tasks/status",params:a});await this.notification(l),Dt(a.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>n.getTaskResult(s,r),updateTaskStatus:async(s,o,i)=>{let a=await n.getTask(s,r);if(!a)throw new L(q.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(Dt(a.status))throw new L(q.InvalidParams,`Cannot update task "${s}" from terminal status "${a.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(s,o,i,r);let l=await n.getTask(s,r);if(l){let d=gn.parse({method:"notifications/tasks/status",params:l});await this.notification(d),Dt(l.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}}});var kn=j(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.regexpCode=ie.getEsmExportName=ie.getProperty=ie.safeStringify=ie.stringify=ie.strConcat=ie.addCodeArg=ie.str=ie._=ie.nil=ie._Code=ie.Name=ie.IDENTIFIER=ie._CodeOrName=void 0;var _n=class{};ie._CodeOrName=_n;ie.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var rr=class extends _n{constructor(e){if(super(),!ie.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}}};ie.Name=rr;var tt=class extends _n{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 rr&&(r[n.str]=(r[n.str]||0)+1),r),{})}};ie._Code=tt;ie.nil=new tt("");function Ip(t,...e){let r=[t[0]],n=0;for(;n<e.length;)za(r,e[n]),r.push(t[++n]);return new tt(r)}ie._=Ip;var ja=new tt("+");function Cp(t,...e){let r=[$n(t[0])],n=0;for(;n<e.length;)r.push(ja),za(r,e[n]),r.push(ja,$n(t[++n]));return Av(r),new tt(r)}ie.str=Cp;function za(t,e){e instanceof tt?t.push(...e._items):e instanceof rr?t.push(e):t.push(Ov(e))}ie.addCodeArg=za;function Av(t){let e=1;for(;e<t.length-1;){if(t[e]===ja){let r=Iv(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function Iv(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof rr||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 rr))return`"${t}${e.slice(1)}`}function Cv(t,e){return e.emptyStr()?t:t.emptyStr()?e:Cp`${t}${e}`}ie.strConcat=Cv;function Ov(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:$n(Array.isArray(t)?t.join(","):t)}function Nv(t){return new tt($n(t))}ie.stringify=Nv;function $n(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}ie.safeStringify=$n;function jv(t){return typeof t=="string"&&ie.IDENTIFIER.test(t)?new tt(`.${t}`):Ip`[${t}]`}ie.getProperty=jv;function zv(t){if(typeof t=="string"&&ie.IDENTIFIER.test(t))return new tt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}ie.getEsmExportName=zv;function Lv(t){return new tt(t.toString())}ie.regexpCode=Lv});var Da=j(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.ValueScope=Be.ValueScopeName=Be.Scope=Be.varKinds=Be.UsedValueState=void 0;var Me=kn(),La=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},eo;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(eo||(Be.UsedValueState=eo={}));Be.varKinds={const:new Me.Name("const"),let:new Me.Name("let"),var:new Me.Name("var")};var to=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Me.Name?e:this.name(e)}name(e){return new Me.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}}};Be.Scope=to;var ro=class extends Me.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Me._)`.${new Me.Name(r)}[${n}]`}};Be.ValueScopeName=ro;var Uv=(0,Me._)`\n`,Ua=class extends to{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Uv:Me.nil}}get(){return this._scope}name(e){return new ro(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 s=this.toName(e),{prefix:o}=s,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[o];if(a){let u=a.get(i);if(u)return u}else a=this._values[o]=new Map;a.set(i,s);let l=this._scope[o]||(this._scope[o]=[]),d=l.length;return l[d]=r.ref,s.setValue(r,{property:o,itemIndex:d}),s}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,Me._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,s=>{if(s.value===void 0)throw new Error(`CodeGen: name "${s}" has no value`);return s.value.code},r,n)}_reduceValues(e,r,n={},s){let o=Me.nil;for(let i in e){let a=e[i];if(!a)continue;let l=n[i]=n[i]||new Map;a.forEach(d=>{if(l.has(d))return;l.set(d,eo.Started);let u=r(d);if(u){let h=this.opts.es5?Be.varKinds.var:Be.varKinds.const;o=(0,Me._)`${o}${h} ${d} = ${u};${this.opts._n}`}else if(u=s?.(d))o=(0,Me._)`${o}${u}${this.opts._n}`;else throw new La(d);l.set(d,eo.Completed)})}return o}};Be.ValueScope=Ua});var W=j(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.or=Z.and=Z.not=Z.CodeGen=Z.operators=Z.varKinds=Z.ValueScopeName=Z.ValueScope=Z.Scope=Z.Name=Z.regexpCode=Z.stringify=Z.getProperty=Z.nil=Z.strConcat=Z.str=Z._=void 0;var ne=kn(),ct=Da(),Mt=kn();Object.defineProperty(Z,"_",{enumerable:!0,get:function(){return Mt._}});Object.defineProperty(Z,"str",{enumerable:!0,get:function(){return Mt.str}});Object.defineProperty(Z,"strConcat",{enumerable:!0,get:function(){return Mt.strConcat}});Object.defineProperty(Z,"nil",{enumerable:!0,get:function(){return Mt.nil}});Object.defineProperty(Z,"getProperty",{enumerable:!0,get:function(){return Mt.getProperty}});Object.defineProperty(Z,"stringify",{enumerable:!0,get:function(){return Mt.stringify}});Object.defineProperty(Z,"regexpCode",{enumerable:!0,get:function(){return Mt.regexpCode}});Object.defineProperty(Z,"Name",{enumerable:!0,get:function(){return Mt.Name}});var io=Da();Object.defineProperty(Z,"Scope",{enumerable:!0,get:function(){return io.Scope}});Object.defineProperty(Z,"ValueScope",{enumerable:!0,get:function(){return io.ValueScope}});Object.defineProperty(Z,"ValueScopeName",{enumerable:!0,get:function(){return io.ValueScopeName}});Object.defineProperty(Z,"varKinds",{enumerable:!0,get:function(){return io.varKinds}});Z.operators={GT:new ne._Code(">"),GTE:new ne._Code(">="),LT:new ne._Code("<"),LTE:new ne._Code("<="),EQ:new ne._Code("==="),NEQ:new ne._Code("!=="),NOT:new ne._Code("!"),OR:new ne._Code("||"),AND:new ne._Code("&&"),ADD:new ne._Code("+")};var xt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},qa=class extends xt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?ct.varKinds.var:this.varKind,s=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${s};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Pr(this.rhs,e,r)),this}get names(){return this.rhs instanceof ne._CodeOrName?this.rhs.names:{}}},no=class extends xt{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 ne.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Pr(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ne.Name?{}:{...this.lhs.names};return oo(e,this.rhs)}},Ma=class extends no{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Ba=class extends xt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Fa=class extends xt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Ha=class extends xt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Ka=class extends xt{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=Pr(this.code,e,r),this}get names(){return this.code instanceof ne._CodeOrName?this.code.names:{}}},xn=class extends xt{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,s=n.length;for(;s--;){let o=n[s];o.optimizeNames(e,r)||(Dv(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>or(e,r.names),{})}},Tt=class extends xn{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Va=class extends xn{},Er=class extends Tt{};Er.kind="else";var nr=class t extends Tt{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 Er(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Op(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=Pr(this.condition,e,r),this}get names(){let e=super.names;return oo(e,this.condition),this.else&&or(e,this.else.names),e}};nr.kind="if";var sr=class extends Tt{};sr.kind="for";var Ga=class extends sr{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=Pr(this.iteration,e,r),this}get names(){return or(super.names,this.iteration.names)}},Wa=class extends sr{constructor(e,r,n,s){super(),this.varKind=e,this.name=r,this.from=n,this.to=s}render(e){let r=e.es5?ct.varKinds.var:this.varKind,{name:n,from:s,to:o}=this;return`for(${r} ${n}=${s}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=oo(super.names,this.from);return oo(e,this.to)}},so=class extends sr{constructor(e,r,n,s){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=s}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=Pr(this.iterable,e,r),this}get names(){return or(super.names,this.iterable.names)}},Tn=class extends Tt{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)}};Tn.kind="func";var Rn=class extends xn{render(e){return"return "+super.render(e)}};Rn.kind="return";var Ja=class extends Tt{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,s;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(s=this.finally)===null||s===void 0||s.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&or(e,this.catch.names),this.finally&&or(e,this.finally.names),e}},En=class extends Tt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};En.kind="catch";var Pn=class extends Tt{render(e){return"finally"+super.render(e)}};Pn.kind="finally";var Za=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
884
|
+
`:""},this._extScope=e,this._scope=new ct.Scope({parent:e}),this._nodes=[new Va]}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,s){let o=this._scope.toName(r);return n!==void 0&&s&&(this._constants[o.str]=n),this._leafNode(new qa(e,o,n)),o}const(e,r,n){return this._def(ct.varKinds.const,e,r,n)}let(e,r,n){return this._def(ct.varKinds.let,e,r,n)}var(e,r,n){return this._def(ct.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new no(e,r,n))}add(e,r){return this._leafNode(new Ma(e,Z.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ne.nil&&this._leafNode(new Ka(e)),this}object(...e){let r=["{"];for(let[n,s]of e)r.length>1&&r.push(","),r.push(n),(n!==s||this.opts.es5)&&(r.push(":"),(0,ne.addCodeArg)(r,s));return r.push("}"),new ne._Code(r)}if(e,r,n){if(this._blockNode(new nr(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 nr(e))}else(){return this._elseNode(new Er)}endIf(){return this._endBlockNode(nr,Er)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Ga(e),r)}forRange(e,r,n,s,o=this.opts.es5?ct.varKinds.var:ct.varKinds.let){let i=this._scope.toName(e);return this._for(new Wa(o,i,r,n),()=>s(i))}forOf(e,r,n,s=ct.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=r instanceof ne.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ne._)`${i}.length`,a=>{this.var(o,(0,ne._)`${i}[${a}]`),n(o)})}return this._for(new so("of",s,o,r),()=>n(o))}forIn(e,r,n,s=this.opts.es5?ct.varKinds.var:ct.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ne._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new so("in",s,o,r),()=>n(o))}endFor(){return this._endBlockNode(sr)}label(e){return this._leafNode(new Ba(e))}break(e){return this._leafNode(new Fa(e))}return(e){let r=new Rn;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Rn)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new Ja;if(this._blockNode(s),this.code(e),r){let o=this.name("e");this._currNode=s.catch=new En(o),r(o)}return n&&(this._currNode=s.finally=new Pn,this.code(n)),this._endBlockNode(En,Pn)}throw(e){return this._leafNode(new Ha(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=ne.nil,n,s){return this._blockNode(new Tn(e,r,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(Tn)}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 nr))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}};Z.CodeGen=Za;function or(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function oo(t,e){return e instanceof ne._CodeOrName?or(t,e.names):t}function Pr(t,e,r){if(t instanceof ne.Name)return n(t);if(!s(t))return t;return new ne._Code(t._items.reduce((o,i)=>(i instanceof ne.Name&&(i=n(i)),i instanceof ne._Code?o.push(...i._items):o.push(i),o),[]));function n(o){let i=r[o.str];return i===void 0||e[o.str]!==1?o:(delete e[o.str],i)}function s(o){return o instanceof ne._Code&&o._items.some(i=>i instanceof ne.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function Dv(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Op(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ne._)`!${Ya(t)}`}Z.not=Op;var qv=Np(Z.operators.AND);function Mv(...t){return t.reduce(qv)}Z.and=Mv;var Bv=Np(Z.operators.OR);function Fv(...t){return t.reduce(Bv)}Z.or=Fv;function Np(t){return(e,r)=>e===ne.nil?r:r===ne.nil?e:(0,ne._)`${Ya(e)} ${t} ${Ya(r)}`}function Ya(t){return t instanceof ne.Name?t:(0,ne._)`(${t})`}});var se=j(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.checkStrictMode=Q.getErrorPath=Q.Type=Q.useFunc=Q.setEvaluated=Q.evaluatedPropsToName=Q.mergeEvaluated=Q.eachItem=Q.unescapeJsonPointer=Q.escapeJsonPointer=Q.escapeFragment=Q.unescapeFragment=Q.schemaRefOrVal=Q.schemaHasRulesButRef=Q.schemaHasRules=Q.checkUnknownRules=Q.alwaysValidSchema=Q.toHash=void 0;var he=W(),Hv=kn();function Kv(t){let e={};for(let r of t)e[r]=!0;return e}Q.toHash=Kv;function Vv(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Lp(t,e),!Up(e,t.self.RULES.all))}Q.alwaysValidSchema=Vv;function Lp(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let s=n.RULES.keywords;for(let o in e)s[o]||Mp(t,`unknown keyword: "${o}"`)}Q.checkUnknownRules=Lp;function Up(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}Q.schemaHasRules=Up;function Gv(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}Q.schemaHasRulesButRef=Gv;function Wv({topSchemaRef:t,schemaPath:e},r,n,s){if(!s){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,he._)`${r}`}return(0,he._)`${t}${e}${(0,he.getProperty)(n)}`}Q.schemaRefOrVal=Wv;function Jv(t){return Dp(decodeURIComponent(t))}Q.unescapeFragment=Jv;function Zv(t){return encodeURIComponent(Xa(t))}Q.escapeFragment=Zv;function Xa(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}Q.escapeJsonPointer=Xa;function Dp(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}Q.unescapeJsonPointer=Dp;function Yv(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}Q.eachItem=Yv;function jp({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(s,o,i,a)=>{let l=i===void 0?o:i instanceof he.Name?(o instanceof he.Name?t(s,o,i):e(s,o,i),i):o instanceof he.Name?(e(s,i,o),o):r(o,i);return a===he.Name&&!(l instanceof he.Name)?n(s,l):l}}Q.mergeEvaluated={props:jp({mergeNames:(t,e,r)=>t.if((0,he._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,he._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,he._)`${r} || {}`).code((0,he._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,he._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,he._)`${r} || {}`),ec(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:qp}),items:jp({mergeNames:(t,e,r)=>t.if((0,he._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,he._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,he._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,he._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function qp(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,he._)`{}`);return e!==void 0&&ec(t,r,e),r}Q.evaluatedPropsToName=qp;function ec(t,e,r){Object.keys(r).forEach(n=>t.assign((0,he._)`${e}${(0,he.getProperty)(n)}`,!0))}Q.setEvaluated=ec;var zp={};function Qv(t,e){return t.scopeValue("func",{ref:e,code:zp[e.code]||(zp[e.code]=new Hv._Code(e.code))})}Q.useFunc=Qv;var Qa;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Qa||(Q.Type=Qa={}));function Xv(t,e,r){if(t instanceof he.Name){let n=e===Qa.Num;return r?n?(0,he._)`"[" + ${t} + "]"`:(0,he._)`"['" + ${t} + "']"`:n?(0,he._)`"/" + ${t}`:(0,he._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,he.getProperty)(t).toString():"/"+Xa(t)}Q.getErrorPath=Xv;function Mp(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}Q.checkStrictMode=Mp});var Rt=j(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});var Pe=W(),eS={data:new Pe.Name("data"),valCxt:new Pe.Name("valCxt"),instancePath:new Pe.Name("instancePath"),parentData:new Pe.Name("parentData"),parentDataProperty:new Pe.Name("parentDataProperty"),rootData:new Pe.Name("rootData"),dynamicAnchors:new Pe.Name("dynamicAnchors"),vErrors:new Pe.Name("vErrors"),errors:new Pe.Name("errors"),this:new Pe.Name("this"),self:new Pe.Name("self"),scope:new Pe.Name("scope"),json:new Pe.Name("json"),jsonPos:new Pe.Name("jsonPos"),jsonLen:new Pe.Name("jsonLen"),jsonPart:new Pe.Name("jsonPart")};tc.default=eS});var An=j(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.extendErrors=Ae.resetErrorsCount=Ae.reportExtraError=Ae.reportError=Ae.keyword$DataError=Ae.keywordError=void 0;var oe=W(),ao=se(),ze=Rt();Ae.keywordError={message:({keyword:t})=>(0,oe.str)`must pass "${t}" keyword validation`};Ae.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,oe.str)`"${t}" keyword must be ${e} ($data)`:(0,oe.str)`"${t}" keyword is invalid ($data)`};function tS(t,e=Ae.keywordError,r,n){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,l=Hp(t,e,r);n??(i||a)?Bp(o,l):Fp(s,(0,oe._)`[${l}]`)}Ae.reportError=tS;function rS(t,e=Ae.keywordError,r){let{it:n}=t,{gen:s,compositeRule:o,allErrors:i}=n,a=Hp(t,e,r);Bp(s,a),o||i||Fp(n,ze.default.vErrors)}Ae.reportExtraError=rS;function nS(t,e){t.assign(ze.default.errors,e),t.if((0,oe._)`${ze.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,oe._)`${ze.default.vErrors}.length`,e),()=>t.assign(ze.default.vErrors,null)))}Ae.resetErrorsCount=nS;function sS({gen:t,keyword:e,schemaValue:r,data:n,errsCount:s,it:o}){if(s===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",s,ze.default.errors,a=>{t.const(i,(0,oe._)`${ze.default.vErrors}[${a}]`),t.if((0,oe._)`${i}.instancePath === undefined`,()=>t.assign((0,oe._)`${i}.instancePath`,(0,oe.strConcat)(ze.default.instancePath,o.errorPath))),t.assign((0,oe._)`${i}.schemaPath`,(0,oe.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,oe._)`${i}.schema`,r),t.assign((0,oe._)`${i}.data`,n))})}Ae.extendErrors=sS;function Bp(t,e){let r=t.const("err",e);t.if((0,oe._)`${ze.default.vErrors} === null`,()=>t.assign(ze.default.vErrors,(0,oe._)`[${r}]`),(0,oe._)`${ze.default.vErrors}.push(${r})`),t.code((0,oe._)`${ze.default.errors}++`)}function Fp(t,e){let{gen:r,validateName:n,schemaEnv:s}=t;s.$async?r.throw((0,oe._)`new ${t.ValidationError}(${e})`):(r.assign((0,oe._)`${n}.errors`,e),r.return(!1))}var ir={keyword:new oe.Name("keyword"),schemaPath:new oe.Name("schemaPath"),params:new oe.Name("params"),propertyName:new oe.Name("propertyName"),message:new oe.Name("message"),schema:new oe.Name("schema"),parentSchema:new oe.Name("parentSchema")};function Hp(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,oe._)`{}`:oS(t,e,r)}function oS(t,e,r={}){let{gen:n,it:s}=t,o=[iS(s,r),aS(t,r)];return cS(t,e,o),n.object(...o)}function iS({errorPath:t},{instancePath:e}){let r=e?(0,oe.str)`${t}${(0,ao.getErrorPath)(e,ao.Type.Str)}`:t;return[ze.default.instancePath,(0,oe.strConcat)(ze.default.instancePath,r)]}function aS({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let s=n?e:(0,oe.str)`${e}/${t}`;return r&&(s=(0,oe.str)`${s}${(0,ao.getErrorPath)(r,ao.Type.Str)}`),[ir.schemaPath,s]}function cS(t,{params:e,message:r},n){let{keyword:s,data:o,schemaValue:i,it:a}=t,{opts:l,propertyName:d,topSchemaRef:u,schemaPath:h}=a;n.push([ir.keyword,s],[ir.params,typeof e=="function"?e(t):e||(0,oe._)`{}`]),l.messages&&n.push([ir.message,typeof r=="function"?r(t):r]),l.verbose&&n.push([ir.schema,i],[ir.parentSchema,(0,oe._)`${u}${h}`],[ze.default.data,o]),d&&n.push([ir.propertyName,d])}});var Vp=j(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.boolOrEmptySchema=Ar.topBoolOrEmptySchema=void 0;var lS=An(),dS=W(),uS=Rt(),pS={message:"boolean schema is false"};function fS(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Kp(t,!1):typeof r=="object"&&r.$async===!0?e.return(uS.default.data):(e.assign((0,dS._)`${n}.errors`,null),e.return(!0))}Ar.topBoolOrEmptySchema=fS;function hS(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Kp(t)):r.var(e,!0)}Ar.boolOrEmptySchema=hS;function Kp(t,e){let{gen:r,data:n}=t,s={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,lS.reportError)(s,pS,void 0,e)}});var rc=j(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.getRules=Ir.isJSONType=void 0;var mS=["string","number","integer","boolean","null","object","array"],gS=new Set(mS);function yS(t){return typeof t=="string"&&gS.has(t)}Ir.isJSONType=yS;function bS(){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:{}}}Ir.getRules=bS});var nc=j(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.shouldUseRule=Bt.shouldUseGroup=Bt.schemaHasRulesForType=void 0;function wS({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Gp(t,n)}Bt.schemaHasRulesForType=wS;function Gp(t,e){return e.rules.some(r=>Wp(t,r))}Bt.shouldUseGroup=Gp;function Wp(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))}Bt.shouldUseRule=Wp});var In=j(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.reportTypeError=Ie.checkDataTypes=Ie.checkDataType=Ie.coerceAndCheckDataType=Ie.getJSONTypes=Ie.getSchemaTypes=Ie.DataType=void 0;var vS=rc(),SS=nc(),_S=An(),G=W(),Jp=se(),Cr;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Cr||(Ie.DataType=Cr={}));function $S(t){let e=Zp(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}Ie.getSchemaTypes=$S;function Zp(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(vS.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ie.getJSONTypes=Zp;function kS(t,e){let{gen:r,data:n,opts:s}=t,o=xS(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,SS.schemaHasRulesForType)(t,e[0]));if(i){let a=oc(e,n,s.strictNumbers,Cr.Wrong);r.if(a,()=>{o.length?TS(t,e,o):ic(t)})}return i}Ie.coerceAndCheckDataType=kS;var Yp=new Set(["string","number","integer","boolean","null"]);function xS(t,e){return e?t.filter(r=>Yp.has(r)||e==="array"&&r==="array"):[]}function TS(t,e,r){let{gen:n,data:s,opts:o}=t,i=n.let("dataType",(0,G._)`typeof ${s}`),a=n.let("coerced",(0,G._)`undefined`);o.coerceTypes==="array"&&n.if((0,G._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,(0,G._)`${s}[0]`).assign(i,(0,G._)`typeof ${s}`).if(oc(e,s,o.strictNumbers),()=>n.assign(a,s))),n.if((0,G._)`${a} !== undefined`);for(let d of r)(Yp.has(d)||d==="array"&&o.coerceTypes==="array")&&l(d);n.else(),ic(t),n.endIf(),n.if((0,G._)`${a} !== undefined`,()=>{n.assign(s,a),RS(t,a)});function l(d){switch(d){case"string":n.elseIf((0,G._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,G._)`"" + ${s}`).elseIf((0,G._)`${s} === null`).assign(a,(0,G._)`""`);return;case"number":n.elseIf((0,G._)`${i} == "boolean" || ${s} === null
|
|
885
|
+
|| (${i} == "string" && ${s} && ${s} == +${s})`).assign(a,(0,G._)`+${s}`);return;case"integer":n.elseIf((0,G._)`${i} === "boolean" || ${s} === null
|
|
886
|
+
|| (${i} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(a,(0,G._)`+${s}`);return;case"boolean":n.elseIf((0,G._)`${s} === "false" || ${s} === 0 || ${s} === null`).assign(a,!1).elseIf((0,G._)`${s} === "true" || ${s} === 1`).assign(a,!0);return;case"null":n.elseIf((0,G._)`${s} === "" || ${s} === 0 || ${s} === false`),n.assign(a,null);return;case"array":n.elseIf((0,G._)`${i} === "string" || ${i} === "number"
|
|
887
|
+
|| ${i} === "boolean" || ${s} === null`).assign(a,(0,G._)`[${s}]`)}}}function RS({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,G._)`${e} !== undefined`,()=>t.assign((0,G._)`${e}[${r}]`,n))}function sc(t,e,r,n=Cr.Correct){let s=n===Cr.Correct?G.operators.EQ:G.operators.NEQ,o;switch(t){case"null":return(0,G._)`${e} ${s} null`;case"array":o=(0,G._)`Array.isArray(${e})`;break;case"object":o=(0,G._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,G._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,G._)`typeof ${e} ${s} ${t}`}return n===Cr.Correct?o:(0,G.not)(o);function i(a=G.nil){return(0,G.and)((0,G._)`typeof ${e} == "number"`,a,r?(0,G._)`isFinite(${e})`:G.nil)}}Ie.checkDataType=sc;function oc(t,e,r,n){if(t.length===1)return sc(t[0],e,r,n);let s,o=(0,Jp.toHash)(t);if(o.array&&o.object){let i=(0,G._)`typeof ${e} != "object"`;s=o.null?i:(0,G._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=G.nil;o.number&&delete o.integer;for(let i in o)s=(0,G.and)(s,sc(i,e,r,n));return s}Ie.checkDataTypes=oc;var ES={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,G._)`{type: ${t}}`:(0,G._)`{type: ${e}}`};function ic(t){let e=PS(t);(0,_S.reportError)(e,ES)}Ie.reportTypeError=ic;function PS(t){let{gen:e,data:r,schema:n}=t,s=(0,Jp.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var Xp=j(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});co.assignDefaults=void 0;var Or=W(),AS=se();function IS(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)Qp(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,o)=>Qp(t,o,s.default))}co.assignDefaults=IS;function Qp(t,e,r){let{gen:n,compositeRule:s,data:o,opts:i}=t;if(r===void 0)return;let a=(0,Or._)`${o}${(0,Or.getProperty)(e)}`;if(s){(0,AS.checkStrictMode)(t,`default is ignored for: ${a}`);return}let l=(0,Or._)`${a} === undefined`;i.useDefaults==="empty"&&(l=(0,Or._)`${l} || ${a} === null || ${a} === ""`),n.if(l,(0,Or._)`${a} = ${(0,Or.stringify)(r)}`)}});var rt=j(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.validateUnion=fe.validateArray=fe.usePattern=fe.callValidateCode=fe.schemaProperties=fe.allSchemaProperties=fe.noPropertyInData=fe.propertyInData=fe.isOwnProperty=fe.hasPropFunc=fe.reportMissingProp=fe.checkMissingProp=fe.checkReportMissingProp=void 0;var me=W(),ac=se(),Ft=Rt(),CS=se();function OS(t,e){let{gen:r,data:n,it:s}=t;r.if(lc(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,me._)`${e}`},!0),t.error()})}fe.checkReportMissingProp=OS;function NS({gen:t,data:e,it:{opts:r}},n,s){return(0,me.or)(...n.map(o=>(0,me.and)(lc(t,e,o,r.ownProperties),(0,me._)`${s} = ${o}`)))}fe.checkMissingProp=NS;function jS(t,e){t.setParams({missingProperty:e},!0),t.error()}fe.reportMissingProp=jS;function ef(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,me._)`Object.prototype.hasOwnProperty`})}fe.hasPropFunc=ef;function cc(t,e,r){return(0,me._)`${ef(t)}.call(${e}, ${r})`}fe.isOwnProperty=cc;function zS(t,e,r,n){let s=(0,me._)`${e}${(0,me.getProperty)(r)} !== undefined`;return n?(0,me._)`${s} && ${cc(t,e,r)}`:s}fe.propertyInData=zS;function lc(t,e,r,n){let s=(0,me._)`${e}${(0,me.getProperty)(r)} === undefined`;return n?(0,me.or)(s,(0,me.not)(cc(t,e,r))):s}fe.noPropertyInData=lc;function tf(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}fe.allSchemaProperties=tf;function LS(t,e){return tf(e).filter(r=>!(0,ac.alwaysValidSchema)(t,e[r]))}fe.schemaProperties=LS;function US({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:o},it:i},a,l,d){let u=d?(0,me._)`${t}, ${e}, ${n}${s}`:e,h=[[Ft.default.instancePath,(0,me.strConcat)(Ft.default.instancePath,o)],[Ft.default.parentData,i.parentData],[Ft.default.parentDataProperty,i.parentDataProperty],[Ft.default.rootData,Ft.default.rootData]];i.opts.dynamicRef&&h.push([Ft.default.dynamicAnchors,Ft.default.dynamicAnchors]);let v=(0,me._)`${u}, ${r.object(...h)}`;return l!==me.nil?(0,me._)`${a}.call(${l}, ${v})`:(0,me._)`${a}(${v})`}fe.callValidateCode=US;var DS=(0,me._)`new RegExp`;function qS({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:s}=e.code,o=s(r,n);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,me._)`${s.code==="new RegExp"?DS:(0,CS.useFunc)(t,s)}(${r}, ${n})`})}fe.usePattern=qS;function MS(t){let{gen:e,data:r,keyword:n,it:s}=t,o=e.name("valid");if(s.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(o,!0),i(()=>e.break()),o;function i(a){let l=e.const("len",(0,me._)`${r}.length`);e.forRange("i",0,l,d=>{t.subschema({keyword:n,dataProp:d,dataPropType:ac.Type.Num},o),e.if((0,me.not)(o),a)})}}fe.validateArray=MS;function BS(t){let{gen:e,schema:r,keyword:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0,ac.alwaysValidSchema)(s,l))&&!s.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((l,d)=>{let u=t.subschema({keyword:n,schemaProp:d,compositeRule:!0},a);e.assign(i,(0,me._)`${i} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,me.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}fe.validateUnion=BS});var sf=j(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.validateKeywordUsage=gt.validSchemaType=gt.funcKeywordCode=gt.macroKeywordCode=void 0;var Le=W(),ar=Rt(),FS=rt(),HS=An();function KS(t,e){let{gen:r,keyword:n,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),l=nf(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let d=r.name("valid");t.subschema({schema:a,schemaPath:Le.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},d),t.pass(d,()=>t.error(!0))}gt.macroKeywordCode=KS;function VS(t,e){var r;let{gen:n,keyword:s,schema:o,parentSchema:i,$data:a,it:l}=t;WS(l,e);let d=!a&&e.compile?e.compile.call(l.self,o,i,l):e.validate,u=nf(n,s,d),h=n.let("valid");t.block$data(h,v),t.ok((r=e.valid)!==null&&r!==void 0?r:h);function v(){if(e.errors===!1)$(),e.modifying&&rf(t),R(()=>t.error());else{let E=e.async?g():w();e.modifying&&rf(t),R(()=>GS(t,E))}}function g(){let E=n.let("ruleErrs",null);return n.try(()=>$((0,Le._)`await `),A=>n.assign(h,!1).if((0,Le._)`${A} instanceof ${l.ValidationError}`,()=>n.assign(E,(0,Le._)`${A}.errors`),()=>n.throw(A))),E}function w(){let E=(0,Le._)`${u}.errors`;return n.assign(E,null),$(Le.nil),E}function $(E=e.async?(0,Le._)`await `:Le.nil){let A=l.opts.passContext?ar.default.this:ar.default.self,z=!("compile"in e&&!a||e.schema===!1);n.assign(h,(0,Le._)`${E}${(0,FS.callValidateCode)(t,u,A,z)}`,e.modifying)}function R(E){var A;n.if((0,Le.not)((A=e.valid)!==null&&A!==void 0?A:h),E)}}gt.funcKeywordCode=VS;function rf(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Le._)`${n.parentData}[${n.parentDataProperty}]`))}function GS(t,e){let{gen:r}=t;r.if((0,Le._)`Array.isArray(${e})`,()=>{r.assign(ar.default.vErrors,(0,Le._)`${ar.default.vErrors} === null ? ${e} : ${ar.default.vErrors}.concat(${e})`).assign(ar.default.errors,(0,Le._)`${ar.default.vErrors}.length`),(0,HS.extendErrors)(t)},()=>t.error())}function WS({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function nf(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,Le.stringify)(r)})}function JS(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")}gt.validSchemaType=JS;function ZS({schema:t,opts:e,self:r,errSchemaPath:n},s,o){if(Array.isArray(s.keyword)?!s.keyword.includes(o):s.keyword!==o)throw new Error("ajv implementation error");let i=s.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${o}: ${i.join(",")}`);if(s.validateSchema&&!s.validateSchema(t[o])){let l=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}gt.validateKeywordUsage=ZS});var af=j(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.extendSubschemaMode=Ht.extendSubschemaData=Ht.getSubschema=void 0;var yt=W(),of=se();function YS(t,{keyword:e,schemaProp:r,schema:n,schemaPath:s,errSchemaPath:o,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,yt._)`${t.schemaPath}${(0,yt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,yt._)`${t.schemaPath}${(0,yt.getProperty)(e)}${(0,yt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,of.escapeFragment)(r)}`}}if(n!==void 0){if(s===void 0||o===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:s,topSchemaRef:i,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}Ht.getSubschema=YS;function QS(t,e,{dataProp:r,dataPropType:n,data:s,dataTypes:o,propertyName:i}){if(s!==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:d,dataPathArr:u,opts:h}=e,v=a.let("data",(0,yt._)`${e.data}${(0,yt.getProperty)(r)}`,!0);l(v),t.errorPath=(0,yt.str)`${d}${(0,of.getErrorPath)(r,n,h.jsPropertySyntax)}`,t.parentDataProperty=(0,yt._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(s!==void 0){let d=s instanceof yt.Name?s:a.let("data",s,!0);l(d),i!==void 0&&(t.propertyName=i)}o&&(t.dataTypes=o);function l(d){t.data=d,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,d]}}Ht.extendSubschemaData=QS;function XS(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:s,allErrors:o}){n!==void 0&&(t.compositeRule=n),s!==void 0&&(t.createErrors=s),o!==void 0&&(t.allErrors=o),t.jtdDiscriminator=e,t.jtdMetadata=r}Ht.extendSubschemaMode=XS});var dc=j((nC,cf)=>{"use strict";cf.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,s,o;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(s=n;s--!==0;)if(!t(e[s],r[s]))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(o=Object.keys(e),n=o.length,n!==Object.keys(r).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[s]))return!1;for(s=n;s--!==0;){var i=o[s];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var df=j((sC,lf)=>{"use strict";var Kt=lf.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},s=r.post||function(){};lo(e,n,s,t,"",t)};Kt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Kt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Kt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Kt.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 lo(t,e,r,n,s,o,i,a,l,d){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,s,o,i,a,l,d);for(var u in n){var h=n[u];if(Array.isArray(h)){if(u in Kt.arrayKeywords)for(var v=0;v<h.length;v++)lo(t,e,r,h[v],s+"/"+u+"/"+v,o,s,u,n,v)}else if(u in Kt.propsKeywords){if(h&&typeof h=="object")for(var g in h)lo(t,e,r,h[g],s+"/"+u+"/"+e_(g),o,s,u,n,g)}else(u in Kt.keywords||t.allKeys&&!(u in Kt.skipKeywords))&&lo(t,e,r,h,s+"/"+u,o,s,u,n)}r(n,s,o,i,a,l,d)}}function e_(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Cn=j(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.getSchemaRefs=Fe.resolveUrl=Fe.normalizeId=Fe._getFullPath=Fe.getFullPath=Fe.inlineRef=void 0;var t_=se(),r_=dc(),n_=df(),s_=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function o_(t,e=!0){return typeof t=="boolean"?!0:e===!0?!uc(t):e?uf(t)<=e:!1}Fe.inlineRef=o_;var i_=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function uc(t){for(let e in t){if(i_.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(uc)||typeof r=="object"&&uc(r))return!0}return!1}function uf(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!s_.has(r)&&(typeof t[r]=="object"&&(0,t_.eachItem)(t[r],n=>e+=uf(n)),e===1/0))return 1/0}return e}function pf(t,e="",r){r!==!1&&(e=Nr(e));let n=t.parse(e);return ff(t,n)}Fe.getFullPath=pf;function ff(t,e){return t.serialize(e).split("#")[0]+"#"}Fe._getFullPath=ff;var a_=/#\/?$/;function Nr(t){return t?t.replace(a_,""):""}Fe.normalizeId=Nr;function c_(t,e,r){return r=Nr(r),t.resolve(e,r)}Fe.resolveUrl=c_;var l_=/^[a-z_][-a-z0-9._]*$/i;function d_(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=Nr(t[r]||e),o={"":s},i=pf(n,s,!1),a={},l=new Set;return n_(t,{allKeys:!0},(h,v,g,w)=>{if(w===void 0)return;let $=i+v,R=o[w];typeof h[r]=="string"&&(R=E.call(this,h[r])),A.call(this,h.$anchor),A.call(this,h.$dynamicAnchor),o[v]=R;function E(z){let ee=this.opts.uriResolver.resolve;if(z=Nr(R?ee(R,z):z),l.has(z))throw u(z);l.add(z);let F=this.refs[z];return typeof F=="string"&&(F=this.refs[F]),typeof F=="object"?d(h,F.schema,z):z!==Nr($)&&(z[0]==="#"?(d(h,a[z],z),a[z]=h):this.refs[z]=$),z}function A(z){if(typeof z=="string"){if(!l_.test(z))throw new Error(`invalid anchor "${z}"`);E.call(this,`#${z}`)}}}),a;function d(h,v,g){if(v!==void 0&&!r_(h,v))throw u(g)}function u(h){return new Error(`reference "${h}" resolves to more than one schema`)}}Fe.getSchemaRefs=d_});var jn=j(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.getData=Vt.KeywordCxt=Vt.validateFunctionCode=void 0;var bf=Vp(),hf=In(),fc=nc(),uo=In(),u_=Xp(),Nn=sf(),pc=af(),U=W(),H=Rt(),p_=Cn(),Et=se(),On=An();function f_(t){if(Sf(t)&&(_f(t),vf(t))){g_(t);return}wf(t,()=>(0,bf.topBoolOrEmptySchema)(t))}Vt.validateFunctionCode=f_;function wf({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},o){s.code.es5?t.func(e,(0,U._)`${H.default.data}, ${H.default.valCxt}`,n.$async,()=>{t.code((0,U._)`"use strict"; ${mf(r,s)}`),m_(t,s),t.code(o)}):t.func(e,(0,U._)`${H.default.data}, ${h_(s)}`,n.$async,()=>t.code(mf(r,s)).code(o))}function h_(t){return(0,U._)`{${H.default.instancePath}="", ${H.default.parentData}, ${H.default.parentDataProperty}, ${H.default.rootData}=${H.default.data}${t.dynamicRef?(0,U._)`, ${H.default.dynamicAnchors}={}`:U.nil}}={}`}function m_(t,e){t.if(H.default.valCxt,()=>{t.var(H.default.instancePath,(0,U._)`${H.default.valCxt}.${H.default.instancePath}`),t.var(H.default.parentData,(0,U._)`${H.default.valCxt}.${H.default.parentData}`),t.var(H.default.parentDataProperty,(0,U._)`${H.default.valCxt}.${H.default.parentDataProperty}`),t.var(H.default.rootData,(0,U._)`${H.default.valCxt}.${H.default.rootData}`),e.dynamicRef&&t.var(H.default.dynamicAnchors,(0,U._)`${H.default.valCxt}.${H.default.dynamicAnchors}`)},()=>{t.var(H.default.instancePath,(0,U._)`""`),t.var(H.default.parentData,(0,U._)`undefined`),t.var(H.default.parentDataProperty,(0,U._)`undefined`),t.var(H.default.rootData,H.default.data),e.dynamicRef&&t.var(H.default.dynamicAnchors,(0,U._)`{}`)})}function g_(t){let{schema:e,opts:r,gen:n}=t;wf(t,()=>{r.$comment&&e.$comment&&kf(t),S_(t),n.let(H.default.vErrors,null),n.let(H.default.errors,0),r.unevaluated&&y_(t),$f(t),k_(t)})}function y_(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,U._)`${r}.evaluated`),e.if((0,U._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,U._)`${t.evaluated}.props`,(0,U._)`undefined`)),e.if((0,U._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,U._)`${t.evaluated}.items`,(0,U._)`undefined`))}function mf(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,U._)`/*# sourceURL=${r} */`:U.nil}function b_(t,e){if(Sf(t)&&(_f(t),vf(t))){w_(t,e);return}(0,bf.boolOrEmptySchema)(t,e)}function vf({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 Sf(t){return typeof t.schema!="boolean"}function w_(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&kf(t),__(t),$_(t);let o=n.const("_errs",H.default.errors);$f(t,o),n.var(e,(0,U._)`${o} === ${H.default.errors}`)}function _f(t){(0,Et.checkUnknownRules)(t),v_(t)}function $f(t,e){if(t.opts.jtd)return gf(t,[],!1,e);let r=(0,hf.getSchemaTypes)(t.schema),n=(0,hf.coerceAndCheckDataType)(t,r);gf(t,r,!n,e)}function v_(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Et.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function S_(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Et.checkStrictMode)(t,"default is ignored in the schema root")}function __(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,p_.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function $_(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function kf({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){let o=r.$comment;if(s.$comment===!0)t.code((0,U._)`${H.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,U.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,U._)`${H.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function k_(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:o}=t;r.$async?e.if((0,U._)`${H.default.errors} === 0`,()=>e.return(H.default.data),()=>e.throw((0,U._)`new ${s}(${H.default.vErrors})`)):(e.assign((0,U._)`${n}.errors`,H.default.vErrors),o.unevaluated&&x_(t),e.return((0,U._)`${H.default.errors} === 0`))}function x_({gen:t,evaluated:e,props:r,items:n}){r instanceof U.Name&&t.assign((0,U._)`${e}.props`,r),n instanceof U.Name&&t.assign((0,U._)`${e}.items`,n)}function gf(t,e,r,n){let{gen:s,schema:o,data:i,allErrors:a,opts:l,self:d}=t,{RULES:u}=d;if(o.$ref&&(l.ignoreKeywordsWithRef||!(0,Et.schemaHasRulesButRef)(o,u))){s.block(()=>Tf(t,"$ref",u.all.$ref.definition));return}l.jtd||T_(t,e),s.block(()=>{for(let v of u.rules)h(v);h(u.post)});function h(v){(0,fc.shouldUseGroup)(o,v)&&(v.type?(s.if((0,uo.checkDataType)(v.type,i,l.strictNumbers)),yf(t,v),e.length===1&&e[0]===v.type&&r&&(s.else(),(0,uo.reportTypeError)(t)),s.endIf()):yf(t,v),a||s.if((0,U._)`${H.default.errors} === ${n||0}`))}}function yf(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,u_.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,fc.shouldUseRule)(n,o)&&Tf(t,o.keyword,o.definition,e.type)})}function T_(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(R_(t,e),t.opts.allowUnionTypes||E_(t,e),P_(t,t.dataTypes))}function R_(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{xf(t.dataTypes,r)||hc(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),I_(t,e)}}function E_(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&hc(t,"use allowUnionTypes to allow union type keyword")}function P_(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,fc.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>A_(e,i))&&hc(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function A_(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function xf(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function I_(t,e){let r=[];for(let n of t.dataTypes)xf(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function hc(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Et.checkStrictMode)(t,e,t.opts.strictTypes)}var po=class{constructor(e,r,n){if((0,Nn.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,Et.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",Rf(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Nn.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",H.default.errors))}result(e,r,n){this.failResult((0,U.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,U.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,U._)`${r} !== undefined && (${(0,U.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?On.reportExtraError:On.reportError)(this,this.def.error,r)}$dataError(){(0,On.reportError)(this,this.def.$dataError||On.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,On.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=U.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=U.nil,r=U.nil){if(!this.$data)return;let{gen:n,schemaCode:s,schemaType:o,def:i}=this;n.if((0,U.or)((0,U._)`${s} === undefined`,r)),e!==U.nil&&n.assign(e,!0),(o.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==U.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:s,it:o}=this;return(0,U.or)(i(),a());function i(){if(n.length){if(!(r instanceof U.Name))throw new Error("ajv implementation error");let l=Array.isArray(n)?n:[n];return(0,U._)`${(0,uo.checkDataTypes)(l,r,o.opts.strictNumbers,uo.DataType.Wrong)}`}return U.nil}function a(){if(s.validateSchema){let l=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,U._)`!${l}(${r})`}return U.nil}}subschema(e,r){let n=(0,pc.getSubschema)(this.it,e);(0,pc.extendSubschemaData)(n,this.it,e),(0,pc.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return b_(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Et.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Et.mergeEvaluated.items(s,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:s}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return s.if(r,()=>this.mergeEvaluated(e,U.Name)),!0}};Vt.KeywordCxt=po;function Tf(t,e,r,n){let s=new po(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,Nn.funcKeywordCode)(s,r):"macro"in r?(0,Nn.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,Nn.funcKeywordCode)(s,r)}var C_=/^\/(?:[^~]|~0|~1)*$/,O_=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Rf(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,o;if(t==="")return H.default.rootData;if(t[0]==="/"){if(!C_.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=H.default.rootData}else{let d=O_.exec(t);if(!d)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+d[1];if(s=d[2],s==="#"){if(u>=e)throw new Error(l("property/index",u));return n[e-u]}if(u>e)throw new Error(l("data",u));if(o=r[e-u],!s)return o}let i=o,a=s.split("/");for(let d of a)d&&(o=(0,U._)`${o}${(0,U.getProperty)((0,Et.unescapeJsonPointer)(d))}`,i=(0,U._)`${i} && ${o}`);return i;function l(d,u){return`Cannot access ${d} ${u} levels up, current level is ${e}`}}Vt.getData=Rf});var fo=j(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});var mc=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};gc.default=mc});var zn=j(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});var yc=Cn(),bc=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,yc.resolveUrl)(e,r,n),this.missingSchema=(0,yc.normalizeId)((0,yc.getFullPath)(e,this.missingRef))}};wc.default=bc});var mo=j(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.resolveSchema=nt.getCompilingSchema=nt.resolveRef=nt.compileSchema=nt.SchemaEnv=void 0;var lt=W(),N_=fo(),cr=Rt(),dt=Cn(),Ef=se(),j_=jn(),jr=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,dt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};nt.SchemaEnv=jr;function Sc(t){let e=Pf.call(this,t);if(e)return e;let r=(0,dt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new lt.CodeGen(this.scope,{es5:n,lines:s,ownProperties:o}),a;t.$async&&(a=i.scopeValue("Error",{ref:N_.default,code:(0,lt._)`require("ajv/dist/runtime/validation_error").default`}));let l=i.scopeName("validate");t.validateName=l;let d={gen:i,allErrors:this.opts.allErrors,data:cr.default.data,parentData:cr.default.parentData,parentDataProperty:cr.default.parentDataProperty,dataNames:[cr.default.data],dataPathArr:[lt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,lt.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:lt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,lt._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,j_.validateFunctionCode)(d),i.optimize(this.opts.code.optimize);let h=i.toString();u=`${i.scopeRefs(cr.default.scope)}return ${h}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let g=new Function(`${cr.default.self}`,`${cr.default.scope}`,u)(this,this.scope.get());if(this.scope.value(l,{ref:g}),g.errors=null,g.schema=t.schema,g.schemaEnv=t,t.$async&&(g.$async=!0),this.opts.code.source===!0&&(g.source={validateName:l,validateCode:h,scopeValues:i._values}),this.opts.unevaluated){let{props:w,items:$}=d;g.evaluated={props:w instanceof lt.Name?void 0:w,items:$ instanceof lt.Name?void 0:$,dynamicProps:w instanceof lt.Name,dynamicItems:$ instanceof lt.Name},g.source&&(g.source.evaluated=(0,lt.stringify)(g.evaluated))}return t.validate=g,t}catch(h){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),h}finally{this._compilations.delete(t)}}nt.compileSchema=Sc;function z_(t,e,r){var n;r=(0,dt.resolveUrl)(this.opts.uriResolver,e,r);let s=t.refs[r];if(s)return s;let o=D_.call(this,t,r);if(o===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(o=new jr({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=L_.call(this,o)}nt.resolveRef=z_;function L_(t){return(0,dt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Sc.call(this,t)}function Pf(t){for(let e of this._compilations)if(U_(e,t))return e}nt.getCompilingSchema=Pf;function U_(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function D_(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||ho.call(this,t,e)}function ho(t,e){let r=this.opts.uriResolver.parse(e),n=(0,dt._getFullPath)(this.opts.uriResolver,r),s=(0,dt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return vc.call(this,r,t);let o=(0,dt.normalizeId)(n),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=ho.call(this,t,i);return typeof a?.schema!="object"?void 0:vc.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Sc.call(this,i),o===(0,dt.normalizeId)(e)){let{schema:a}=i,{schemaId:l}=this.opts,d=a[l];return d&&(s=(0,dt.resolveUrl)(this.opts.uriResolver,s,d)),new jr({schema:a,schemaId:l,root:t,baseId:s})}return vc.call(this,r,i)}}nt.resolveSchema=ho;var q_=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function vc(t,{baseId:e,schema:r,root:n}){var s;if(((s=t.fragment)===null||s===void 0?void 0:s[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let l=r[(0,Ef.unescapeFragment)(a)];if(l===void 0)return;r=l;let d=typeof r=="object"&&r[this.opts.schemaId];!q_.has(a)&&d&&(e=(0,dt.resolveUrl)(this.opts.uriResolver,e,d))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,Ef.schemaHasRulesButRef)(r,this.RULES)){let a=(0,dt.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=ho.call(this,n,a)}let{schemaId:i}=this.opts;if(o=o||new jr({schema:r,schemaId:i,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var Af=j((dC,M_)=>{M_.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 kc=j((uC,zf)=>{"use strict";var B_=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Cf=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),_c=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Of=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),F_=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function $c(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 H_=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function If(t){return t.length=0,!0}function K_(t,e,r){if(t.length){let n=$c(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function V_(t){let e=0,r={error:!1,address:"",zone:""},n=[],s=[],o=!1,i=!1,a=K_;for(let l=0;l<t.length;l++){let d=t[l];if(!(d==="["||d==="]"))if(d===":"){if(o===!0&&(i=!0),!a(s,n,r))break;if(++e>7){r.error=!0;break}l>0&&t[l-1]===":"&&(o=!0),n.push(":");continue}else if(d==="%"){if(!a(s,n,r))break;a=If}else{s.push(d);continue}}return s.length&&(a===If?r.zone=s.join(""):i?n.push(s.join("")):n.push($c(s))),r.address=n.join(""),r}function Nf(t){if(G_(t,":")<2)return{host:t,isIPV6:!1};let e=V_(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 G_(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function W_(t){let e=t,r=[],n=-1,s=0;for(;s=e.length;){if(s===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(s===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(s===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 J_={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Z_=/[@/?#:]/g,Y_=/[@/?#]/g;function jf(t,e){let r=e?Y_:Z_;return r.lastIndex=0,t.replace(r,n=>J_[n])}function Q_(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 s=t.slice(n+1,n+3);if(_c(s)){let o=s.toUpperCase(),i=String.fromCharCode(parseInt(o,16));e&&Of(i)?r+=i:r+="%"+o,n+=2;continue}}r+=t[n]}return r}function X_(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(_c(n)){let s=n.toUpperCase(),o=String.fromCharCode(parseInt(s,16));o!=="."&&Of(o)?e+=o:e+="%"+s,r+=2;continue}}F_(t[r])?e+=t[r]:e+=escape(t[r])}return e}function e$(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(_c(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function t$(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!Cf(r)){let n=Nf(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=jf(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}zf.exports={nonSimpleDomain:H_,recomposeAuthority:t$,reescapeHostDelimiters:jf,normalizePercentEncoding:Q_,normalizePathEncoding:X_,escapePreservingEscapes:e$,removeDotSegments:W_,isIPv4:Cf,isUUID:B_,normalizeIPv6:Nf,stringArrayToHexStripped:$c}});var Mf=j((pC,qf)=>{"use strict";var{isUUID:r$}=kc(),n$=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,s$=["http","https","ws","wss","urn","urn:uuid"];function o$(t){return s$.indexOf(t)!==-1}function xc(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 Lf(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Uf(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 i$(t){return t.secure=xc(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function a$(t){if((t.port===(xc(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 c$(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(n$);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let s=`${n}:${e.nid||t.nid}`,o=Tc(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function l$(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(),s=`${r}:${e.nid||n}`,o=Tc(s);o&&(t=o.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function d$(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!r$(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function u$(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Df={scheme:"http",domainHost:!0,parse:Lf,serialize:Uf},p$={scheme:"https",domainHost:Df.domainHost,parse:Lf,serialize:Uf},go={scheme:"ws",domainHost:!0,parse:i$,serialize:a$},f$={scheme:"wss",domainHost:go.domainHost,parse:go.parse,serialize:go.serialize},h$={scheme:"urn",parse:c$,serialize:l$,skipNormalize:!0},m$={scheme:"urn:uuid",parse:d$,serialize:u$,skipNormalize:!0},yo={http:Df,https:p$,ws:go,wss:f$,urn:h$,"urn:uuid":m$};Object.setPrototypeOf(yo,null);function Tc(t){return t&&(yo[t]||yo[t.toLowerCase()])||void 0}qf.exports={wsIsSecure:xc,SCHEMES:yo,isValidSchemeName:o$,getSchemeHandler:Tc}});var Vf=j((fC,vo)=>{"use strict";var{normalizeIPv6:g$,removeDotSegments:Ln,recomposeAuthority:y$,normalizePercentEncoding:b$,normalizePathEncoding:w$,escapePreservingEscapes:v$,reescapeHostDelimiters:S$,isIPv4:_$,nonSimpleDomain:$$}=kc(),{SCHEMES:k$,getSchemeHandler:Ff}=Mf();function x$(t,e){return typeof t=="string"?t=C$(t,e):typeof t=="object"&&(t=wo(lr(t,e),e)),t}function T$(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:s,malformedAuthorityOrPort:o}=bo(t,n),{parsed:i,malformedAuthorityOrPort:a}=bo(e,n);if(o||a)throw new Error(s.error||i.error||"URI is malformed.");let l=Hf(s,i,n,!0);return n.skipEscape=!0,lr(l,n)}function Hf(t,e,r,n){let s={};return n||(t=wo(lr(t,r),r),e=wo(lr(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(s.scheme=e.scheme,s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=Ln(e.path||""),s.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=Ln(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=Ln(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?s.path="/"+e.path:t.path?s.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:s.path=e.path,s.path=Ln(s.path)),s.query=e.query):(s.path=t.path,e.query!==void 0?s.query=e.query:s.query=t.query),s.userinfo=t.userinfo,s.host=t.host,s.port=t.port),s.scheme=t.scheme),s.fragment=e.fragment,s}function R$(t,e,r){let n=Bf(t,r),s=Bf(e,r);return n!==void 0&&s!==void 0&&n.toLowerCase()===s.toLowerCase()}function lr(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),s=[],o=Ff(n.scheme||r.scheme);o&&o.serialize&&o.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=b$(r.path):(r.path=v$(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&s.push(r.scheme,":");let i=y$(r);if(i!==void 0&&(n.reference!=="suffix"&&s.push("//"),s.push(i),r.path&&r.path[0]!=="/"&&s.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!o||!o.absolutePath)&&(a=Ln(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),s.push(a)}return r.query!==void 0&&s.push("?",r.query),r.fragment!==void 0&&s.push("#",r.fragment),s.join("")}var E$=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,P$=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,A$=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function I$(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 bo(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},s=!1,o=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let i=t.match(P$);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",s=!0);let a=t.match(A$);if(a!==null){let d=a[1],u=d.replace(/[\t\n\r]/g,"");u.length>=2&&(u.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",s=!0):d.length!==u.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",s=!0))}let l=t.match(E$);if(l){n.scheme=l[1],n.userinfo=l[3],n.host=l[4],n.port=parseInt(l[5],10),n.path=l[6]||"",n.query=l[7],n.fragment=l[8],isNaN(n.port)&&(n.port=l[5]);let d=I$(n,l);if(d!==void 0&&(n.error=n.error||d,s=!0),n.host)if(_$(n.host)===!1){let v=g$(n.host);n.host=v.host.toLowerCase(),o=v.isIPV6}else o=!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=Ff(r.scheme||n.scheme);if(!r.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(r.domainHost||u&&u.domainHost)&&o===!1&&$$(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(h){n.error=n.error||"Host's domain name can not be converted to ASCII: "+h}if((!u||u&&!u.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=S$(unescape(n.host),o))),n.path&&(n.path=w$(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:s}}function wo(t,e){return bo(t,e).parsed}function C$(t,e){return Kf(t,e).normalized}function Kf(t,e){let{parsed:r,malformedAuthorityOrPort:n}=bo(t,e);return{normalized:n?t:lr(r,e),malformedAuthorityOrPort:n}}function Bf(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Kf(t,e);return n?void 0:r}if(typeof t=="object")return lr(t,e)}var Rc={SCHEMES:k$,normalize:x$,resolve:T$,resolveComponent:Hf,equal:R$,serialize:lr,parse:wo};vo.exports=Rc;vo.exports.default=Rc;vo.exports.fastUri=Rc});var Wf=j(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var Gf=Vf();Gf.code='require("ajv/dist/runtime/uri").default';Ec.default=Gf});var rh=j(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.CodeGen=Re.Name=Re.nil=Re.stringify=Re.str=Re._=Re.KeywordCxt=void 0;var O$=jn();Object.defineProperty(Re,"KeywordCxt",{enumerable:!0,get:function(){return O$.KeywordCxt}});var zr=W();Object.defineProperty(Re,"_",{enumerable:!0,get:function(){return zr._}});Object.defineProperty(Re,"str",{enumerable:!0,get:function(){return zr.str}});Object.defineProperty(Re,"stringify",{enumerable:!0,get:function(){return zr.stringify}});Object.defineProperty(Re,"nil",{enumerable:!0,get:function(){return zr.nil}});Object.defineProperty(Re,"Name",{enumerable:!0,get:function(){return zr.Name}});Object.defineProperty(Re,"CodeGen",{enumerable:!0,get:function(){return zr.CodeGen}});var N$=fo(),Xf=zn(),j$=rc(),Un=mo(),z$=W(),Dn=Cn(),So=In(),Ac=se(),Jf=Af(),L$=Wf(),eh=(t,e)=>new RegExp(t,e);eh.code="new RegExp";var U$=["removeAdditional","useDefaults","coerceTypes"],D$=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),q$={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."},M$={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Zf=200;function B$(t){var e,r,n,s,o,i,a,l,d,u,h,v,g,w,$,R,E,A,z,ee,F,Ce,Ue,ft,Vr;let ot=t.strict,Zt=(e=t.code)===null||e===void 0?void 0:e.optimize,fr=Zt===!0||Zt===void 0?1:Zt||0,Gr=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:eh,Wr=(s=t.uriResolver)!==null&&s!==void 0?s:L$.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:ot)!==null&&i!==void 0?i:!0,strictNumbers:(l=(a=t.strictNumbers)!==null&&a!==void 0?a:ot)!==null&&l!==void 0?l:!0,strictTypes:(u=(d=t.strictTypes)!==null&&d!==void 0?d:ot)!==null&&u!==void 0?u:"log",strictTuples:(v=(h=t.strictTuples)!==null&&h!==void 0?h:ot)!==null&&v!==void 0?v:"log",strictRequired:(w=(g=t.strictRequired)!==null&&g!==void 0?g:ot)!==null&&w!==void 0?w:!1,code:t.code?{...t.code,optimize:fr,regExp:Gr}:{optimize:fr,regExp:Gr},loopRequired:($=t.loopRequired)!==null&&$!==void 0?$:Zf,loopEnum:(R=t.loopEnum)!==null&&R!==void 0?R:Zf,meta:(E=t.meta)!==null&&E!==void 0?E:!0,messages:(A=t.messages)!==null&&A!==void 0?A:!0,inlineRefs:(z=t.inlineRefs)!==null&&z!==void 0?z:!0,schemaId:(ee=t.schemaId)!==null&&ee!==void 0?ee:"$id",addUsedSchema:(F=t.addUsedSchema)!==null&&F!==void 0?F:!0,validateSchema:(Ce=t.validateSchema)!==null&&Ce!==void 0?Ce:!0,validateFormats:(Ue=t.validateFormats)!==null&&Ue!==void 0?Ue:!0,unicodeRegExp:(ft=t.unicodeRegExp)!==null&&ft!==void 0?ft:!0,int32range:(Vr=t.int32range)!==null&&Vr!==void 0?Vr:!0,uriResolver:Wr}}var qn=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,...B$(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new z$.ValueScope({scope:{},prefixes:D$,es5:r,lines:n}),this.logger=W$(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,j$.getRules)(),Yf.call(this,q$,e,"NOT SUPPORTED"),Yf.call(this,M$,e,"DEPRECATED","warn"),this._metaOpts=V$.call(this),e.formats&&H$.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&K$.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),F$.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=Jf;n==="id"&&(s={...Jf},s.id=s.$id,delete s.$id),r&&e&&this.addMetaSchema(s,s[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 s=n(r);return"$async"in n||(this.errors=n.errors),s}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 s.call(this,e,r);async function s(u,h){await o.call(this,u.$schema);let v=this._addSchema(u,h);return v.validate||i.call(this,v)}async function o(u){u&&!this.getSchema(u)&&await s.call(this,{$ref:u},!0)}async function i(u){try{return this._compileSchemaEnv(u)}catch(h){if(!(h instanceof Xf.default))throw h;return a.call(this,h),await l.call(this,h.missingSchema),i.call(this,u)}}function a({missingSchema:u,missingRef:h}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${h} cannot be resolved`)}async function l(u){let h=await d.call(this,u);this.refs[u]||await o.call(this,h.$schema),this.refs[u]||this.addSchema(h,u,r)}async function d(u){let h=this._loading[u];if(h)return h;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(e,r,n,s=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,s);return this}let o;if(typeof e=="object"){let{schemaId:i}=this.opts;if(o=e[i],o!==void 0&&typeof o!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Dn.normalizeId)(r||o),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,s,!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 s=this.validate(n,e);if(!s&&r){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return s}getSchema(e){let r;for(;typeof(r=Qf.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new Un.SchemaEnv({schema:{},schemaId:n});if(r=Un.resolveSchema.call(this,s,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=Qf.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,Dn.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(Z$.call(this,n,r),!r)return(0,Ac.eachItem)(n,o=>Pc.call(this,o)),this;Q$.call(this,r);let s={...r,type:(0,So.getJSONTypes)(r.type),schemaType:(0,So.getJSONTypes)(r.schemaType)};return(0,Ac.eachItem)(n,s.type.length===0?o=>Pc.call(this,o,s):o=>s.type.forEach(i=>Pc.call(this,o,s,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 s=n.rules.findIndex(o=>o.keyword===e);s>=0&&n.rules.splice(s,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(s=>`${n}${s.instancePath} ${s.message}`).reduce((s,o)=>s+r+o)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let s of r){let o=s.split("/").slice(1),i=e;for(let a of o)i=i[a];for(let a in n){let l=n[a];if(typeof l!="object")continue;let{$data:d}=l.definition,u=i[a];d&&u&&(i[a]=th(u))}}return e}_removeAllSchemas(e,r){for(let n in e){let s=e[n];(!r||r.test(n))&&(typeof s=="string"?delete e[n]:s&&!s.meta&&(this._cache.delete(s.schema),delete e[n]))}}_addSchema(e,r,n,s=this.opts.validateSchema,o=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 l=this._cache.get(e);if(l!==void 0)return l;n=(0,Dn.normalizeId)(i||n);let d=Dn.getSchemaRefs.call(this,e,n);return l=new Un.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:d}),this._cache.set(l.schema,l),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=l),s&&this.validateSchema(e,!0),l}_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):Un.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{Un.compileSchema.call(this,e)}finally{this.opts=r}}};qn.ValidationError=N$.default;qn.MissingRefError=Xf.default;Re.default=qn;function Yf(t,e,r,n="error"){for(let s in t){let o=s;o in e&&this.logger[n](`${r}: option ${s}. ${t[o]}`)}}function Qf(t){return t=(0,Dn.normalizeId)(t),this.schemas[t]||this.refs[t]}function F$(){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 H$(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function K$(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 V$(){let t={...this.opts};for(let e of U$)delete t[e];return t}var G$={log(){},warn(){},error(){}};function W$(t){if(t===!1)return G$;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 J$=/^[a-z_$][a-z0-9_$:-]*$/i;function Z$(t,e){let{RULES:r}=this;if((0,Ac.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!J$.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 Pc(t,e,r){var n;let s=e?.post;if(r&&s)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,i=s?o.post:o.rules.find(({type:l})=>l===r);if(i||(i={type:r,rules:[]},o.rules.push(i)),o.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,So.getJSONTypes)(e.type),schemaType:(0,So.getJSONTypes)(e.schemaType)}};e.before?Y$.call(this,i,a,e.before):i.rules.push(a),o.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(l=>this.addKeyword(l))}function Y$(t,e,r){let n=t.rules.findIndex(s=>s.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function Q$(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=th(e)),t.validateSchema=this.compile(e,!0))}var X$={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function th(t){return{anyOf:[t,X$]}}});var nh=j(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var ek={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ic.default=ek});var ah=j(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.callRef=dr.getValidate=void 0;var tk=zn(),sh=rt(),He=W(),Lr=Rt(),oh=mo(),_o=se(),rk={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:s,schemaEnv:o,validateName:i,opts:a,self:l}=n,{root:d}=o;if((r==="#"||r==="#/")&&s===d.baseId)return h();let u=oh.resolveRef.call(l,d,s,r);if(u===void 0)throw new tk.default(n.opts.uriResolver,s,r);if(u instanceof oh.SchemaEnv)return v(u);return g(u);function h(){if(o===d)return $o(t,i,o,o.$async);let w=e.scopeValue("root",{ref:d});return $o(t,(0,He._)`${w}.validate`,d,d.$async)}function v(w){let $=ih(t,w);$o(t,$,w,w.$async)}function g(w){let $=e.scopeValue("schema",a.code.source===!0?{ref:w,code:(0,He.stringify)(w)}:{ref:w}),R=e.name("valid"),E=t.subschema({schema:w,dataTypes:[],schemaPath:He.nil,topSchemaRef:$,errSchemaPath:r},R);t.mergeEvaluated(E),t.ok(R)}}};function ih(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,He._)`${r.scopeValue("wrapper",{ref:e})}.validate`}dr.getValidate=ih;function $o(t,e,r,n){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:l}=o,d=l.passContext?Lr.default.this:He.nil;n?u():h();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let w=s.let("valid");s.try(()=>{s.code((0,He._)`await ${(0,sh.callValidateCode)(t,e,d)}`),g(e),i||s.assign(w,!0)},$=>{s.if((0,He._)`!(${$} instanceof ${o.ValidationError})`,()=>s.throw($)),v($),i||s.assign(w,!1)}),t.ok(w)}function h(){t.result((0,sh.callValidateCode)(t,e,d),()=>g(e),()=>v(e))}function v(w){let $=(0,He._)`${w}.errors`;s.assign(Lr.default.vErrors,(0,He._)`${Lr.default.vErrors} === null ? ${$} : ${Lr.default.vErrors}.concat(${$})`),s.assign(Lr.default.errors,(0,He._)`${Lr.default.vErrors}.length`)}function g(w){var $;if(!o.opts.unevaluated)return;let R=($=r?.validate)===null||$===void 0?void 0:$.evaluated;if(o.props!==!0)if(R&&!R.dynamicProps)R.props!==void 0&&(o.props=_o.mergeEvaluated.props(s,R.props,o.props));else{let E=s.var("props",(0,He._)`${w}.evaluated.props`);o.props=_o.mergeEvaluated.props(s,E,o.props,He.Name)}if(o.items!==!0)if(R&&!R.dynamicItems)R.items!==void 0&&(o.items=_o.mergeEvaluated.items(s,R.items,o.items));else{let E=s.var("items",(0,He._)`${w}.evaluated.items`);o.items=_o.mergeEvaluated.items(s,E,o.items,He.Name)}}}dr.callRef=$o;dr.default=rk});var ch=j(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});var nk=nh(),sk=ah(),ok=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",nk.default,sk.default];Cc.default=ok});var lh=j(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});var ko=W(),Gt=ko.operators,xo={maximum:{okStr:"<=",ok:Gt.LTE,fail:Gt.GT},minimum:{okStr:">=",ok:Gt.GTE,fail:Gt.LT},exclusiveMaximum:{okStr:"<",ok:Gt.LT,fail:Gt.GTE},exclusiveMinimum:{okStr:">",ok:Gt.GT,fail:Gt.LTE}},ik={message:({keyword:t,schemaCode:e})=>(0,ko.str)`must be ${xo[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ko._)`{comparison: ${xo[t].okStr}, limit: ${e}}`},ak={keyword:Object.keys(xo),type:"number",schemaType:"number",$data:!0,error:ik,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,ko._)`${r} ${xo[e].fail} ${n} || isNaN(${r})`)}};Oc.default=ak});var dh=j(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var Mn=W(),ck={message:({schemaCode:t})=>(0,Mn.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Mn._)`{multipleOf: ${t}}`},lk={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:ck,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,Mn._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,Mn._)`${i} !== parseInt(${i})`;t.fail$data((0,Mn._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Nc.default=lk});var ph=j(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});function uh(t){let e=t.length,r=0,n=0,s;for(;n<e;)r++,s=t.charCodeAt(n++),s>=55296&&s<=56319&&n<e&&(s=t.charCodeAt(n),(s&64512)===56320&&n++);return r}jc.default=uh;uh.code='require("ajv/dist/runtime/ucs2length").default'});var fh=j(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var ur=W(),dk=se(),uk=ph(),pk={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,ur.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,ur._)`{limit: ${t}}`},fk={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:pk,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,o=e==="maxLength"?ur.operators.GT:ur.operators.LT,i=s.opts.unicode===!1?(0,ur._)`${r}.length`:(0,ur._)`${(0,dk.useFunc)(t.gen,uk.default)}(${r})`;t.fail$data((0,ur._)`${i} ${o} ${n}`)}};zc.default=fk});var hh=j(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});var hk=rt(),mk=se(),Ur=W(),gk={message:({schemaCode:t})=>(0,Ur.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Ur._)`{pattern: ${t}}`},yk={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:gk,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:l}=i.opts.code,d=l.code==="new RegExp"?(0,Ur._)`new RegExp`:(0,mk.useFunc)(e,l),u=e.let("valid");e.try(()=>e.assign(u,(0,Ur._)`${d}(${o}, ${a}).test(${r})`),()=>e.assign(u,!1)),t.fail$data((0,Ur._)`!${u}`)}else{let l=(0,hk.usePattern)(t,s);t.fail$data((0,Ur._)`!${l}.test(${r})`)}}};Lc.default=yk});var mh=j(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});var Bn=W(),bk={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Bn.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Bn._)`{limit: ${t}}`},wk={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:bk,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?Bn.operators.GT:Bn.operators.LT;t.fail$data((0,Bn._)`Object.keys(${r}).length ${s} ${n}`)}};Uc.default=wk});var gh=j(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});var Fn=rt(),Hn=W(),vk=se(),Sk={message:({params:{missingProperty:t}})=>(0,Hn.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Hn._)`{missingProperty: ${t}}`},_k={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Sk,code(t){let{gen:e,schema:r,schemaCode:n,data:s,$data:o,it:i}=t,{opts:a}=i;if(!o&&r.length===0)return;let l=r.length>=a.loopRequired;if(i.allErrors?d():u(),a.strictRequired){let g=t.parentSchema.properties,{definedProperties:w}=t.it;for(let $ of r)if(g?.[$]===void 0&&!w.has($)){let R=i.schemaEnv.baseId+i.errSchemaPath,E=`required property "${$}" is not defined at "${R}" (strictRequired)`;(0,vk.checkStrictMode)(i,E,i.opts.strictRequired)}}function d(){if(l||o)t.block$data(Hn.nil,h);else for(let g of r)(0,Fn.checkReportMissingProp)(t,g)}function u(){let g=e.let("missing");if(l||o){let w=e.let("valid",!0);t.block$data(w,()=>v(g,w)),t.ok(w)}else e.if((0,Fn.checkMissingProp)(t,r,g)),(0,Fn.reportMissingProp)(t,g),e.else()}function h(){e.forOf("prop",n,g=>{t.setParams({missingProperty:g}),e.if((0,Fn.noPropertyInData)(e,s,g,a.ownProperties),()=>t.error())})}function v(g,w){t.setParams({missingProperty:g}),e.forOf(g,n,()=>{e.assign(w,(0,Fn.propertyInData)(e,s,g,a.ownProperties)),e.if((0,Hn.not)(w),()=>{t.error(),e.break()})},Hn.nil)}}};Dc.default=_k});var yh=j(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var Kn=W(),$k={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Kn.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Kn._)`{limit: ${t}}`},kk={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:$k,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?Kn.operators.GT:Kn.operators.LT;t.fail$data((0,Kn._)`${r}.length ${s} ${n}`)}};qc.default=kk});var To=j(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});var bh=dc();bh.code='require("ajv/dist/runtime/equal").default';Mc.default=bh});var wh=j(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});var Bc=In(),Ee=W(),xk=se(),Tk=To(),Rk={message:({params:{i:t,j:e}})=>(0,Ee.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Ee._)`{i: ${t}, j: ${e}}`},Ek={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Rk,code(t){let{gen:e,data:r,$data:n,schema:s,parentSchema:o,schemaCode:i,it:a}=t;if(!n&&!s)return;let l=e.let("valid"),d=o.items?(0,Bc.getSchemaTypes)(o.items):[];t.block$data(l,u,(0,Ee._)`${i} === false`),t.ok(l);function u(){let w=e.let("i",(0,Ee._)`${r}.length`),$=e.let("j");t.setParams({i:w,j:$}),e.assign(l,!0),e.if((0,Ee._)`${w} > 1`,()=>(h()?v:g)(w,$))}function h(){return d.length>0&&!d.some(w=>w==="object"||w==="array")}function v(w,$){let R=e.name("item"),E=(0,Bc.checkDataTypes)(d,R,a.opts.strictNumbers,Bc.DataType.Wrong),A=e.const("indices",(0,Ee._)`{}`);e.for((0,Ee._)`;${w}--;`,()=>{e.let(R,(0,Ee._)`${r}[${w}]`),e.if(E,(0,Ee._)`continue`),d.length>1&&e.if((0,Ee._)`typeof ${R} == "string"`,(0,Ee._)`${R} += "_"`),e.if((0,Ee._)`typeof ${A}[${R}] == "number"`,()=>{e.assign($,(0,Ee._)`${A}[${R}]`),t.error(),e.assign(l,!1).break()}).code((0,Ee._)`${A}[${R}] = ${w}`)})}function g(w,$){let R=(0,xk.useFunc)(e,Tk.default),E=e.name("outer");e.label(E).for((0,Ee._)`;${w}--;`,()=>e.for((0,Ee._)`${$} = ${w}; ${$}--;`,()=>e.if((0,Ee._)`${R}(${r}[${w}], ${r}[${$}])`,()=>{t.error(),e.assign(l,!1).break(E)})))}}};Fc.default=Ek});var vh=j(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});var Hc=W(),Pk=se(),Ak=To(),Ik={message:"must be equal to constant",params:({schemaCode:t})=>(0,Hc._)`{allowedValue: ${t}}`},Ck={keyword:"const",$data:!0,error:Ik,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,Hc._)`!${(0,Pk.useFunc)(e,Ak.default)}(${r}, ${s})`):t.fail((0,Hc._)`${o} !== ${r}`)}};Kc.default=Ck});var Sh=j(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});var Vn=W(),Ok=se(),Nk=To(),jk={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Vn._)`{allowedValues: ${t}}`},zk={keyword:"enum",schemaType:"array",$data:!0,error:jk,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t;if(!n&&s.length===0)throw new Error("enum must have non-empty array");let a=s.length>=i.opts.loopEnum,l,d=()=>l??(l=(0,Ok.useFunc)(e,Nk.default)),u;if(a||n)u=e.let("valid"),t.block$data(u,h);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let g=e.const("vSchema",o);u=(0,Vn.or)(...s.map((w,$)=>v(g,$)))}t.pass(u);function h(){e.assign(u,!1),e.forOf("v",o,g=>e.if((0,Vn._)`${d()}(${r}, ${g})`,()=>e.assign(u,!0).break()))}function v(g,w){let $=s[w];return typeof $=="object"&&$!==null?(0,Vn._)`${d()}(${r}, ${g}[${w}])`:(0,Vn._)`${r} === ${$}`}}};Vc.default=zk});var _h=j(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var Lk=lh(),Uk=dh(),Dk=fh(),qk=hh(),Mk=mh(),Bk=gh(),Fk=yh(),Hk=wh(),Kk=vh(),Vk=Sh(),Gk=[Lk.default,Uk.default,Dk.default,qk.default,Mk.default,Bk.default,Fk.default,Hk.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Kk.default,Vk.default];Gc.default=Gk});var Jc=j(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.validateAdditionalItems=void 0;var pr=W(),Wc=se(),Wk={message:({params:{len:t}})=>(0,pr.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,pr._)`{limit: ${t}}`},Jk={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Wk,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Wc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}$h(t,n)}};function $h(t,e){let{gen:r,schema:n,data:s,keyword:o,it:i}=t;i.items=!0;let a=r.const("len",(0,pr._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,pr._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Wc.alwaysValidSchema)(i,n)){let d=r.var("valid",(0,pr._)`${a} <= ${e.length}`);r.if((0,pr.not)(d),()=>l(d)),t.ok(d)}function l(d){r.forRange("i",e.length,a,u=>{t.subschema({keyword:o,dataProp:u,dataPropType:Wc.Type.Num},d),i.allErrors||r.if((0,pr.not)(d),()=>r.break())})}}Gn.validateAdditionalItems=$h;Gn.default=Jk});var Zc=j(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.validateTuple=void 0;var kh=W(),Ro=se(),Zk=rt(),Yk={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return xh(t,"additionalItems",e);r.items=!0,!(0,Ro.alwaysValidSchema)(r,e)&&t.ok((0,Zk.validateArray)(t))}};function xh(t,e,r=t.schema){let{gen:n,parentSchema:s,data:o,keyword:i,it:a}=t;u(s),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Ro.mergeEvaluated.items(n,r.length,a.items));let l=n.name("valid"),d=n.const("len",(0,kh._)`${o}.length`);r.forEach((h,v)=>{(0,Ro.alwaysValidSchema)(a,h)||(n.if((0,kh._)`${d} > ${v}`,()=>t.subschema({keyword:i,schemaProp:v,dataProp:v},l)),t.ok(l))});function u(h){let{opts:v,errSchemaPath:g}=a,w=r.length,$=w===h.minItems&&(w===h.maxItems||h[e]===!1);if(v.strictTuples&&!$){let R=`"${i}" is ${w}-tuple, but minItems or maxItems/${e} are not specified or different at path "${g}"`;(0,Ro.checkStrictMode)(a,R,v.strictTuples)}}}Wn.validateTuple=xh;Wn.default=Yk});var Th=j(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});var Qk=Zc(),Xk={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,Qk.validateTuple)(t,"items")};Yc.default=Xk});var Eh=j(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});var Rh=W(),ex=se(),tx=rt(),rx=Jc(),nx={message:({params:{len:t}})=>(0,Rh.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Rh._)`{limit: ${t}}`},sx={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:nx,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,ex.alwaysValidSchema)(n,e)&&(s?(0,rx.validateAdditionalItems)(t,s):t.ok((0,tx.validateArray)(t)))}};Qc.default=sx});var Ph=j(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});var st=W(),Eo=se(),ox={message:({params:{min:t,max:e}})=>e===void 0?(0,st.str)`must contain at least ${t} valid item(s)`:(0,st.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,st._)`{minContains: ${t}}`:(0,st._)`{minContains: ${t}, maxContains: ${e}}`},ix={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:ox,code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t,i,a,{minContains:l,maxContains:d}=n;o.opts.next?(i=l===void 0?1:l,a=d):i=1;let u=e.const("len",(0,st._)`${s}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Eo.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Eo.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Eo.alwaysValidSchema)(o,r)){let $=(0,st._)`${u} >= ${i}`;a!==void 0&&($=(0,st._)`${$} && ${u} <= ${a}`),t.pass($);return}o.items=!0;let h=e.name("valid");a===void 0&&i===1?g(h,()=>e.if(h,()=>e.break())):i===0?(e.let(h,!0),a!==void 0&&e.if((0,st._)`${s}.length > 0`,v)):(e.let(h,!1),v()),t.result(h,()=>t.reset());function v(){let $=e.name("_valid"),R=e.let("count",0);g($,()=>e.if($,()=>w(R)))}function g($,R){e.forRange("i",0,u,E=>{t.subschema({keyword:"contains",dataProp:E,dataPropType:Eo.Type.Num,compositeRule:!0},$),R()})}function w($){e.code((0,st._)`${$}++`),a===void 0?e.if((0,st._)`${$} >= ${i}`,()=>e.assign(h,!0).break()):(e.if((0,st._)`${$} > ${a}`,()=>e.assign(h,!1).break()),i===1?e.assign(h,!0):e.if((0,st._)`${$} >= ${i}`,()=>e.assign(h,!0)))}}};Xc.default=ix});var Ch=j(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.validateSchemaDeps=bt.validatePropertyDeps=bt.error=void 0;var el=W(),ax=se(),Jn=rt();bt.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,el.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,el._)`{property: ${t},
|
|
888
888
|
missingProperty: ${n},
|
|
889
889
|
depsCount: ${e},
|
|
890
|
-
deps: ${r}}`};var Gk={keyword:"dependencies",type:"object",schemaType:"object",error:gt.error,code(t){let[e,r]=Wk(t);$h(t,e),kh(t,r)}};function Wk({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let s=Array.isArray(t[n])?e:r;s[n]=t[n]}return[e,r]}function $h(t,e=t.schema){let{gen:r,data:n,it:s}=t;if(Object.keys(e).length===0)return;let o=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let l=(0,Jn.propertyInData)(r,n,i,s.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),s.allErrors?r.if(l,()=>{for(let u of a)(0,Jn.checkReportMissingProp)(t,u)}):(r.if((0,Zc._)`${l} && (${(0,Jn.checkMissingProp)(t,a,o)})`),(0,Jn.reportMissingProp)(t,o),r.else())}}gt.validatePropertyDeps=$h;function kh(t,e=t.schema){let{gen:r,data:n,keyword:s,it:o}=t,i=r.name("valid");for(let a in e)(0,Vk.alwaysValidSchema)(o,e[a])||(r.if((0,Jn.propertyInData)(r,n,a,o.opts.ownProperties),()=>{let l=t.subschema({keyword:s,schemaProp:a},i);t.mergeValidEvaluated(l,i)},()=>r.var(i,!0)),t.ok(i))}gt.validateSchemaDeps=kh;gt.default=Gk});var Rh=j(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});var Th=V(),Jk=re(),Zk={message:"property name must be valid",params:({params:t})=>(0,Th._)`{propertyName: ${t.propertyName}}`},Yk={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Zk,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,Jk.alwaysValidSchema)(s,r))return;let o=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},o),e.if((0,Th.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};Yc.default=Yk});var Xc=j(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});var xo=tt(),dt=V(),Qk=St(),To=re(),Xk={message:"must NOT have additional properties",params:({params:t})=>(0,dt._)`{additionalProperty: ${t.additionalProperty}}`},ex={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Xk,code(t){let{gen:e,schema:r,parentSchema:n,data:s,errsCount:o,it:i}=t;if(!o)throw new Error("ajv implementation error");let{allErrors:a,opts:l}=i;if(i.props=!0,l.removeAdditional!=="all"&&(0,To.alwaysValidSchema)(i,r))return;let u=(0,xo.allSchemaProperties)(n.properties),p=(0,xo.allSchemaProperties)(n.patternProperties);d(),t.ok((0,dt._)`${o} === ${Qk.default.errors}`);function d(){e.forIn("key",s,T=>{!u.length&&!p.length?v(T):e.if(h(T),()=>v(T))})}function h(T){let P;if(u.length>8){let N=(0,To.schemaRefOrVal)(i,n.properties,"properties");P=(0,xo.isOwnProperty)(e,N,T)}else u.length?P=(0,dt.or)(...u.map(N=>(0,dt._)`${T} === ${N}`)):P=dt.nil;return p.length&&(P=(0,dt.or)(P,...p.map(N=>(0,dt._)`${(0,xo.usePattern)(t,N)}.test(${T})`))),(0,dt.not)(P)}function g(T){e.code((0,dt._)`delete ${s}[${T}]`)}function v(T){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){g(T);return}if(r===!1){t.setParams({additionalProperty:T}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,To.alwaysValidSchema)(i,r)){let P=e.name("valid");l.removeAdditional==="failing"?(_(T,P,!1),e.if((0,dt.not)(P),()=>{t.reset(),g(T)})):(_(T,P),a||e.if((0,dt.not)(P),()=>e.break()))}}function _(T,P,N){let D={keyword:"additionalProperties",dataProp:T,dataPropType:To.Type.Str};N===!1&&Object.assign(D,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(D,P)}}};Qc.default=ex});var Ah=j(tl=>{"use strict";Object.defineProperty(tl,"__esModule",{value:!0});var tx=jn(),Eh=tt(),el=re(),Ph=Xc(),rx={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Ph.default.code(new tx.KeywordCxt(o,Ph.default,"additionalProperties"));let i=(0,Eh.allSchemaProperties)(r);for(let d of i)o.definedProperties.add(d);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=el.mergeEvaluated.props(e,(0,el.toHash)(i),o.props));let a=i.filter(d=>!(0,el.alwaysValidSchema)(o,r[d]));if(a.length===0)return;let l=e.name("valid");for(let d of a)u(d)?p(d):(e.if((0,Eh.propertyInData)(e,s,d,o.opts.ownProperties)),p(d),o.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(l);function u(d){return o.opts.useDefaults&&!o.compositeRule&&r[d].default!==void 0}function p(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},l)}}};tl.default=rx});var Nh=j(rl=>{"use strict";Object.defineProperty(rl,"__esModule",{value:!0});var Ih=tt(),Ro=V(),Ch=re(),Oh=re(),nx={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:s,it:o}=t,{opts:i}=o,a=(0,Ih.allSchemaProperties)(r),l=a.filter(_=>(0,Ch.alwaysValidSchema)(o,r[_]));if(a.length===0||l.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&s.properties,p=e.name("valid");o.props!==!0&&!(o.props instanceof Ro.Name)&&(o.props=(0,Oh.evaluatedPropsToName)(e,o.props));let{props:d}=o;h();function h(){for(let _ of a)u&&g(_),o.allErrors?v(_):(e.var(p,!0),v(_),e.if(p))}function g(_){for(let T in u)new RegExp(_).test(T)&&(0,Ch.checkStrictMode)(o,`property ${T} matches pattern ${_} (use allowMatchingProperties)`)}function v(_){e.forIn("key",n,T=>{e.if((0,Ro._)`${(0,Ih.usePattern)(t,_)}.test(${T})`,()=>{let P=l.includes(_);P||t.subschema({keyword:"patternProperties",schemaProp:_,dataProp:T,dataPropType:Oh.Type.Str},p),o.opts.unevaluated&&d!==!0?e.assign((0,Ro._)`${d}[${T}]`,!0):!P&&!o.allErrors&&e.if((0,Ro.not)(p),()=>e.break())})})}}};rl.default=nx});var jh=j(nl=>{"use strict";Object.defineProperty(nl,"__esModule",{value:!0});var sx=re(),ox={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,sx.alwaysValidSchema)(n,r)){t.fail();return}let s=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),t.failResult(s,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};nl.default=ox});var zh=j(sl=>{"use strict";Object.defineProperty(sl,"__esModule",{value:!0});var ix=tt(),ax={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:ix.validateUnion,error:{message:"must match a schema in anyOf"}};sl.default=ax});var Lh=j(ol=>{"use strict";Object.defineProperty(ol,"__esModule",{value:!0});var Eo=V(),cx=re(),lx={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Eo._)`{passingSchemas: ${t.passing}}`},dx={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:lx,code(t){let{gen:e,schema:r,parentSchema:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(s.opts.discriminator&&n.discriminator)return;let o=r,i=e.let("valid",!1),a=e.let("passing",null),l=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){o.forEach((p,d)=>{let h;(0,cx.alwaysValidSchema)(s,p)?e.var(l,!0):h=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},l),d>0&&e.if((0,Eo._)`${l} && ${i}`).assign(i,!1).assign(a,(0,Eo._)`[${a}, ${d}]`).else(),e.if(l,()=>{e.assign(i,!0),e.assign(a,d),h&&t.mergeEvaluated(h,Eo.Name)})})}}};ol.default=dx});var Dh=j(il=>{"use strict";Object.defineProperty(il,"__esModule",{value:!0});var ux=re(),px={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 s=e.name("valid");r.forEach((o,i)=>{if((0,ux.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};il.default=px});var Uh=j(al=>{"use strict";Object.defineProperty(al,"__esModule",{value:!0});var Po=V(),qh=re(),fx={message:({params:t})=>(0,Po.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Po._)`{failingKeyword: ${t.ifClause}}`},hx={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:fx,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,qh.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=Mh(n,"then"),o=Mh(n,"else");if(!s&&!o)return;let i=e.let("valid",!0),a=e.name("_valid");if(l(),t.reset(),s&&o){let p=e.let("ifClause");t.setParams({ifClause:p}),e.if(a,u("then",p),u("else",p))}else s?e.if(a,u("then")):e.if((0,Po.not)(a),u("else"));t.pass(i,()=>t.error(!0));function l(){let p=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(p)}function u(p,d){return()=>{let h=t.subschema({keyword:p},a);e.assign(i,a),t.mergeValidEvaluated(h,i),d?e.assign(d,(0,Po._)`${p}`):t.setParams({ifClause:p})}}}};function Mh(t,e){let r=t.schema[e];return r!==void 0&&!(0,qh.alwaysValidSchema)(t,r)}al.default=hx});var Bh=j(cl=>{"use strict";Object.defineProperty(cl,"__esModule",{value:!0});var mx=re(),gx={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,mx.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};cl.default=gx});var Fh=j(ll=>{"use strict";Object.defineProperty(ll,"__esModule",{value:!0});var yx=Kc(),bx=wh(),wx=Vc(),vx=_h(),_x=Sh(),Sx=xh(),$x=Rh(),kx=Xc(),xx=Ah(),Tx=Nh(),Rx=jh(),Ex=zh(),Px=Lh(),Ax=Dh(),Ix=Uh(),Cx=Bh();function Ox(t=!1){let e=[Rx.default,Ex.default,Px.default,Ax.default,Ix.default,Cx.default,$x.default,kx.default,Sx.default,xx.default,Tx.default];return t?e.push(bx.default,vx.default):e.push(yx.default,wx.default),e.push(_x.default),e}ll.default=Ox});var Hh=j(dl=>{"use strict";Object.defineProperty(dl,"__esModule",{value:!0});var be=V(),Nx={message:({schemaCode:t})=>(0,be.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,be._)`{format: ${t}}`},jx={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Nx,code(t,e){let{gen:r,data:n,$data:s,schema:o,schemaCode:i,it:a}=t,{opts:l,errSchemaPath:u,schemaEnv:p,self:d}=a;if(!l.validateFormats)return;s?h():g();function h(){let v=r.scopeValue("formats",{ref:d.formats,code:l.code.formats}),_=r.const("fDef",(0,be._)`${v}[${i}]`),T=r.let("fType"),P=r.let("format");r.if((0,be._)`typeof ${_} == "object" && !(${_} instanceof RegExp)`,()=>r.assign(T,(0,be._)`${_}.type || "string"`).assign(P,(0,be._)`${_}.validate`),()=>r.assign(T,(0,be._)`"string"`).assign(P,_)),t.fail$data((0,be.or)(N(),D()));function N(){return l.strictSchema===!1?be.nil:(0,be._)`${i} && !${P}`}function D(){let Q=p.$async?(0,be._)`(${_}.async ? await ${P}(${n}) : ${P}(${n}))`:(0,be._)`${P}(${n})`,B=(0,be._)`(typeof ${P} == "function" ? ${Q} : ${P}.test(${n}))`;return(0,be._)`${P} && ${P} !== true && ${T} === ${e} && !${B}`}}function g(){let v=d.formats[o];if(!v){N();return}if(v===!0)return;let[_,T,P]=D(v);_===e&&t.pass(Q());function N(){if(l.strictSchema===!1){d.logger.warn(B());return}throw new Error(B());function B(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function D(B){let Le=B instanceof RegExp?(0,be.regexpCode)(B):l.code.formats?(0,be._)`${l.code.formats}${(0,be.getProperty)(o)}`:void 0,Ee=r.scopeValue("formats",{key:o,ref:B,code:Le});return typeof B=="object"&&!(B instanceof RegExp)?[B.type||"string",B.validate,(0,be._)`${Ee}.validate`]:["string",B,Ee]}function Q(){if(typeof v=="object"&&!(v instanceof RegExp)&&v.async){if(!p.$async)throw new Error("async format in sync schema");return(0,be._)`await ${P}(${n})`}return typeof T=="function"?(0,be._)`${P}(${n})`:(0,be._)`${P}.test(${n})`}}}};dl.default=jx});var Kh=j(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});var zx=Hh(),Lx=[zx.default];ul.default=Lx});var Vh=j(Dr=>{"use strict";Object.defineProperty(Dr,"__esModule",{value:!0});Dr.contentVocabulary=Dr.metadataVocabulary=void 0;Dr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Dr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Wh=j(pl=>{"use strict";Object.defineProperty(pl,"__esModule",{value:!0});var Dx=th(),Mx=mh(),qx=Fh(),Ux=Kh(),Gh=Vh(),Bx=[Dx.default,Mx.default,(0,qx.default)(),Ux.default,Gh.metadataVocabulary,Gh.contentVocabulary];pl.default=Bx});var Zh=j(Ao=>{"use strict";Object.defineProperty(Ao,"__esModule",{value:!0});Ao.DiscrError=void 0;var Jh;(function(t){t.Tag="tag",t.Mapping="mapping"})(Jh||(Ao.DiscrError=Jh={}))});var Qh=j(hl=>{"use strict";Object.defineProperty(hl,"__esModule",{value:!0});var Mr=V(),fl=Zh(),Yh=fo(),Fx=zn(),Hx=re(),Kx={message:({params:{discrError:t,tagName:e}})=>t===fl.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Mr._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},Vx={keyword:"discriminator",type:"object",schemaType:"object",error:Kx,code(t){let{gen:e,data:r,schema:n,parentSchema:s,it:o}=t,{oneOf:i}=s;if(!o.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 l=e.let("valid",!1),u=e.const("tag",(0,Mr._)`${r}${(0,Mr.getProperty)(a)}`);e.if((0,Mr._)`typeof ${u} == "string"`,()=>p(),()=>t.error(!1,{discrError:fl.DiscrError.Tag,tag:u,tagName:a})),t.ok(l);function p(){let g=h();e.if(!1);for(let v in g)e.elseIf((0,Mr._)`${u} === ${v}`),e.assign(l,d(g[v]));e.else(),t.error(!1,{discrError:fl.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(g){let v=e.name("valid"),_=t.subschema({keyword:"oneOf",schemaProp:g},v);return t.mergeEvaluated(_,Mr.Name),v}function h(){var g;let v={},_=P(s),T=!0;for(let Q=0;Q<i.length;Q++){let B=i[Q];if(B?.$ref&&!(0,Hx.schemaHasRulesButRef)(B,o.self.RULES)){let Ee=B.$ref;if(B=Yh.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,Ee),B instanceof Yh.SchemaEnv&&(B=B.schema),B===void 0)throw new Fx.default(o.opts.uriResolver,o.baseId,Ee)}let Le=(g=B?.properties)===null||g===void 0?void 0:g[a];if(typeof Le!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);T=T&&(_||P(B)),N(Le,Q)}if(!T)throw new Error(`discriminator: "${a}" must be required`);return v;function P({required:Q}){return Array.isArray(Q)&&Q.includes(a)}function N(Q,B){if(Q.const)D(Q.const,B);else if(Q.enum)for(let Le of Q.enum)D(Le,B);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function D(Q,B){if(typeof Q!="string"||Q in v)throw new Error(`discriminator: "${a}" values must be unique strings`);v[Q]=B}}}};hl.default=Vx});var Xh=j((jC,Gx)=>{Gx.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 gl=j((he,ml)=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.MissingRefError=he.ValidationError=he.CodeGen=he.Name=he.nil=he.stringify=he.str=he._=he.KeywordCxt=he.Ajv=void 0;var Wx=Jf(),Jx=Wh(),Zx=Qh(),em=Xh(),Yx=["/properties"],Io="http://json-schema.org/draft-07/schema",qr=class extends Wx.default{_addVocabularies(){super._addVocabularies(),Jx.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Zx.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(em,Yx):em;this.addMetaSchema(e,Io,!1),this.refs["http://json-schema.org/schema"]=Io}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Io)?Io:void 0)}};he.Ajv=qr;ml.exports=he=qr;ml.exports.Ajv=qr;Object.defineProperty(he,"__esModule",{value:!0});he.default=qr;var Qx=jn();Object.defineProperty(he,"KeywordCxt",{enumerable:!0,get:function(){return Qx.KeywordCxt}});var Ur=V();Object.defineProperty(he,"_",{enumerable:!0,get:function(){return Ur._}});Object.defineProperty(he,"str",{enumerable:!0,get:function(){return Ur.str}});Object.defineProperty(he,"stringify",{enumerable:!0,get:function(){return Ur.stringify}});Object.defineProperty(he,"nil",{enumerable:!0,get:function(){return Ur.nil}});Object.defineProperty(he,"Name",{enumerable:!0,get:function(){return Ur.Name}});Object.defineProperty(he,"CodeGen",{enumerable:!0,get:function(){return Ur.CodeGen}});var Xx=uo();Object.defineProperty(he,"ValidationError",{enumerable:!0,get:function(){return Xx.default}});var e0=zn();Object.defineProperty(he,"MissingRefError",{enumerable:!0,get:function(){return e0.default}})});var cm=j(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.formatNames=bt.fastFormats=bt.fullFormats=void 0;function yt(t,e){return{validate:t,compare:e}}bt.fullFormats={date:yt(sm,vl),time:yt(bl(!0),_l),"date-time":yt(tm(!0),im),"iso-time":yt(bl(),om),"iso-date-time":yt(tm(),am),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:i0,"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:f0,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:a0,int32:{type:"number",validate:d0},int64:{type:"number",validate:u0},float:{type:"number",validate:nm},double:{type:"number",validate:nm},password:!0,binary:!0};bt.fastFormats={...bt.fullFormats,date:yt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,vl),time:yt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,_l),"date-time":yt(/^\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,im),"iso-time":yt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,om),"iso-date-time":yt(/^\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,am),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};bt.formatNames=Object.keys(bt.fullFormats);function t0(t){return t%4===0&&(t%100!==0||t%400===0)}var r0=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,n0=[0,31,28,31,30,31,30,31,31,30,31,30,31];function sm(t){let e=r0.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],s=+e[3];return n>=1&&n<=12&&s>=1&&s<=(n===2&&t0(r)?29:n0[n])}function vl(t,e){if(t&&e)return t>e?1:t<e?-1:0}var yl=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function bl(t){return function(r){let n=yl.exec(r);if(!n)return!1;let s=+n[1],o=+n[2],i=+n[3],a=n[4],l=n[5]==="-"?-1:1,u=+(n[6]||0),p=+(n[7]||0);if(u>23||p>59||t&&!a)return!1;if(s<=23&&o<=59&&i<60)return!0;let d=o-p*l,h=s-u*l-(d<0?1:0);return(h===23||h===-1)&&(d===59||d===-1)&&i<61}}function _l(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 om(t,e){if(!(t&&e))return;let r=yl.exec(t),n=yl.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 wl=/t|\s/i;function tm(t){let e=bl(t);return function(n){let s=n.split(wl);return s.length===2&&sm(s[0])&&e(s[1])}}function im(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function am(t,e){if(!(t&&e))return;let[r,n]=t.split(wl),[s,o]=e.split(wl),i=vl(r,s);if(i!==void 0)return i||_l(n,o)}var s0=/\/|:/,o0=/^(?:[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 i0(t){return s0.test(t)&&o0.test(t)}var rm=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function a0(t){return rm.lastIndex=0,rm.test(t)}var c0=-(2**31),l0=2**31-1;function d0(t){return Number.isInteger(t)&&t<=l0&&t>=c0}function u0(t){return Number.isInteger(t)}function nm(){return!0}var p0=/[^\\]\\Z/;function f0(t){if(p0.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var lm=j(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});Br.formatLimitDefinition=void 0;var h0=gl(),ut=V(),Ft=ut.operators,Co={formatMaximum:{okStr:"<=",ok:Ft.LTE,fail:Ft.GT},formatMinimum:{okStr:">=",ok:Ft.GTE,fail:Ft.LT},formatExclusiveMaximum:{okStr:"<",ok:Ft.LT,fail:Ft.GTE},formatExclusiveMinimum:{okStr:">",ok:Ft.GT,fail:Ft.LTE}},m0={message:({keyword:t,schemaCode:e})=>(0,ut.str)`should be ${Co[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ut._)`{comparison: ${Co[t].okStr}, limit: ${e}}`};Br.formatLimitDefinition={keyword:Object.keys(Co),type:"string",schemaType:"string",$data:!0,error:m0,code(t){let{gen:e,data:r,schemaCode:n,keyword:s,it:o}=t,{opts:i,self:a}=o;if(!i.validateFormats)return;let l=new h0.KeywordCxt(o,a.RULES.all.format.definition,"format");l.$data?u():p();function u(){let h=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),g=e.const("fmt",(0,ut._)`${h}[${l.schemaCode}]`);t.fail$data((0,ut.or)((0,ut._)`typeof ${g} != "object"`,(0,ut._)`${g} instanceof RegExp`,(0,ut._)`typeof ${g}.compare != "function"`,d(g)))}function p(){let h=l.schema,g=a.formats[h];if(!g||g===!0)return;if(typeof g!="object"||g instanceof RegExp||typeof g.compare!="function")throw new Error(`"${s}": format "${h}" does not define "compare" function`);let v=e.scopeValue("formats",{key:h,ref:g,code:i.code.formats?(0,ut._)`${i.code.formats}${(0,ut.getProperty)(h)}`:void 0});t.fail$data(d(v))}function d(h){return(0,ut._)`${h}.compare(${r}, ${n}) ${Co[s].fail} 0`}},dependencies:["format"]};var g0=t=>(t.addKeyword(Br.formatLimitDefinition),t);Br.default=g0});var fm=j((Zn,pm)=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});var Fr=cm(),y0=lm(),Sl=V(),dm=new Sl.Name("fullFormats"),b0=new Sl.Name("fastFormats"),$l=(t,e={keywords:!0})=>{if(Array.isArray(e))return um(t,e,Fr.fullFormats,dm),t;let[r,n]=e.mode==="fast"?[Fr.fastFormats,b0]:[Fr.fullFormats,dm],s=e.formats||Fr.formatNames;return um(t,s,r,n),e.keywords&&(0,y0.default)(t),t};$l.get=(t,e="full")=>{let n=(e==="fast"?Fr.fastFormats:Fr.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function um(t,e,r,n){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,Sl._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}pm.exports=Zn=$l;Object.defineProperty(Zn,"__esModule",{value:!0});Zn.default=$l});function w0(){let t=new hm.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,mm.default)(t),t}var hm,mm,Oo,gm=O(()=>{hm=jl(gl(),1),mm=jl(fm(),1);Oo=class{constructor(e){this._ajv=e??w0()}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 No,ym=O(()=>{xr();No=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 s=e.messages[e.messages.length-1],o=Array.isArray(s.content)?s.content:[s.content],i=o.some(p=>p.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,l=a?Array.isArray(a.content)?a.content:[a.content]:[],u=l.some(p=>p.type==="tool_use");if(i){if(o.some(p=>p.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let p=new Set(l.filter(h=>h.type==="tool_use").map(h=>h.id)),d=new Set(o.filter(h=>h.type==="tool_result").map(h=>h.toolUseId));if(p.size!==d.size||![...p].every(h=>d.has(h)))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},wn,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),s=e.mode??"form";switch(s){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 o=s==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},kr,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 bm(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 wm(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 vm=O(()=>{});var jo,_m=O(()=>{Sp();xr();gm();ln();ym();vm();jo=class extends Ys{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(bn.options.map((n,s)=>[n,s])),this.isMessageIgnored=(n,s)=>{let o=this._loggingLevels.get(s);return o?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Oo,this.setRequestHandler(Li,n=>this._oninitialize(n)),this.setNotificationHandler(Di,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Ki,async(n,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=bn.safeParse(i);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new No(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=_p(this._capabilities,e)}setRequestHandler(e,r){let s=Ct(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o=wr(s);if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let a=async(l,u)=>{let p=It($r,l);if(!p.success){let v=p.error instanceof Error?p.error.message:String(p.error);throw new z(M.InvalidParams,`Invalid tools/call request: ${v}`)}let{params:d}=p.data,h=await Promise.resolve(r(l,u));if(d.task){let v=It(_r,h);if(!v.success){let _=v.error instanceof Error?v.error.message:String(v.error);throw new z(M.InvalidParams,`Invalid task creation result: ${_}`)}return v.data}let g=It(Ms,h);if(!g.success){let v=g.error instanceof Error?g.error.message:String(g.error);throw new z(M.InvalidParams,`Invalid tools/call result: ${v}`)}return g.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){wm(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&bm(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:vu.includes(r)?r:Ci,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"},$s)}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],s=Array.isArray(n.content)?n.content:[n.content],o=s.some(u=>u.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]:[],l=a.some(u=>u.type==="tool_use");if(o){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(a.filter(d=>d.type==="tool_use").map(d=>d.id)),p=new Set(s.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==p.size||![...u].every(d=>p.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Vi,r):this.request({method:"sampling/createMessage",params:e},wn,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 s=e;return this.request({method:"elicitation/create",params:s},kr,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let s=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:s},kr,r);if(o.action==="accept"&&o.content&&s.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!a.valid)throw new z(M.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof z?i:new z(M.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return o}}}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},Gi,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 kl(t){return!!t&&typeof t=="object"&&$m in t}function km(t){return t[$m]?.complete}var $m,Sm,xm=O(()=>{$m=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(Sm||(Sm={}))});var Tm=O(()=>{});function _0(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"),!v0.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,s,o)=>o.indexOf(n)===s);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 S0(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 xl(t){let e=_0(t);return S0(t,e.warnings),e.isValid}var v0,Rm=O(()=>{v0=/^[A-Za-z0-9._-]{1,128}$/});var zo,Em=O(()=>{zo=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let s={taskSupport:"required",...r.execution};if(s.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,s,r._meta,n)}}});import{ZodOptional as $0}from"zod";function Im(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Cm(t){return"_def"in t||"_zod"in t||Im(t)}function Tl(t){return typeof t!="object"||t===null||Cm(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Im)}function Pm(t){if(t){if(Tl(t))return Xt(t);if(!Cm(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function x0(t){let e=Ct(t);return e?Object.entries(e).map(([r,n])=>{let s=bu(n),o=wu(n);return{name:r,description:s,required:!o}}):[]}function Ht(t){let r=Ct(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=wr(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function Am(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Lo,k0,Yn,Om=O(()=>{_m();ln();Aa();xr();xm();Tm();Rm();Em();Lo=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 jo(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new zo(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Ht(Ds)),this.server.assertCanSetRequestHandler(Ht($r)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ds,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let s=br(r.inputSchema);return s?Ra(s,{strictUnions:!0,pipeStrategy:"input"}):k0})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let s=br(r.outputSchema);s&&(n.outputSchema=Ra(s,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler($r,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new z(M.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new z(M.InvalidParams,`Tool ${e.params.name} disabled`);let s=!!e.params.task,o=n.execution?.taskSupport,i="createTask"in n.handler;if((o==="required"||o==="optional")&&!i)throw new z(M.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!s)throw new z(M.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!s&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),l=await this.executeToolHandler(n,a,r);return s||await this.validateToolOutput(n,l,e.params.name),l}catch(n){if(n instanceof z&&n.code===M.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 o=br(e.inputSchema)??e.inputSchema,i=await bs(o,r);if(!i.success){let a="error"in i?i.error:"Unknown error",l=ws(a);throw new z(M.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${l}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new z(M.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let s=br(e.outputSchema),o=await bs(s,r.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",a=ws(i);throw new z(M.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let s=e.handler;if("createTask"in s){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=s;return await Promise.resolve(a.createTask(r,i))}else{let a=s;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=s;return await Promise.resolve(i(r,n))}else{let i=s;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 s=await this.validateToolInput(e,r.params.arguments,r.params.name),o=e.handler,i={...n,taskStore:n.taskStore},a=s?await Promise.resolve(o.createTask(s,i)):await Promise.resolve(o.createTask(i)),l=a.task.taskId,u=a.task,p=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(h=>setTimeout(h,p));let d=await n.taskStore.getTask(l);if(!d)throw new z(M.InternalError,`Task ${l} not found during polling`);u=d}return await n.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Ht(qs)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(qs,async e=>{switch(e.params.ref.type){case"ref/prompt":return zu(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Lu(e),this.handleResourceCompletion(e,e.params.ref);default:throw new z(M.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new z(M.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new z(M.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Yn;let o=Ct(n.argsSchema)?.[e.params.argument.name];if(!kl(o))return Yn;let i=km(o);if(!i)return Yn;let a=await i(e.params.argument.value,e.params.context);return Am(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 Yn;throw new z(M.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=n.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return Yn;let o=await s(e.params.argument.value,e.params.context);return Am(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Ht(Os)),this.server.assertCanSetRequestHandler(Ht(Ns)),this.server.assertCanSetRequestHandler(Ht(js)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Os,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([o,i])=>i.enabled).map(([o,i])=>({uri:o,name:i.name,...i.metadata})),s=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let i=await o.resourceTemplate.listCallback(r);for(let a of i.resources)s.push({...o.metadata,...a})}return{resources:[...n,...s]}}),this.server.setRequestHandler(Ns,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(js,async(e,r)=>{let n=new URL(e.params.uri),s=this._registeredResources[n.toString()];if(s){if(!s.enabled)throw new z(M.InvalidParams,`Resource ${n} disabled`);return s.readCallback(n,r)}for(let o of Object.values(this._registeredResourceTemplates)){let i=o.resourceTemplate.uriTemplate.match(n.toString());if(i)return o.readCallback(n,i,r)}throw new z(M.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Ht(zs)),this.server.assertCanSetRequestHandler(Ht(Ls)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(zs,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?x0(r.argsSchema):void 0}))})),this.server.setRequestHandler(Ls,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new z(M.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new z(M.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let s=br(n.argsSchema),o=await bs(s,e.params.arguments);if(!o.success){let l="error"in o?o.error:"Unknown error",u=ws(l);throw new z(M.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=o.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let s=n.callback;return await Promise.resolve(s(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let s;typeof n[0]=="object"&&(s=n.shift());let o=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,s,o);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,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,s){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let o=this._createRegisteredResource(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,r,n,s,o){let i={name:e,title:r,metadata:s,readCallback:o,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,s,o){let i={resourceTemplate:n,title:r,metadata:s,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,s,o){let i={title:r,description:n,argsSchema:s===void 0?void 0:Xt(s),callback:o,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=Xt(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,s&&Object.values(s).some(l=>{let u=l instanceof $0?l._def?.innerType:l;return kl(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,s,o,i,a,l,u){xl(e);let p={title:r,description:n,inputSchema:Pm(s),outputSchema:Pm(o),annotations:i,execution:a,_meta:l,handler:u,enabled:!0,disable:()=>p.update({enabled:!1}),enable:()=>p.update({enabled:!0}),remove:()=>p.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&xl(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=p)),typeof d.title<"u"&&(p.title=d.title),typeof d.description<"u"&&(p.description=d.description),typeof d.paramsSchema<"u"&&(p.inputSchema=Xt(d.paramsSchema)),typeof d.outputSchema<"u"&&(p.outputSchema=Xt(d.outputSchema)),typeof d.callback<"u"&&(p.handler=d.callback),typeof d.annotations<"u"&&(p.annotations=d.annotations),typeof d._meta<"u"&&(p._meta=d._meta),typeof d.enabled<"u"&&(p.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=p,this.setToolRequestHandlers(),this.sendToolListChanged(),p}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,s,o,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let l=r[0];if(Tl(l))s=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Tl(r[0])&&(i=r.shift());else if(typeof l=="object"&&l!==null){if(Object.values(l).some(u=>typeof u=="object"&&u!==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,s,o,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:s,description:o,inputSchema:i,outputSchema:a,annotations:l,_meta:u}=r;return this._createRegisteredTool(e,s,o,i,a,l,{taskSupport:"forbidden"},u,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 s;r.length>1&&(s=r.shift());let o=r[0],i=this._createRegisteredPrompt(e,void 0,n,s,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:s,description:o,argsSchema:i}=r,a=this._createRegisteredPrompt(e,s,o,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()}},k0={type:"object",properties:{}};Yn={completion:{values:[],hasMore:!1}}});function R0(t){return Eu.parse(JSON.parse(t))}function Nm(t){return JSON.stringify(t)+`
|
|
891
|
-
`}var
|
|
892
|
-
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),
|
|
890
|
+
deps: ${r}}`};var cx={keyword:"dependencies",type:"object",schemaType:"object",error:bt.error,code(t){let[e,r]=lx(t);Ah(t,e),Ih(t,r)}};function lx({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let s=Array.isArray(t[n])?e:r;s[n]=t[n]}return[e,r]}function Ah(t,e=t.schema){let{gen:r,data:n,it:s}=t;if(Object.keys(e).length===0)return;let o=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let l=(0,Jn.propertyInData)(r,n,i,s.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),s.allErrors?r.if(l,()=>{for(let d of a)(0,Jn.checkReportMissingProp)(t,d)}):(r.if((0,el._)`${l} && (${(0,Jn.checkMissingProp)(t,a,o)})`),(0,Jn.reportMissingProp)(t,o),r.else())}}bt.validatePropertyDeps=Ah;function Ih(t,e=t.schema){let{gen:r,data:n,keyword:s,it:o}=t,i=r.name("valid");for(let a in e)(0,ax.alwaysValidSchema)(o,e[a])||(r.if((0,Jn.propertyInData)(r,n,a,o.opts.ownProperties),()=>{let l=t.subschema({keyword:s,schemaProp:a},i);t.mergeValidEvaluated(l,i)},()=>r.var(i,!0)),t.ok(i))}bt.validateSchemaDeps=Ih;bt.default=cx});var Nh=j(tl=>{"use strict";Object.defineProperty(tl,"__esModule",{value:!0});var Oh=W(),dx=se(),ux={message:"property name must be valid",params:({params:t})=>(0,Oh._)`{propertyName: ${t.propertyName}}`},px={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:ux,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,dx.alwaysValidSchema)(s,r))return;let o=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},o),e.if((0,Oh.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};tl.default=px});var nl=j(rl=>{"use strict";Object.defineProperty(rl,"__esModule",{value:!0});var Po=rt(),ut=W(),fx=Rt(),Ao=se(),hx={message:"must NOT have additional properties",params:({params:t})=>(0,ut._)`{additionalProperty: ${t.additionalProperty}}`},mx={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:hx,code(t){let{gen:e,schema:r,parentSchema:n,data:s,errsCount:o,it:i}=t;if(!o)throw new Error("ajv implementation error");let{allErrors:a,opts:l}=i;if(i.props=!0,l.removeAdditional!=="all"&&(0,Ao.alwaysValidSchema)(i,r))return;let d=(0,Po.allSchemaProperties)(n.properties),u=(0,Po.allSchemaProperties)(n.patternProperties);h(),t.ok((0,ut._)`${o} === ${fx.default.errors}`);function h(){e.forIn("key",s,R=>{!d.length&&!u.length?w(R):e.if(v(R),()=>w(R))})}function v(R){let E;if(d.length>8){let A=(0,Ao.schemaRefOrVal)(i,n.properties,"properties");E=(0,Po.isOwnProperty)(e,A,R)}else d.length?E=(0,ut.or)(...d.map(A=>(0,ut._)`${R} === ${A}`)):E=ut.nil;return u.length&&(E=(0,ut.or)(E,...u.map(A=>(0,ut._)`${(0,Po.usePattern)(t,A)}.test(${R})`))),(0,ut.not)(E)}function g(R){e.code((0,ut._)`delete ${s}[${R}]`)}function w(R){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){g(R);return}if(r===!1){t.setParams({additionalProperty:R}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Ao.alwaysValidSchema)(i,r)){let E=e.name("valid");l.removeAdditional==="failing"?($(R,E,!1),e.if((0,ut.not)(E),()=>{t.reset(),g(R)})):($(R,E),a||e.if((0,ut.not)(E),()=>e.break()))}}function $(R,E,A){let z={keyword:"additionalProperties",dataProp:R,dataPropType:Ao.Type.Str};A===!1&&Object.assign(z,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(z,E)}}};rl.default=mx});var Lh=j(ol=>{"use strict";Object.defineProperty(ol,"__esModule",{value:!0});var gx=jn(),jh=rt(),sl=se(),zh=nl(),yx={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&zh.default.code(new gx.KeywordCxt(o,zh.default,"additionalProperties"));let i=(0,jh.allSchemaProperties)(r);for(let h of i)o.definedProperties.add(h);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=sl.mergeEvaluated.props(e,(0,sl.toHash)(i),o.props));let a=i.filter(h=>!(0,sl.alwaysValidSchema)(o,r[h]));if(a.length===0)return;let l=e.name("valid");for(let h of a)d(h)?u(h):(e.if((0,jh.propertyInData)(e,s,h,o.opts.ownProperties)),u(h),o.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(h),t.ok(l);function d(h){return o.opts.useDefaults&&!o.compositeRule&&r[h].default!==void 0}function u(h){t.subschema({keyword:"properties",schemaProp:h,dataProp:h},l)}}};ol.default=yx});var Mh=j(il=>{"use strict";Object.defineProperty(il,"__esModule",{value:!0});var Uh=rt(),Io=W(),Dh=se(),qh=se(),bx={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:s,it:o}=t,{opts:i}=o,a=(0,Uh.allSchemaProperties)(r),l=a.filter($=>(0,Dh.alwaysValidSchema)(o,r[$]));if(a.length===0||l.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let d=i.strictSchema&&!i.allowMatchingProperties&&s.properties,u=e.name("valid");o.props!==!0&&!(o.props instanceof Io.Name)&&(o.props=(0,qh.evaluatedPropsToName)(e,o.props));let{props:h}=o;v();function v(){for(let $ of a)d&&g($),o.allErrors?w($):(e.var(u,!0),w($),e.if(u))}function g($){for(let R in d)new RegExp($).test(R)&&(0,Dh.checkStrictMode)(o,`property ${R} matches pattern ${$} (use allowMatchingProperties)`)}function w($){e.forIn("key",n,R=>{e.if((0,Io._)`${(0,Uh.usePattern)(t,$)}.test(${R})`,()=>{let E=l.includes($);E||t.subschema({keyword:"patternProperties",schemaProp:$,dataProp:R,dataPropType:qh.Type.Str},u),o.opts.unevaluated&&h!==!0?e.assign((0,Io._)`${h}[${R}]`,!0):!E&&!o.allErrors&&e.if((0,Io.not)(u),()=>e.break())})})}}};il.default=bx});var Bh=j(al=>{"use strict";Object.defineProperty(al,"__esModule",{value:!0});var wx=se(),vx={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,wx.alwaysValidSchema)(n,r)){t.fail();return}let s=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),t.failResult(s,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};al.default=vx});var Fh=j(cl=>{"use strict";Object.defineProperty(cl,"__esModule",{value:!0});var Sx=rt(),_x={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Sx.validateUnion,error:{message:"must match a schema in anyOf"}};cl.default=_x});var Hh=j(ll=>{"use strict";Object.defineProperty(ll,"__esModule",{value:!0});var Co=W(),$x=se(),kx={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Co._)`{passingSchemas: ${t.passing}}`},xx={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:kx,code(t){let{gen:e,schema:r,parentSchema:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(s.opts.discriminator&&n.discriminator)return;let o=r,i=e.let("valid",!1),a=e.let("passing",null),l=e.name("_valid");t.setParams({passing:a}),e.block(d),t.result(i,()=>t.reset(),()=>t.error(!0));function d(){o.forEach((u,h)=>{let v;(0,$x.alwaysValidSchema)(s,u)?e.var(l,!0):v=t.subschema({keyword:"oneOf",schemaProp:h,compositeRule:!0},l),h>0&&e.if((0,Co._)`${l} && ${i}`).assign(i,!1).assign(a,(0,Co._)`[${a}, ${h}]`).else(),e.if(l,()=>{e.assign(i,!0),e.assign(a,h),v&&t.mergeEvaluated(v,Co.Name)})})}}};ll.default=xx});var Kh=j(dl=>{"use strict";Object.defineProperty(dl,"__esModule",{value:!0});var Tx=se(),Rx={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 s=e.name("valid");r.forEach((o,i)=>{if((0,Tx.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};dl.default=Rx});var Wh=j(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});var Oo=W(),Gh=se(),Ex={message:({params:t})=>(0,Oo.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Oo._)`{failingKeyword: ${t.ifClause}}`},Px={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Ex,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Gh.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=Vh(n,"then"),o=Vh(n,"else");if(!s&&!o)return;let i=e.let("valid",!0),a=e.name("_valid");if(l(),t.reset(),s&&o){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,d("then",u),d("else",u))}else s?e.if(a,d("then")):e.if((0,Oo.not)(a),d("else"));t.pass(i,()=>t.error(!0));function l(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function d(u,h){return()=>{let v=t.subschema({keyword:u},a);e.assign(i,a),t.mergeValidEvaluated(v,i),h?e.assign(h,(0,Oo._)`${u}`):t.setParams({ifClause:u})}}}};function Vh(t,e){let r=t.schema[e];return r!==void 0&&!(0,Gh.alwaysValidSchema)(t,r)}ul.default=Px});var Jh=j(pl=>{"use strict";Object.defineProperty(pl,"__esModule",{value:!0});var Ax=se(),Ix={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,Ax.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};pl.default=Ix});var Zh=j(fl=>{"use strict";Object.defineProperty(fl,"__esModule",{value:!0});var Cx=Jc(),Ox=Th(),Nx=Zc(),jx=Eh(),zx=Ph(),Lx=Ch(),Ux=Nh(),Dx=nl(),qx=Lh(),Mx=Mh(),Bx=Bh(),Fx=Fh(),Hx=Hh(),Kx=Kh(),Vx=Wh(),Gx=Jh();function Wx(t=!1){let e=[Bx.default,Fx.default,Hx.default,Kx.default,Vx.default,Gx.default,Ux.default,Dx.default,Lx.default,qx.default,Mx.default];return t?e.push(Ox.default,jx.default):e.push(Cx.default,Nx.default),e.push(zx.default),e}fl.default=Wx});var Yh=j(hl=>{"use strict";Object.defineProperty(hl,"__esModule",{value:!0});var we=W(),Jx={message:({schemaCode:t})=>(0,we.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,we._)`{format: ${t}}`},Zx={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Jx,code(t,e){let{gen:r,data:n,$data:s,schema:o,schemaCode:i,it:a}=t,{opts:l,errSchemaPath:d,schemaEnv:u,self:h}=a;if(!l.validateFormats)return;s?v():g();function v(){let w=r.scopeValue("formats",{ref:h.formats,code:l.code.formats}),$=r.const("fDef",(0,we._)`${w}[${i}]`),R=r.let("fType"),E=r.let("format");r.if((0,we._)`typeof ${$} == "object" && !(${$} instanceof RegExp)`,()=>r.assign(R,(0,we._)`${$}.type || "string"`).assign(E,(0,we._)`${$}.validate`),()=>r.assign(R,(0,we._)`"string"`).assign(E,$)),t.fail$data((0,we.or)(A(),z()));function A(){return l.strictSchema===!1?we.nil:(0,we._)`${i} && !${E}`}function z(){let ee=u.$async?(0,we._)`(${$}.async ? await ${E}(${n}) : ${E}(${n}))`:(0,we._)`${E}(${n})`,F=(0,we._)`(typeof ${E} == "function" ? ${ee} : ${E}.test(${n}))`;return(0,we._)`${E} && ${E} !== true && ${R} === ${e} && !${F}`}}function g(){let w=h.formats[o];if(!w){A();return}if(w===!0)return;let[$,R,E]=z(w);$===e&&t.pass(ee());function A(){if(l.strictSchema===!1){h.logger.warn(F());return}throw new Error(F());function F(){return`unknown format "${o}" ignored in schema at path "${d}"`}}function z(F){let Ce=F instanceof RegExp?(0,we.regexpCode)(F):l.code.formats?(0,we._)`${l.code.formats}${(0,we.getProperty)(o)}`:void 0,Ue=r.scopeValue("formats",{key:o,ref:F,code:Ce});return typeof F=="object"&&!(F instanceof RegExp)?[F.type||"string",F.validate,(0,we._)`${Ue}.validate`]:["string",F,Ue]}function ee(){if(typeof w=="object"&&!(w instanceof RegExp)&&w.async){if(!u.$async)throw new Error("async format in sync schema");return(0,we._)`await ${E}(${n})`}return typeof R=="function"?(0,we._)`${E}(${n})`:(0,we._)`${E}.test(${n})`}}}};hl.default=Zx});var Qh=j(ml=>{"use strict";Object.defineProperty(ml,"__esModule",{value:!0});var Yx=Yh(),Qx=[Yx.default];ml.default=Qx});var Xh=j(Dr=>{"use strict";Object.defineProperty(Dr,"__esModule",{value:!0});Dr.contentVocabulary=Dr.metadataVocabulary=void 0;Dr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Dr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var tm=j(gl=>{"use strict";Object.defineProperty(gl,"__esModule",{value:!0});var Xx=ch(),eT=_h(),tT=Zh(),rT=Qh(),em=Xh(),nT=[Xx.default,eT.default,(0,tT.default)(),rT.default,em.metadataVocabulary,em.contentVocabulary];gl.default=nT});var nm=j(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});No.DiscrError=void 0;var rm;(function(t){t.Tag="tag",t.Mapping="mapping"})(rm||(No.DiscrError=rm={}))});var om=j(bl=>{"use strict";Object.defineProperty(bl,"__esModule",{value:!0});var qr=W(),yl=nm(),sm=mo(),sT=zn(),oT=se(),iT={message:({params:{discrError:t,tagName:e}})=>t===yl.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,qr._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},aT={keyword:"discriminator",type:"object",schemaType:"object",error:iT,code(t){let{gen:e,data:r,schema:n,parentSchema:s,it:o}=t,{oneOf:i}=s;if(!o.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 l=e.let("valid",!1),d=e.const("tag",(0,qr._)`${r}${(0,qr.getProperty)(a)}`);e.if((0,qr._)`typeof ${d} == "string"`,()=>u(),()=>t.error(!1,{discrError:yl.DiscrError.Tag,tag:d,tagName:a})),t.ok(l);function u(){let g=v();e.if(!1);for(let w in g)e.elseIf((0,qr._)`${d} === ${w}`),e.assign(l,h(g[w]));e.else(),t.error(!1,{discrError:yl.DiscrError.Mapping,tag:d,tagName:a}),e.endIf()}function h(g){let w=e.name("valid"),$=t.subschema({keyword:"oneOf",schemaProp:g},w);return t.mergeEvaluated($,qr.Name),w}function v(){var g;let w={},$=E(s),R=!0;for(let ee=0;ee<i.length;ee++){let F=i[ee];if(F?.$ref&&!(0,oT.schemaHasRulesButRef)(F,o.self.RULES)){let Ue=F.$ref;if(F=sm.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,Ue),F instanceof sm.SchemaEnv&&(F=F.schema),F===void 0)throw new sT.default(o.opts.uriResolver,o.baseId,Ue)}let Ce=(g=F?.properties)===null||g===void 0?void 0:g[a];if(typeof Ce!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);R=R&&($||E(F)),A(Ce,ee)}if(!R)throw new Error(`discriminator: "${a}" must be required`);return w;function E({required:ee}){return Array.isArray(ee)&&ee.includes(a)}function A(ee,F){if(ee.const)z(ee.const,F);else if(ee.enum)for(let Ce of ee.enum)z(Ce,F);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function z(ee,F){if(typeof ee!="string"||ee in w)throw new Error(`discriminator: "${a}" values must be unique strings`);w[ee]=F}}}};bl.default=aT});var im=j((tO,cT)=>{cT.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 vl=j((ge,wl)=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.MissingRefError=ge.ValidationError=ge.CodeGen=ge.Name=ge.nil=ge.stringify=ge.str=ge._=ge.KeywordCxt=ge.Ajv=void 0;var lT=rh(),dT=tm(),uT=om(),am=im(),pT=["/properties"],jo="http://json-schema.org/draft-07/schema",Mr=class extends lT.default{_addVocabularies(){super._addVocabularies(),dT.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(uT.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(am,pT):am;this.addMetaSchema(e,jo,!1),this.refs["http://json-schema.org/schema"]=jo}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(jo)?jo:void 0)}};ge.Ajv=Mr;wl.exports=ge=Mr;wl.exports.Ajv=Mr;Object.defineProperty(ge,"__esModule",{value:!0});ge.default=Mr;var fT=jn();Object.defineProperty(ge,"KeywordCxt",{enumerable:!0,get:function(){return fT.KeywordCxt}});var Br=W();Object.defineProperty(ge,"_",{enumerable:!0,get:function(){return Br._}});Object.defineProperty(ge,"str",{enumerable:!0,get:function(){return Br.str}});Object.defineProperty(ge,"stringify",{enumerable:!0,get:function(){return Br.stringify}});Object.defineProperty(ge,"nil",{enumerable:!0,get:function(){return Br.nil}});Object.defineProperty(ge,"Name",{enumerable:!0,get:function(){return Br.Name}});Object.defineProperty(ge,"CodeGen",{enumerable:!0,get:function(){return Br.CodeGen}});var hT=fo();Object.defineProperty(ge,"ValidationError",{enumerable:!0,get:function(){return hT.default}});var mT=zn();Object.defineProperty(ge,"MissingRefError",{enumerable:!0,get:function(){return mT.default}})});var mm=j(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.formatNames=vt.fastFormats=vt.fullFormats=void 0;function wt(t,e){return{validate:t,compare:e}}vt.fullFormats={date:wt(um,kl),time:wt(_l(!0),xl),"date-time":wt(cm(!0),fm),"iso-time":wt(_l(),pm),"iso-date-time":wt(cm(),hm),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:ST,"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:ET,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:_T,int32:{type:"number",validate:xT},int64:{type:"number",validate:TT},float:{type:"number",validate:dm},double:{type:"number",validate:dm},password:!0,binary:!0};vt.fastFormats={...vt.fullFormats,date:wt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,kl),time:wt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,xl),"date-time":wt(/^\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,fm),"iso-time":wt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,pm),"iso-date-time":wt(/^\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,hm),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};vt.formatNames=Object.keys(vt.fullFormats);function gT(t){return t%4===0&&(t%100!==0||t%400===0)}var yT=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,bT=[0,31,28,31,30,31,30,31,31,30,31,30,31];function um(t){let e=yT.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],s=+e[3];return n>=1&&n<=12&&s>=1&&s<=(n===2&&gT(r)?29:bT[n])}function kl(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Sl=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function _l(t){return function(r){let n=Sl.exec(r);if(!n)return!1;let s=+n[1],o=+n[2],i=+n[3],a=n[4],l=n[5]==="-"?-1:1,d=+(n[6]||0),u=+(n[7]||0);if(d>23||u>59||t&&!a)return!1;if(s<=23&&o<=59&&i<60)return!0;let h=o-u*l,v=s-d*l-(h<0?1:0);return(v===23||v===-1)&&(h===59||h===-1)&&i<61}}function xl(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 pm(t,e){if(!(t&&e))return;let r=Sl.exec(t),n=Sl.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 $l=/t|\s/i;function cm(t){let e=_l(t);return function(n){let s=n.split($l);return s.length===2&&um(s[0])&&e(s[1])}}function fm(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function hm(t,e){if(!(t&&e))return;let[r,n]=t.split($l),[s,o]=e.split($l),i=kl(r,s);if(i!==void 0)return i||xl(n,o)}var wT=/\/|:/,vT=/^(?:[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 ST(t){return wT.test(t)&&vT.test(t)}var lm=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function _T(t){return lm.lastIndex=0,lm.test(t)}var $T=-(2**31),kT=2**31-1;function xT(t){return Number.isInteger(t)&&t<=kT&&t>=$T}function TT(t){return Number.isInteger(t)}function dm(){return!0}var RT=/[^\\]\\Z/;function ET(t){if(RT.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var gm=j(Fr=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});Fr.formatLimitDefinition=void 0;var PT=vl(),pt=W(),Wt=pt.operators,zo={formatMaximum:{okStr:"<=",ok:Wt.LTE,fail:Wt.GT},formatMinimum:{okStr:">=",ok:Wt.GTE,fail:Wt.LT},formatExclusiveMaximum:{okStr:"<",ok:Wt.LT,fail:Wt.GTE},formatExclusiveMinimum:{okStr:">",ok:Wt.GT,fail:Wt.LTE}},AT={message:({keyword:t,schemaCode:e})=>(0,pt.str)`should be ${zo[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,pt._)`{comparison: ${zo[t].okStr}, limit: ${e}}`};Fr.formatLimitDefinition={keyword:Object.keys(zo),type:"string",schemaType:"string",$data:!0,error:AT,code(t){let{gen:e,data:r,schemaCode:n,keyword:s,it:o}=t,{opts:i,self:a}=o;if(!i.validateFormats)return;let l=new PT.KeywordCxt(o,a.RULES.all.format.definition,"format");l.$data?d():u();function d(){let v=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),g=e.const("fmt",(0,pt._)`${v}[${l.schemaCode}]`);t.fail$data((0,pt.or)((0,pt._)`typeof ${g} != "object"`,(0,pt._)`${g} instanceof RegExp`,(0,pt._)`typeof ${g}.compare != "function"`,h(g)))}function u(){let v=l.schema,g=a.formats[v];if(!g||g===!0)return;if(typeof g!="object"||g instanceof RegExp||typeof g.compare!="function")throw new Error(`"${s}": format "${v}" does not define "compare" function`);let w=e.scopeValue("formats",{key:v,ref:g,code:i.code.formats?(0,pt._)`${i.code.formats}${(0,pt.getProperty)(v)}`:void 0});t.fail$data(h(w))}function h(v){return(0,pt._)`${v}.compare(${r}, ${n}) ${zo[s].fail} 0`}},dependencies:["format"]};var IT=t=>(t.addKeyword(Fr.formatLimitDefinition),t);Fr.default=IT});var vm=j((Zn,wm)=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});var Hr=mm(),CT=gm(),Tl=W(),ym=new Tl.Name("fullFormats"),OT=new Tl.Name("fastFormats"),Rl=(t,e={keywords:!0})=>{if(Array.isArray(e))return bm(t,e,Hr.fullFormats,ym),t;let[r,n]=e.mode==="fast"?[Hr.fastFormats,OT]:[Hr.fullFormats,ym],s=e.formats||Hr.formatNames;return bm(t,s,r,n),e.keywords&&(0,CT.default)(t),t};Rl.get=(t,e="full")=>{let n=(e==="fast"?Hr.fastFormats:Hr.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function bm(t,e,r,n){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,Tl._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}wm.exports=Zn=Rl;Object.defineProperty(Zn,"__esModule",{value:!0});Zn.default=Rl});function NT(){let t=new Sm.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,_m.default)(t),t}var Sm,_m,Lo,$m=N(()=>{Sm=Ml(vl(),1),_m=Ml(vm(),1);Lo=class{constructor(e){this._ajv=e??NT()}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 Uo,km=N(()=>{Rr();Uo=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 s=e.messages[e.messages.length-1],o=Array.isArray(s.content)?s.content:[s.content],i=o.some(u=>u.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,l=a?Array.isArray(a.content)?a.content:[a.content]:[],d=l.some(u=>u.type==="tool_use");if(i){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!d)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(d){let u=new Set(l.filter(v=>v.type==="tool_use").map(v=>v.id)),h=new Set(o.filter(v=>v.type==="tool_result").map(v=>v.toolUseId));if(u.size!==h.size||![...u].every(v=>h.has(v)))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},wn,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),s=e.mode??"form";switch(s){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 o=s==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},Tr,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 xm(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 Tm(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 Rm=N(()=>{});var Do,Em=N(()=>{Ap();Rr();$m();ln();km();Rm();Do=class extends Xs{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(bn.options.map((n,s)=>[n,s])),this.isMessageIgnored=(n,s)=>{let o=this._loggingLevels.get(s);return o?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Lo,this.setRequestHandler(Mi,n=>this._oninitialize(n)),this.setNotificationHandler(Bi,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Ji,async(n,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=bn.safeParse(i);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Uo(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Pp(this._capabilities,e)}setRequestHandler(e,r){let s=Lt(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o=Sr(s);if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let a=async(l,d)=>{let u=zt(xr,l);if(!u.success){let w=u.error instanceof Error?u.error.message:String(u.error);throw new L(q.InvalidParams,`Invalid tools/call request: ${w}`)}let{params:h}=u.data,v=await Promise.resolve(r(l,d));if(h.task){let w=zt($r,v);if(!w.success){let $=w.error instanceof Error?w.error.message:String(w.error);throw new L(q.InvalidParams,`Invalid task creation result: ${$}`)}return w.data}let g=zt(Ms,v);if(!g.success){let w=g.error instanceof Error?g.error.message:String(g.error);throw new L(q.InvalidParams,`Invalid tools/call result: ${w}`)}return g.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){Tm(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&xm(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:Eu.includes(r)?r:zi,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"},xs)}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],s=Array.isArray(n.content)?n.content:[n.content],o=s.some(d=>d.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]:[],l=a.some(d=>d.type==="tool_use");if(o){if(s.some(d=>d.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 d=new Set(a.filter(h=>h.type==="tool_use").map(h=>h.id)),u=new Set(s.filter(h=>h.type==="tool_result").map(h=>h.toolUseId));if(d.size!==u.size||![...d].every(h=>u.has(h)))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},Zi,r):this.request({method:"sampling/createMessage",params:e},wn,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 s=e;return this.request({method:"elicitation/create",params:s},Tr,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let s=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:s},Tr,r);if(o.action==="accept"&&o.content&&s.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!a.valid)throw new L(q.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof L?i:new L(q.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return o}}}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},Yi,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 El(t){return!!t&&typeof t=="object"&&Am in t}function Im(t){return t[Am]?.complete}var Am,Pm,Cm=N(()=>{Am=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(Pm||(Pm={}))});var Om=N(()=>{});function zT(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"),!jT.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,s,o)=>o.indexOf(n)===s);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 LT(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 Pl(t){let e=zT(t);return LT(t,e.warnings),e.isValid}var jT,Nm=N(()=>{jT=/^[A-Za-z0-9._-]{1,128}$/});var qo,jm=N(()=>{qo=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let s={taskSupport:"required",...r.execution};if(s.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,s,r._meta,n)}}});import{ZodOptional as UT}from"zod";function Um(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Dm(t){return"_def"in t||"_zod"in t||Um(t)}function Al(t){return typeof t!="object"||t===null||Dm(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Um)}function zm(t){if(t){if(Al(t))return tr(t);if(!Dm(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function qT(t){let e=Lt(t);return e?Object.entries(e).map(([r,n])=>{let s=Tu(n),o=Ru(n);return{name:r,description:s,required:!o}}):[]}function Jt(t){let r=Lt(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Sr(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function Lm(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Mo,DT,Yn,qm=N(()=>{Em();ln();Na();Rr();Cm();Om();Nm();jm();Mo=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 Do(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new qo(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Jt(qs)),this.server.assertCanSetRequestHandler(Jt(xr)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(qs,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let s=vr(r.inputSchema);return s?Ia(s,{strictUnions:!0,pipeStrategy:"input"}):DT})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let s=vr(r.outputSchema);s&&(n.outputSchema=Ia(s,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(xr,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new L(q.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new L(q.InvalidParams,`Tool ${e.params.name} disabled`);let s=!!e.params.task,o=n.execution?.taskSupport,i="createTask"in n.handler;if((o==="required"||o==="optional")&&!i)throw new L(q.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!s)throw new L(q.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!s&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),l=await this.executeToolHandler(n,a,r);return s||await this.validateToolOutput(n,l,e.params.name),l}catch(n){if(n instanceof L&&n.code===q.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let o=vr(e.inputSchema)??e.inputSchema,i=await vs(o,r);if(!i.success){let a="error"in i?i.error:"Unknown error",l=Ss(a);throw new L(q.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${l}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new L(q.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let s=vr(e.outputSchema),o=await vs(s,r.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",a=Ss(i);throw new L(q.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let s=e.handler;if("createTask"in s){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=s;return await Promise.resolve(a.createTask(r,i))}else{let a=s;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=s;return await Promise.resolve(i(r,n))}else{let i=s;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 s=await this.validateToolInput(e,r.params.arguments,r.params.name),o=e.handler,i={...n,taskStore:n.taskStore},a=s?await Promise.resolve(o.createTask(s,i)):await Promise.resolve(o.createTask(i)),l=a.task.taskId,d=a.task,u=d.pollInterval??5e3;for(;d.status!=="completed"&&d.status!=="failed"&&d.status!=="cancelled";){await new Promise(v=>setTimeout(v,u));let h=await n.taskStore.getTask(l);if(!h)throw new L(q.InternalError,`Task ${l} not found during polling`);d=h}return await n.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Jt(Bs)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Bs,async e=>{switch(e.params.ref.type){case"ref/prompt":return Hu(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Ku(e),this.handleResourceCompletion(e,e.params.ref);default:throw new L(q.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new L(q.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new L(q.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Yn;let o=Lt(n.argsSchema)?.[e.params.argument.name];if(!El(o))return Yn;let i=Im(o);if(!i)return Yn;let a=await i(e.params.argument.value,e.params.context);return Lm(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 Yn;throw new L(q.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=n.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return Yn;let o=await s(e.params.argument.value,e.params.context);return Lm(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Jt(js)),this.server.assertCanSetRequestHandler(Jt(zs)),this.server.assertCanSetRequestHandler(Jt(Ls)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(js,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([o,i])=>i.enabled).map(([o,i])=>({uri:o,name:i.name,...i.metadata})),s=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let i=await o.resourceTemplate.listCallback(r);for(let a of i.resources)s.push({...o.metadata,...a})}return{resources:[...n,...s]}}),this.server.setRequestHandler(zs,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Ls,async(e,r)=>{let n=new URL(e.params.uri),s=this._registeredResources[n.toString()];if(s){if(!s.enabled)throw new L(q.InvalidParams,`Resource ${n} disabled`);return s.readCallback(n,r)}for(let o of Object.values(this._registeredResourceTemplates)){let i=o.resourceTemplate.uriTemplate.match(n.toString());if(i)return o.readCallback(n,i,r)}throw new L(q.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Jt(Us)),this.server.assertCanSetRequestHandler(Jt(Ds)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Us,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?qT(r.argsSchema):void 0}))})),this.server.setRequestHandler(Ds,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new L(q.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new L(q.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let s=vr(n.argsSchema),o=await vs(s,e.params.arguments);if(!o.success){let l="error"in o?o.error:"Unknown error",d=Ss(l);throw new L(q.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${d}`)}let i=o.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let s=n.callback;return await Promise.resolve(s(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let s;typeof n[0]=="object"&&(s=n.shift());let o=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,s,o);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,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,s){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let o=this._createRegisteredResource(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,r,n,s,o){let i={name:e,title:r,metadata:s,readCallback:o,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,s,o){let i={resourceTemplate:n,title:r,metadata:s,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(delete this._registeredResourceTemplates[e],d.name&&(this._registeredResourceTemplates[d.name]=i)),typeof d.title<"u"&&(i.title=d.title),typeof d.template<"u"&&(i.resourceTemplate=d.template),typeof d.metadata<"u"&&(i.metadata=d.metadata),typeof d.callback<"u"&&(i.readCallback=d.callback),typeof d.enabled<"u"&&(i.enabled=d.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(d=>!!n.completeCallback(d))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,s,o){let i={title:r,description:n,argsSchema:s===void 0?void 0:tr(s),callback:o,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=tr(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,s&&Object.values(s).some(l=>{let d=l instanceof UT?l._def?.innerType:l;return El(d)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,s,o,i,a,l,d){Pl(e);let u={title:r,description:n,inputSchema:zm(s),outputSchema:zm(o),annotations:i,execution:a,_meta:l,handler:d,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:h=>{typeof h.name<"u"&&h.name!==e&&(typeof h.name=="string"&&Pl(h.name),delete this._registeredTools[e],h.name&&(this._registeredTools[h.name]=u)),typeof h.title<"u"&&(u.title=h.title),typeof h.description<"u"&&(u.description=h.description),typeof h.paramsSchema<"u"&&(u.inputSchema=tr(h.paramsSchema)),typeof h.outputSchema<"u"&&(u.outputSchema=tr(h.outputSchema)),typeof h.callback<"u"&&(u.handler=h.callback),typeof h.annotations<"u"&&(u.annotations=h.annotations),typeof h._meta<"u"&&(u._meta=h._meta),typeof h.enabled<"u"&&(u.enabled=h.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,s,o,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let l=r[0];if(Al(l))s=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Al(r[0])&&(i=r.shift());else if(typeof l=="object"&&l!==null){if(Object.values(l).some(d=>typeof d=="object"&&d!==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,s,o,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:s,description:o,inputSchema:i,outputSchema:a,annotations:l,_meta:d}=r;return this._createRegisteredTool(e,s,o,i,a,l,{taskSupport:"forbidden"},d,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 s;r.length>1&&(s=r.shift());let o=r[0],i=this._createRegisteredPrompt(e,void 0,n,s,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:s,description:o,argsSchema:i}=r,a=this._createRegisteredPrompt(e,s,o,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()}},DT={type:"object",properties:{}};Yn={completion:{values:[],hasMore:!1}}});function BT(t){return zu.parse(JSON.parse(t))}function Mm(t){return JSON.stringify(t)+`
|
|
891
|
+
`}var MT,Bo,Bm=N(()=>{Rr();MT=10*1024*1024,Bo=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??MT}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(`
|
|
892
|
+
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),BT(r)}clear(){this._buffer=void 0}}});import Fm from"node:process";var Fo,Hm=N(()=>{Bm();Fo=class{constructor(e=Fm.stdin,r=Fm.stdout,n){this._stdin=e,this._stdout=r,this._started=!1,this._ondata=s=>{try{this._readBuffer.append(s),this.processReadBuffer()}catch(o){this.onerror?.(o),this.close().catch(()=>{})}},this._onerror=s=>{this.onerror?.(s)},this._readBuffer=new Bo({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=Mm(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var Km,Vm=N(()=>{Km=[]});var tg={};ql(tg,{AUTHORING_MCP_SERVER_NAME:()=>Ym,AUTHORING_MCP_SERVER_VERSION:()=>Qm,AUTHORING_RESOURCES:()=>VT,AUTHORING_TOOLS:()=>KT,AUTHORING_TOOLS_PUBLIC:()=>eg,buildAuthoringMcpServer:()=>Xm,runAuthoringMcpServer:()=>GT});import{promises as FT}from"node:fs";import{resolve as Gm}from"node:path";import{z as D}from"zod";function Zm(){return Jm??=import("../mcp/grounding.js").then(e=>e,()=>null),Jm}function ve(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function HT(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(o=>o.hookId).filter(o=>typeof o=="string"):null}catch{return null}}async function Xm(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let g=await ht(t.baseUrl);if(!g)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:g.baseUrl,token:g.token}}let r=t.grounding??{},n=await Zm(),s=null;if(n)try{let g=await e();s={surface:"mcp-authoring",baseUrl:g.baseUrl,token:g.token}}catch{s=null}let o=n&&s?await n.loadActiveSources(s,r):[],i={...r,loadActiveSourcesImpl:async()=>o},a=[],l=[];if(n&&s){try{a=await n.listMcpPromptSkills(s,i)}catch{a=[]}try{l=(await n.listRecipesForSurface(s,i)).map(g=>({id:g.id,record_type:g.record_type,intent:g.intent}))}catch{l=[]}}let d=s?await HT(s,r):null,u=new Mo({name:Ym,version:Qm},n?{instructions:n.renderAuthoringInstructions({baseUrl:s?.baseUrl??t.baseUrl??"this instance",sources:o,recipeIntents:l,promptNames:a.map(g=>g.id),deployedExtensions:d,docsToken:r.docsToken??n.docsPublicToken()})}:void 0);if(n&&s){let g=s;for(let w of a)u.registerPrompt(w.id,{title:w.name,description:w.description},async()=>{let $=await n.getMcpPromptSkill(g,w.id,r);if(!$)throw new Error(`unknown prompt: ${w.id}`);return{description:$.description,messages:[{role:"user",content:{type:"text",text:($.prompts??[]).join(`
|
|
893
893
|
|
|
894
|
-
`)}}]}})}return p.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:d,token:h}=await e(),g=await fetch(`${d}/v1/catalog/records`,{headers:{Authorization:`Bearer ${h}`,Accept:"application/json"}});if(!g.ok)throw new Error(`catalog fetch failed: ${g.status}`);return $e(await g.json())}),p.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:H.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".')}},async({recordType:d})=>{let{baseUrl:h,token:g}=await e(),v=await fetch(`${h}/v1/catalog/records/${encodeURIComponent(d)}`,{headers:{Authorization:`Bearer ${g}`,Accept:"application/json"}});if(v.status===404)throw new Error(`unknown record type "${d}" \u2014 list them with catalog_get.`);if(!v.ok)throw new Error(`record anatomy fetch failed: ${v.status}`);return $e(await v.json())}),p.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:H.array(H.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].')}},async({recordTypes:d})=>{let{baseUrl:h,token:g}=await e(),v=new URLSearchParams({types:d.join(",")}),_=await fetch(`${h}/v1/catalog/columns?${v}`,{headers:{Authorization:`Bearer ${g}`,Accept:"application/json"}});if(_.status===404)throw new Error(`none of those record types resolved: ${d.join(", ")} \u2014 list them with catalog_get.`);if(!_.ok)throw new Error(`common columns fetch failed: ${_.status}`);return $e(await _.json())}),p.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:d,token:h}=await e(),g=await fetch(`${d}/v1/catalog/census`,{headers:{Authorization:`Bearer ${h}`,Accept:"application/json"}});if(!g.ok)throw new Error(`catalog census failed: ${g.status}`);return $e(await g.json())}),p.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:H.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:H.enum(Um).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:H.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:d,kind:h,limit:g})=>{let{baseUrl:v,token:_}=await e(),T=new URLSearchParams({q:d});h&&T.set("kind",h),g!==void 0&&T.set("limit",String(g));let P=await fetch(`${v}/v1/catalog/objects?${T}`,{headers:{Authorization:`Bearer ${_}`,Accept:"application/json"}});if(!P.ok)throw new Error(`catalog object search failed: ${P.status}`);return $e(await P.json())}),p.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:H.enum(Um),externalId:H.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:d,externalId:h})=>{let{baseUrl:g,token:v}=await e(),_=await fetch(`${g}/v1/catalog/objects/${encodeURIComponent(d)}/${encodeURIComponent(h)}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});if(_.status===404)throw new Error(`unknown object ${d}:${h} \u2014 find it with search_catalog.`);if(!_.ok)throw new Error(`catalog object fetch failed: ${_.status}`);return $e(await _.json())}),p.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:H.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:H.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:d,limit:h})=>{let{baseUrl:g,token:v}=await e(),_=new URLSearchParams({q:d});h!==void 0&&_.set("limit",String(h));let T=await fetch(`${g}/v1/kb/search?${_}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});if(!T.ok)throw new Error(`kb search failed: ${T.status}`);return $e(await T.json())}),p.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:H.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:d})=>{let{baseUrl:h,token:g}=await e(),v=await fetch(`${h}/v1/kb/document/${encodeURIComponent(d)}`,{headers:{Authorization:`Bearer ${g}`,Accept:"application/json"}});if(!v.ok&&v.status!==404)throw new Error(`kb document fetch failed: ${v.status}`);return $e(await v.json())}),p.registerTool("generate_types",{title:"Generate types.ts",description:"Generate the instance's types.ts (record shapes + PostgREST ops). Returns the source.",inputSchema:{recordsOnly:H.boolean().optional()}},async({recordsOnly:d})=>{let{baseUrl:h,token:g}=await e();return{content:[{type:"text",text:await Tt({baseUrl:h,token:g,recordsOnly:d})}]}}),p.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:H.string(),event:H.string().optional(),template:H.enum(["require-field","enforce-format","blank"]).optional(),field:H.string().optional(),regex:H.string().optional(),source:H.string().optional(),id:H.string().optional()}},async d=>{let h=gr("hook",{recordType:d.recordType,event:d.event,template:d.template,field:d.field,regex:d.regex,source:d.source,id:d.id});return $e({path:h.relativePath,content:h.content})}),p.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:H.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:H.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:H.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:H.string().optional().describe("Target record type (defaults to the trigger record type)."),event:H.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:H.string().optional()}},async d=>{let h=gr("conduit",{recordType:d.recordType,source:d.source,to:d.to,toRecordType:d.toRecordType,event:d.event,id:d.id});return $e({path:h.relativePath,content:h.content})}),p.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:H.string().describe("The extension TS source."),samplesDir:H.string().optional().describe('Samples directory (default "samples").')}},async({source:d,samplesDir:h})=>{let g=qm(process.cwd(),h??"samples"),v=await Qr(g),_=await ds(d,v.map(P=>P.fixture)),T=_.filter(P=>!P.pass).length;return $e({total:_.length,passed:_.length-T,results:_})}),p.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:H.string(),recordType:H.string(),event:H.string(),source:H.string().describe('Adapter id or "standalone".'),sourceCode:H.string().describe("The verbatim extension TS."),extensionKind:H.string().optional()}},async d=>{let{baseUrl:h,token:g}=await e(),_=await new ae({baseUrl:h,token:g}).deploy({id:d.id,recordType:d.recordType,event:d.event,source:d.source,sourceCode:d.sourceCode,extensionKind:d.extensionKind});return $e(_)}),p.registerTool("tail_logs",{title:"Tail an extension's logs",description:"Read an extension's log ring buffer (GET /v1/extensions/:id/logs).",inputSchema:{id:H.string(),limit:H.number().int().positive().optional()}},async({id:d,limit:h})=>{let{baseUrl:g,token:v}=await e(),_=new ae({baseUrl:g,token:v});return $e({id:d,logs:await _.logs(d,h)})}),p.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:d,token:h}=await e(),g=new ae({baseUrl:d,token:h});return $e(await g.appsList())}),p.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:H.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:H.string().optional().describe("Display name (defaults to the slug)."),description:H.string().optional().describe("Short description.")}},async({slug:d,name:h,description:g})=>{let{baseUrl:v,token:_}=await e(),T=new ae({baseUrl:v,token:_});return $e(await T.appsCreate({slug:d,name:h,description:g}))}),p.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:H.string().describe("App slug or id.")}},async({app:d})=>{let{baseUrl:h,token:g}=await e(),v=new ae({baseUrl:h,token:g});return $e(await v.appsPull(d))}),p.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:H.string().describe("App slug or id."),files:H.record(H.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:H.string().optional().describe("Short note stored with the revision.")}},async({app:d,files:h,note:g})=>{let{baseUrl:v,token:_}=await e(),T=new ae({baseUrl:v,token:_});return $e(await T.appsPush(d,h,{note:g}))}),p.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async d=>{let{baseUrl:h,token:g}=await e(),_=await(await fetch(`${h}/v1/catalog/records`,{headers:{Authorization:`Bearer ${g}`,Accept:"application/json"}})).text();return{contents:[{uri:d.href,mimeType:"application/json",text:_}]}}),p.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async d=>{let{baseUrl:h,token:g}=await e(),v=await Tt({baseUrl:h,token:g});return{contents:[{uri:d.href,mimeType:"text/plain",text:v}]}}),p.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async d=>{let h=qm(process.cwd(),"samples"),g=[];try{g=(await E0.readdir(h)).filter(_=>_.endsWith(".json"))}catch{g=[]}let v=await Qr(h);return{contents:[{uri:d.href,mimeType:"application/json",text:JSON.stringify({files:g,samples:v.map(_=>_.fixture)},null,2)}]}}),p.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 d=>{let h=await Fm(),g=[];if(h){let{baseUrl:v,token:_}=await e();g=await h.listRecipesForSurface({surface:"mcp-authoring",baseUrl:v,token:_},r)}return{contents:[{uri:d.href,mimeType:"application/json",text:JSON.stringify({recipes:g})}]}}),p}async function C0(t={}){let e=await Vm(t),r=new Mo;await e.connect(r)}var Um,Bm,Hm,Km,Gm,A0,I0,Jm=O(()=>{Om();Lm();Xo();as();Zr();ci();mi();Mm();Um=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];Hm="turbobase-authoring",Km="0.1.0";Gm=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","search_catalog","catalog_census","explain_object","generate_types","scaffold_hook","scaffold_conduit","mock_test","deploy","tail_logs","apps_list","apps_create","apps_pull","apps_push"],A0=[...Gm,...Dm],I0=["catalog:///","types://all","samples:///","recipes:///"]});Xo();as();Zr();ci();import{spawn as Cl}from"node:child_process";import{promises as oe}from"node:fs";import{homedir as O0}from"node:os";import{basename as Ym,dirname as Qn,join as Kt,relative as qo,resolve as ce,sep as Il}from"node:path";import{Command as N0}from"commander";ii();import{promises as sd}from"node:fs";function rd(t,e){return e===t?"same-type-merge":"different-type-mint"}var od=4;function li(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=fr(t,"id"),r=fr(t,"on"),n=fr(t,"source"),s=fr(t,"recordType"),o=/to\s*:\s*\{([^}]*)\}/.exec(t)?.[1]??"",i=fr(o,"source"),a=fr(o,"recordType"),l=/cycleBudget\s*:\s*(\d+)/.exec(t);if(!e||!n||!s||!i||!a)throw new Error("could not parse id/from.{source,recordType}/to.{source,recordType} \u2014 is it a reference-shape defineConduit({...})?");return{id:e,on:r,fromSource:n,fromRecordType:s,toSource:i,toRecordType:a,cycleBudget:l?Number(l[1]):od}}function fr(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function Eg(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 id(t,e,r="fixture"){let n=e.name??r,s=[],o;try{o=li(t)}catch(l){return{fixtureName:n,conduit:Ag(),guards:s,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],logs:[],error:l instanceof Error?l.message:String(l)}}let i=Eg(e),a=Object.entries(e.atlasLinks??{}).map(([l,u])=>({key:l,resolved:u}));try{let l=await ls(t),p=!!(await Yr(l,i,{member:"when",timeoutMs:200})).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 d=e.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${d} vs cycleBudget=${o.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:n,conduit:o,guards:s,whenPassed:p,atlasResolutions:a,wouldWriteBindings:[],logs:[]};let h=await Yr(l,i,{member:"transform",timeoutMs:200}),g=h.effects.logs,v=h.effects.result;if(!v||typeof v!="object")throw new Error(`conduit ${o.id} transform returned no result (expected { patch, createdFrom? })`);let _=v,T=rd(o.fromRecordType,o.toRecordType),{wouldWriteBindings:P,masterAction:N}=Pg(o,T,e);return{fixtureName:n,conduit:o,guards:s,whenPassed:p,atlasResolutions:a,transformResult:_,applyBranch:T,wouldWriteBindings:P,masterAction:N,logs:g}}catch(l){return{fixtureName:n,conduit:o,guards:s,whenPassed:!1,atlasResolutions:a,wouldWriteBindings:[],logs:[],error:l instanceof Error?l.message:String(l)}}}function Pg(t,e,r){return e==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${r.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:r.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:t.toSource,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${t.toRecordType} master (source_system='${t.toSource}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:t.toSource,externalId:null,role:"origin",why:"this conduit CREATED the new master, so the target is its origin; external_id null until writeback mints it"},{source:t.fromSource,externalId:r.externalId,role:"replica",why:"firing source bound onto the created master (supplementary lineage; best-effort, may collide in a 1\u2192N fan)"}]}}function Ag(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",cycleBudget:od}}async function ad(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 cd(t){let e=await sd.readFile(t,"utf8");return JSON.parse(e)}function ld(t){return sd.readFile(t,"utf8")}function dd(t,e){let r=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;if(!e)return t.whenPassed?`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`:`replay ${t.fixtureName} [${r.id}]: WHEN-FAILED (conduit short-circuited)`;let n=[];n.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),n.push(`conduit: ${r.id}`),n.push(`route: ${r.fromSource}.${r.fromRecordType} \u2192 ${r.toSource}.${r.toRecordType}${r.on?` on=${r.on}`:""}`),n.push(""),n.push("guards (dispatch order):");for(let s of t.guards){let o=s.status==="passed"?"\u2713":s.status==="failed"?"\u2717":"\u2298";n.push(` ${o} ${s.name} [${s.status}] \u2014 ${s.detail}`)}if(n.push(""),n.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)n.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let s of t.atlasResolutions)n.push(` ${s.key} \u2192 ${s.resolved===null?"null (no Atlas link \u2014 noted)":s.resolved}`);if(!t.whenPassed)return n.push(""),n.push("transform: SKIPPED (from.when gate did not fire)."),n.join(`
|
|
895
|
-
`);if(n.push(""),n.push("transform \u2192 patch:"),n.push(
|
|
896
|
-
`)}function
|
|
894
|
+
`)}}]}})}u.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:g,token:w}=await e(),$=await fetch(`${g}/v1/catalog/records`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});if(!$.ok)throw new Error(`catalog fetch failed: ${$.status}`);return ve(await $.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:D.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:D.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:g,source:w})=>{let{baseUrl:$,token:R}=await e(),E=w?`?source=${encodeURIComponent(w)}`:"",A=await fetch(`${$}/v1/catalog/records/${encodeURIComponent(g)}${E}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(A.status===404)throw new Error(`unknown record type "${g}" \u2014 list them with catalog_get.`);if(!A.ok)throw new Error(`record anatomy fetch failed: ${A.status}`);return ve(await A.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:D.array(D.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:D.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:g,source:w})=>{let{baseUrl:$,token:R}=await e(),E=new URLSearchParams({types:g.join(",")});w&&E.set("source",w);let A=await fetch(`${$}/v1/catalog/columns?${E}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(A.status===404)throw new Error(`none of those record types resolved: ${g.join(", ")} \u2014 list them with catalog_get.`);if(!A.ok)throw new Error(`common columns fetch failed: ${A.status}`);return ve(await A.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:g,token:w}=await e(),$=await fetch(`${g}/v1/catalog/census`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});if(!$.ok)throw new Error(`catalog census failed: ${$.status}`);return ve(await $.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:D.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:D.enum(Wm).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:D.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:g,kind:w,limit:$})=>{let{baseUrl:R,token:E}=await e(),A=new URLSearchParams({q:g});w&&A.set("kind",w),$!==void 0&&A.set("limit",String($));let z=await fetch(`${R}/v1/catalog/objects?${A}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(!z.ok)throw new Error(`catalog object search failed: ${z.status}`);return ve(await z.json())}),u.registerTool("explain_object",{title:"Explain one catalog object",description:"Fetch ONE customization-catalog object in depth: its captured definition (or script source, or a bundle\u2019s membership), human label, the generated plain-English explanation (tldr + markdown) of what it is for, and its OWNERSHIP \u2014 `modifiability` plus a one-line reason saying whether this account can change it at all. Address it by the {kind, externalId} a search_catalog hit returns. For a FIELD it also reports `selectTarget`: where a List/Record field ACTUALLY points, resolved to a mirrored table plus the filter needed to read it correctly. Do not infer a target from the field name \u2014 a carrier-named field can point at `entity` (vendors), and building on the wrong guess resolves nothing while looking like an empty table.",inputSchema:{kind:D.enum(Wm),externalId:D.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:g,externalId:w})=>{let{baseUrl:$,token:R}=await e(),E=await fetch(`${$}/v1/catalog/objects/${encodeURIComponent(g)}/${encodeURIComponent(w)}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(E.status===404)throw new Error(`unknown object ${g}:${w} \u2014 find it with search_catalog.`);if(!E.ok)throw new Error(`catalog object fetch failed: ${E.status}`);return ve(await E.json())}),u.registerTool("search_documentation",{title:"Search the knowledge base",description:'Search this instance\'s published knowledge base \u2014 internal documentation: processes, policies, playbooks, how-tos. Route questions about how the ORGANISATION works here ("what\'s our receiving process", "how do we handle returns"), and ALWAYS search it before building UI over a custom record \u2014 the KB is the only spec a custom record has. Returns up to `limit` {slug, title, snippet} hits; pass a slug to read_document for the full text. Published release only \u2014 drafts are never returned.',inputSchema:{query:D.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:D.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:g,limit:w})=>{let{baseUrl:$,token:R}=await e(),E=new URLSearchParams({q:g});w!==void 0&&E.set("limit",String(w));let A=await fetch(`${$}/v1/kb/search?${E}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(!A.ok)throw new Error(`kb search failed: ${A.status}`);return ve(await A.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:D.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:g})=>{let{baseUrl:w,token:$}=await e(),R=await fetch(`${w}/v1/kb/document/${encodeURIComponent(g)}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(!R.ok&&R.status!==404)throw new Error(`kb document fetch failed: ${R.status}`);return ve(await R.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:D.boolean().optional()}},async({recordsOnly:g})=>{let{baseUrl:w,token:$}=await e();return{content:[{type:"text",text:await It({baseUrl:w,token:$,recordsOnly:g})}]}}),u.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:D.string(),event:D.string().optional(),template:D.enum(["require-field","enforce-format","blank"]).optional(),field:D.string().optional(),regex:D.string().optional(),source:D.string().optional(),id:D.string().optional()}},async g=>{let w=wr("hook",{recordType:g.recordType,event:g.event,template:g.template,field:g.field,regex:g.regex,source:g.source,id:g.id});return ve({path:w.relativePath,content:w.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:D.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:D.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:D.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:D.string().optional().describe("Target record type (defaults to the trigger record type)."),event:D.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:D.string().optional()}},async g=>{let w=wr("conduit",{recordType:g.recordType,source:g.source,to:g.to,toRecordType:g.toRecordType,event:g.event,id:g.id});return ve({path:w.relativePath,content:w.content})}),u.registerTool("mock_test",{title:"Dry-run an extension against samples",description:"Bundle the given source through the production sandbox and run it against samples/ fixtures.",inputSchema:{source:D.string().describe("The extension TS source."),samplesDir:D.string().optional().describe('Samples directory (default "samples").')}},async({source:g,samplesDir:w})=>{let $=Gm(process.cwd(),w??"samples"),R=await Xr($),E=await ps(g,R.map(z=>z.fixture)),A=E.filter(z=>!z.pass).length;return ve({total:E.length,passed:E.length-A,results:E})}),u.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:D.string(),recordType:D.string(),event:D.string(),source:D.string().describe('Adapter id or "standalone".'),sourceCode:D.string().describe("The verbatim extension TS."),extensionKind:D.string().optional()}},async g=>{let{baseUrl:w,token:$}=await e(),E=await new K({baseUrl:w,token:$}).deploy({id:g.id,recordType:g.recordType,event:g.event,source:g.source,sourceCode:g.sourceCode,extensionKind:g.extensionKind});return ve(E)}),u.registerTool("tail_logs",{title:"Tail an extension's logs",description:"Read an extension's log ring buffer (GET /v1/extensions/:id/logs).",inputSchema:{id:D.string(),limit:D.number().int().positive().optional()}},async({id:g,limit:w})=>{let{baseUrl:$,token:R}=await e(),E=new K({baseUrl:$,token:R});return ve({id:g,logs:await E.logs(g,w)})}),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:g,token:w}=await e(),$=new K({baseUrl:g,token:w});return ve(await $.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:D.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:D.string().optional().describe("Display name (defaults to the slug)."),description:D.string().optional().describe("Short description.")}},async({slug:g,name:w,description:$})=>{let{baseUrl:R,token:E}=await e(),A=new K({baseUrl:R,token:E});return ve(await A.appsCreate({slug:g,name:w,description:$}))}),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:D.string().describe("App slug or id.")}},async({app:g})=>{let{baseUrl:w,token:$}=await e(),R=new K({baseUrl:w,token:$});return ve(await R.appsPull(g))}),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:D.string().describe("App slug or id."),files:D.record(D.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:D.string().optional().describe("Short note stored with the revision.")}},async({app:g,files:w,note:$})=>{let{baseUrl:R,token:E}=await e(),A=new K({baseUrl:R,token:E});return ve(await A.appsPush(g,w,{note:$}))});let h=D.object({name:D.string().describe("Field name (lowercase identifier)."),type:D.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:D.boolean().optional()}),v=D.object({slug:D.string().describe("Table slug; the physical table is cr_<slug>."),displayName:D.string().optional(),fields:D.array(h).describe("At least one field."),rowLevelOwner:D.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:g,token:w}=await e(),$=new K({baseUrl:g,token:w});return ve(await $.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:D.array(v),claimedBy:D.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:g,claimedBy:w})=>{let{baseUrl:$,token:R}=await e(),E=new K({baseUrl:$,token:R});return ve(await E.tablesPlan({tables:g,claimedBy:w}))}),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:D.array(v),claimedBy:D.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:g,claimedBy:w})=>{let{baseUrl:$,token:R}=await e(),E=new K({baseUrl:$,token:R});return ve(await E.tablesApply({tables:g,claimedBy:w}))}),u.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async g=>{let{baseUrl:w,token:$}=await e(),E=await(await fetch(`${w}/v1/catalog/records`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}})).text();return{contents:[{uri:g.href,mimeType:"application/json",text:E}]}}),u.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async g=>{let{baseUrl:w,token:$}=await e(),R=await It({baseUrl:w,token:$});return{contents:[{uri:g.href,mimeType:"text/plain",text:R}]}}),u.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async g=>{let w=Gm(process.cwd(),"samples"),$=[];try{$=(await FT.readdir(w)).filter(E=>E.endsWith(".json"))}catch{$=[]}let R=await Xr(w);return{contents:[{uri:g.href,mimeType:"application/json",text:JSON.stringify({files:$,samples:R.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 g=>{let w=await Zm(),$=[];if(w){let{baseUrl:R,token:E}=await e();$=await w.listRecipesForSurface({surface:"mcp-authoring",baseUrl:R,token:E},r)}return{contents:[{uri:g.href,mimeType:"application/json",text:JSON.stringify({recipes:$})}]}}),u}async function GT(t={}){let e=await Xm(t),r=new Fo;await e.connect(r)}var Wm,Jm,Ym,Qm,eg,KT,VT,rg=N(()=>{qm();Hm();ni();ls();mr();pi();wi();Vm();Wm=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];Ym="turbobase-authoring",Qm="0.1.0";eg=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","search_catalog","catalog_census","explain_object","generate_types","scaffold_hook","scaffold_conduit","mock_test","deploy","tail_logs","apps_list","apps_create","apps_pull","apps_push","tables_list","tables_plan","tables_apply"],KT=[...eg,...Km],VT=["catalog:///","types://all","samples:///","recipes:///"]});ni();ls();mr();pi();import{spawn as zl}from"node:child_process";import{promises as ce}from"node:fs";import{homedir as WT}from"node:os";import{basename as sg,dirname as Qn,join as Pt,relative as Ho,resolve as ae,sep as jl}from"node:path";import{Command as JT}from"commander";di();import{promises as dd}from"node:fs";function cd(t,e){return e===t?"same-type-merge":"different-type-mint"}var ud=4;function fi(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=gr(t,"id"),r=gr(t,"on"),n=gr(t,"source"),s=gr(t,"recordType"),o=/to\s*:\s*\{([^}]*)\}/.exec(t)?.[1]??"",i=gr(o,"source"),a=gr(o,"recordType"),l=/cycleBudget\s*:\s*(\d+)/.exec(t);if(!e||!n||!s||!i||!a)throw new Error("could not parse id/from.{source,recordType}/to.{source,recordType} \u2014 is it a reference-shape defineConduit({...})?");return{id:e,on:r,fromSource:n,fromRecordType:s,toSource:i,toRecordType:a,cycleBudget:l?Number(l[1]):ud}}function gr(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function Lg(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 pd(t,e,r="fixture"){let n=e.name??r,s=[],o;try{o=fi(t)}catch(l){return{fixtureName:n,conduit:Dg(),guards:s,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],logs:[],error:l instanceof Error?l.message:String(l)}}let i=Lg(e),a=Object.entries(e.atlasLinks??{}).map(([l,d])=>({key:l,resolved:d}));try{let l=await us(t),u=!!(await Qr(l,i,{member:"when",timeoutMs:200})).whenResult;s.push({name:"from.when",status:u?"passed":"failed",detail:u?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let h=e.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${h} vs cycleBudget=${o.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)"}),!u)return{fixtureName:n,conduit:o,guards:s,whenPassed:u,atlasResolutions:a,wouldWriteBindings:[],logs:[]};let v=await Qr(l,i,{member:"transform",timeoutMs:200}),g=v.effects.logs,w=v.effects.result;if(!w||typeof w!="object")throw new Error(`conduit ${o.id} transform returned no result (expected { patch, createdFrom? })`);let $=w,R=cd(o.fromRecordType,o.toRecordType),{wouldWriteBindings:E,masterAction:A}=Ug(o,R,e);return{fixtureName:n,conduit:o,guards:s,whenPassed:u,atlasResolutions:a,transformResult:$,applyBranch:R,wouldWriteBindings:E,masterAction:A,logs:g}}catch(l){return{fixtureName:n,conduit:o,guards:s,whenPassed:!1,atlasResolutions:a,wouldWriteBindings:[],logs:[],error:l instanceof Error?l.message:String(l)}}}function Ug(t,e,r){return e==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${r.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:r.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:t.toSource,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${t.toRecordType} master (source_system='${t.toSource}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:t.toSource,externalId:null,role:"origin",why:"this conduit CREATED the new master, so the target is its origin; external_id null until writeback mints it"},{source:t.fromSource,externalId:r.externalId,role:"replica",why:"firing source bound onto the created master (supplementary lineage; best-effort, may collide in a 1\u2192N fan)"}]}}function Dg(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",cycleBudget:ud}}async function fd(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 hd(t){let e=await dd.readFile(t,"utf8");return JSON.parse(e)}function md(t){return dd.readFile(t,"utf8")}function gd(t,e){let r=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;if(!e)return t.whenPassed?`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`:`replay ${t.fixtureName} [${r.id}]: WHEN-FAILED (conduit short-circuited)`;let n=[];n.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),n.push(`conduit: ${r.id}`),n.push(`route: ${r.fromSource}.${r.fromRecordType} \u2192 ${r.toSource}.${r.toRecordType}${r.on?` on=${r.on}`:""}`),n.push(""),n.push("guards (dispatch order):");for(let s of t.guards){let o=s.status==="passed"?"\u2713":s.status==="failed"?"\u2717":"\u2298";n.push(` ${o} ${s.name} [${s.status}] \u2014 ${s.detail}`)}if(n.push(""),n.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)n.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let s of t.atlasResolutions)n.push(` ${s.key} \u2192 ${s.resolved===null?"null (no Atlas link \u2014 noted)":s.resolved}`);if(!t.whenPassed)return n.push(""),n.push("transform: SKIPPED (from.when gate did not fire)."),n.join(`
|
|
895
|
+
`);if(n.push(""),n.push("transform \u2192 patch:"),n.push(qg(JSON.stringify(t.transformResult?.patch??{},null,2)," ")),t.transformResult?.createdFrom&&n.push(` createdFrom: ${JSON.stringify(t.transformResult.createdFrom)}`),t.logs.length>0){n.push(""),n.push("conduit logs:");for(let s of t.logs)n.push(` [${s.level}] ${s.message}${s.meta?` ${JSON.stringify(s.meta)}`:""}`)}n.push(""),n.push(`apply-branch: ${t.applyBranch}`),n.push(` ${t.masterAction}`),n.push(""),n.push("bindings that WOULD be written (txn_source_link):");for(let s of t.wouldWriteBindings)n.push(` ${s.source} role=${s.role} external_id=${s.externalId??"null"} \u2014 ${s.why}`);return n.join(`
|
|
896
|
+
`)}function qg(t,e){return t.split(`
|
|
897
897
|
`).map(r=>e+r).join(`
|
|
898
|
-
`)}var
|
|
898
|
+
`)}var Mg="2026-01-01",yd="2026-01-01T00:00:00.000Z";function Bg(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"?Mg:r.startsWith("timestamp")?yd: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:yd}:{}:r==="uuid"?"00000000-0000-0000-0000-000000000000":r==="array"||r.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function Fg(t){let e={};for(let r of t.columns)e[r.name]=Bg(r.pgType,r.name);return e}function Hg(t,e={}){let r=e.event??"before_save";return{name:`${t.recordType} ${r} (generated)`,context:{recordType:t.recordType,event:r,source:t.source,payload:Fg(t)},expect:e.expect??"pass"}}function bd(t,e={}){return t.map(r=>({recordType:r.recordType,fixture:Hg(r,e)}))}import{promises as wd}from"node:fs";import{join as vd,relative as Kg,sep as Vg}from"node:path";var Gg=67324752,Wg=33639248,Jg=101010256,Zg=(()=>{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 Yg(t){let e=4294967295;for(let r=0;r<t.length;r++)e=Zg[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}async function Qg(t){let e=[];async function r(n){let s=await wd.readdir(n,{withFileTypes:!0});for(let o of s){let i=vd(n,o.name);o.isDirectory()?await r(i):o.isFile()&&e.push(Kg(t,i).split(Vg).join("/"))}}return await r(t),e.sort(),e}async function Sd(t){let e=await Qg(t),r=[],n=[],s=0;for(let a of e){let l=Buffer.from(a,"utf8"),d=await wd.readFile(vd(t,a)),u=Yg(d),h=Buffer.alloc(30+l.length);h.writeUInt32LE(Gg,0),h.writeUInt16LE(20,4),h.writeUInt16LE(0,6),h.writeUInt16LE(0,8),h.writeUInt32LE(u,14),h.writeUInt32LE(d.length,18),h.writeUInt32LE(d.length,22),h.writeUInt16LE(l.length,26),l.copy(h,30),r.push(h,d);let v=Buffer.alloc(46+l.length);v.writeUInt32LE(Wg,0),v.writeUInt16LE(20,4),v.writeUInt16LE(20,6),v.writeUInt16LE(0,10),v.writeUInt32LE(u,16),v.writeUInt32LE(d.length,20),v.writeUInt32LE(d.length,24),v.writeUInt16LE(l.length,28),v.writeUInt32LE(s,42),l.copy(v,46),n.push(v),s+=h.length+d.length}let o=Buffer.concat(n),i=Buffer.alloc(22);return i.writeUInt32LE(Jg,0),i.writeUInt16LE(e.length,8),i.writeUInt16LE(e.length,10),i.writeUInt32LE(o.length,12),i.writeUInt32LE(s,16),{buffer:Buffer.concat([...r,o,i]),fileCount:e.length}}function Xg(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":"hook"}function fs(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function ey(t){let e=_d(t,"from"),r=_d(t,"to");return{fromSource:e?fs(e,"source"):void 0,fromRecordType:e?fs(e,"recordType"):void 0,toSource:r?fs(r,"source"):void 0,toRecordType:r?fs(r,"recordType"):void 0}}function _d(t,e){let r=new RegExp(`\\b${e}\\s*:\\s*\\{`).exec(t);if(!r)return null;let n=0,s=r.index+r[0].length-1;for(let o=s;o<t.length;o+=1){let i=t[o];if(i==="{")n+=1;else if(i==="}"&&(n-=1,n===0))return t.slice(s+1,o)}return null}function ty(t){let e=/idempotencyKey\s*:/.exec(t);if(!e)return null;let r=e.index+e[0].length,n=0,s=null,o=r;for(;o<t.length;o+=1){let l=t[o];if(s){l==="\\"?o+=1:l===s&&(s=null);continue}if(l==="'"||l==='"'||l==="`"){s=l;continue}if(l==="("||l==="{"||l==="[")n+=1;else if(l===")"||l==="}"||l==="]"){if(n===0)break;n-=1}else if(l===","&&n===0)break}let i=t.slice(r,o),a=i.indexOf("=>");return a>=0?i.slice(a+2):i}function ry(t,e){let r=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return r?Number(r[1]):void 0}function ny(t){return/\bcreatedFrom\b/.test(t)}function $d(t){let e=Xg(t),r=[];if(e==="hook")return{kind:e,warnings:r};let{fromSource:n,toSource:s,fromRecordType:o,toRecordType:i}=ey(t);n&&s&&n===s&&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.`});let a=ty(t);if(a!==null){let d=/\bexternalId\b/.test(a),u=/\bfromSource\b/.test(a);!d&&!u&&r.push({rule:"weak-idempotency-key",message:"idempotencyKey omits both ctx.externalId and ctx.fromSource \u2014 two distinct re-fires (different records, or the same record from different sources) collapse onto one conduit_event ledger row and one of them is silently dropped as a duplicate.",fix:"Include `ctx.externalId` (and, for multi-source triggers, `ctx.fromSource`) in the key, e.g. `idempotencyKey: (ctx) => `${ctx.fromSource}:${ctx.externalId}``."})}o&&i&&o!==i&&!ny(t)&&r.push({rule:"missing-created-from",message:`this conduit bridges '${o}' \u2192 '${i}' (different record types) but its transform never returns 'createdFrom' \u2014 the created ${i} won't carry a lineage pointer back to its origin, so the reverse leg can't find it.`,fix:"Return `createdFrom: { source: ctx.fromSource, recordType: ctx.recordType, externalId: ctx.externalId }` from the transform so the counterpart is bound to the master by construction."});let l=ry(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 kd(t,e,r={}){let n=r.warn??(a=>a),s=r.ok??(a=>a),o=r.dim??(a=>a),i=[];if(i.push(`lint: ${t} (${e.kind})`),e.warnings.length===0)return i.push(` ${s("ok")} \u2014 no warnings.`),i.join(`
|
|
899
899
|
`);for(let a of e.warnings)i.push(` ${n("WARN")} ${o(`[${a.rule}]`)} ${a.message}`),i.push(` ${o("\u2192 fix:")} ${a.fix}`);return i.push(`
|
|
900
900
|
lint: ${n(`${e.warnings.length} warning(s).`)}`),i.join(`
|
|
901
|
-
`)}function
|
|
901
|
+
`)}function xd(t){return t.cases.filter(e=>e.status==="failed").length}function tn(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function sy(t){let e=xd(t),r=[];r.push('<?xml version="1.0" encoding="UTF-8"?>'),r.push(`<testsuite name="${tn(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let n of t.cases){let s=` <testcase name="${tn(n.name)}"`;if(n.status==="passed"){r.push(`${s} />`);continue}r.push(`${s}>`);let o=n.detail??"failed",i=n.type?` type="${tn(n.type)}"`:"";r.push(` <failure${i} message="${tn(o)}">${tn(o)}</failure>`),r.push(" </testcase>")}return r.push("</testsuite>"),`${r.join(`
|
|
902
902
|
`)}
|
|
903
|
-
`}function
|
|
904
|
-
`}function
|
|
905
|
-
`)}function
|
|
906
|
-
`)}function
|
|
903
|
+
`}function oy(t){let e={suite:t.name,tests:t.cases.length,failures:xd(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
|
|
904
|
+
`}function hs(t,e){return e==="junit"?sy(t):oy(t)}var De={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"},Se={hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",clearLine:"\x1B[2K",clearToEnd:"\x1B[0J",col0:"\r",cursorUp:t=>`\x1B[${t}A`},yr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],We={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},Td=/\x1b\[[0-9;]*m/g;function St(t){return t.replace(Td,"").length}function hi(t,e){return e<=0?1:Math.max(1,Math.ceil(St(t)/e))}function iy(){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 mi=iy();function qe(){return mi}function gi(t){mi=t}function _t(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function Je(t,e){return mi?`${t}${e}${De.reset}`:e}var k={bold:t=>Je(De.bold,t),dim:t=>Je(De.dim,t),red:t=>Je(De.red,t),green:t=>Je(De.green,t),yellow:t=>Je(De.yellow,t),blue:t=>Je(De.blue,t),magenta:t=>Je(De.magenta,t),cyan:t=>Je(De.cyan,t),grey:t=>Je(De.grey,t)};var Ne={success:t=>`${k.green("\u2713")} ${t}`,error:t=>`${k.red("\u2716")} ${t}`,warn:t=>`${k.yellow("\u26A0")} ${t}`,info:t=>`${k.dim("\xB7")} ${t}`,step:t=>`${k.cyan("\u25B8")} ${t}`},Ot={add:t=>k.green(`+ ${t}`),change:t=>k.yellow(`~ ${t}`),destroy:t=>k.red(`- ${t}`)},ay=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),cy=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),ly=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function br(t){let e=t.toLowerCase();return ay.has(e)?k.green(t):cy.has(e)?k.red(t):ly.has(e)?k.yellow(t):t}function Nt(t,e=[]){let r=Math.max(St(t),...e.map(St),0),n=r+2,s=k.cyan(We.v),o=a=>` ${a}${" ".repeat(r-St(a))} `,i=[k.cyan(`${We.tl}${We.h.repeat(n)}${We.tr}`),`${s}${k.bold(o(t))}${s}`];if(e.length){i.push(`${k.cyan(We.ml)}${k.dim(We.h.repeat(n))}${k.cyan(We.mr)}`);for(let a of e)i.push(`${s}${o(a)}${s}`)}return i.push(k.cyan(`${We.bl}${We.h.repeat(n)}${We.br}`)),i.join(`
|
|
905
|
+
`)}function Qt(t,e={}){let r=e.indent??" ",n=e.gap??" ",s=e.head?[e.head,...t]:t,o=Math.max(0,...s.map(d=>d.length)),i=[];for(let d=0;d<o;d+=1)i[d]=Math.max(0,...s.map(u=>St(u[d]??"")));let a=d=>{let u=d.map((h,v)=>{let g=h??"";return v===d.length-1?g:g+" ".repeat(Math.max(0,i[v]-St(g)))});return r+u.join(n)},l=[];e.head&&(l.push(a(e.head.map(d=>k.bold(d)))),l.push(a(e.head.map((d,u)=>k.dim("\u2500".repeat(i[u]??St(d)))))));for(let d of t)l.push(a(d));return l.join(`
|
|
906
|
+
`)}function yi(t="the CLI for your Turbobase instance"){let e=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D"," \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2557 "," \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u255A\u2550\u2550\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D "," \u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"];return`${qe()?e.map(n=>Je(De.cyan,n)).join(`
|
|
907
907
|
`):e.join(`
|
|
908
908
|
`)}
|
|
909
|
-
${
|
|
910
|
-
`),i}catch(i){throw o(),r&&
|
|
911
|
-
`),i}}function
|
|
912
|
-
`),o()},status(l){r=l,o()},done(l){clearInterval(a),i(),
|
|
913
|
-
`)},stop(){clearInterval(a),i(),
|
|
914
|
-
`),a(`${
|
|
915
|
-
`),a(
|
|
916
|
-
`),
|
|
917
|
-
`),s(new Error("aborted"));return}if(
|
|
918
|
-
`){let
|
|
919
|
-
`)}),s=r.sleep??
|
|
920
|
-
`)});if(e.retry){let s=await t.retryBinding(e.retry);return r(`binding: re-enqueued fan-out for ${s.id} \u2192 ${s.sourceSystem} (master ${s.masterTable}/${s.masterRowId}).`),{mode:"retry",id:s.id,retried:s.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 s of n)r(
|
|
921
|
-
binding: ${n.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:n.length}}
|
|
909
|
+
${k.dim(` ${t}`)}`}var Ze=t=>{process.stderr.write(t)};function ms(){return qe()&&process.stderr.isTTY===!0}function Rd(t,e=15){let r=Math.max(0,Math.min(100,t??0)),n=Math.round(r/100*e);return`${"\u2588".repeat(n)}${k.dim("\u2591".repeat(e-n))}`}async function le(t,e){let r=ms(),n=0,s;r&&(Ze(Se.hideCursor),s=setInterval(()=>{Ze(`${Se.col0}${Se.clearLine}${k.magenta(yr[n++%yr.length])} ${t}`)},80));let o=()=>{s&&clearInterval(s),r&&Ze(`${Se.col0}${Se.clearLine}${Se.showCursor}`)};try{let i=await e();return o(),r&&Ze(`${Ne.success(t)}
|
|
910
|
+
`),i}catch(i){throw o(),r&&Ze(`${Ne.error(t)}
|
|
911
|
+
`),i}}function bi(t){let e=0,r={stage:"queued"},n=!1,s=()=>{let l=k.magenta(yr[e%yr.length]),d=k.cyan(r.stage),u=r.runStatus?` ${k.dim(`(${r.runStatus})`)}`:"",h=`${String(Math.round(r.percent??0)).padStart(3)}%`;return`${l} ${t} ${k.dim("\u25B8")} ${d}${u} ${Rd(r.percent)} ${h}`},o=()=>{Ze(`${Se.col0}${Se.clearLine}${s()}`),n=!0},i=()=>{n&&Ze(`${Se.col0}${Se.clearLine}`),n=!1};Ze(Se.hideCursor);let a=setInterval(()=>{e+=1,o()},80);return{log(l){i(),Ze(`${l}
|
|
912
|
+
`),o()},status(l){r=l,o()},done(l){clearInterval(a),i(),Ze(Se.showCursor);let d=l.stage!=="failed",u=`${t} ${k.dim("\u25B8")} ${dy(l.stage)}${l.runStatus?` (${l.runStatus})`:""}`;Ze(`${d?Ne.success(u):Ne.error(u)}
|
|
913
|
+
`)},stop(){clearInterval(a),i(),Ze(Se.showCursor)}}}function dy(t){return t==="completed"?k.green(t):t==="failed"?k.red(t):k.cyan(t)}function $t(t,e,r={}){return new Promise((n,s)=>{let o=e.findIndex($=>!$.disabled);if(o===-1){s(new Error("no selectable options"));return}let i=r.defaultIndex!==void 0&&!e[r.defaultIndex]?.disabled?r.defaultIndex:o,a=$=>{process.stderr.write($)},l=process.stdin,d=l.isRaw;l.setRawMode?.(!0),l.resume(),a(`${k.bold(k.cyan("?"))} ${k.bold(t)}
|
|
914
|
+
`),a(`${k.dim(" (\u2191/\u2193 to move, enter to select, ctrl+c to abort)")}
|
|
915
|
+
`),a(Se.hideCursor);let u=0,h=()=>{let $=process.stderr.columns??process.stdout.columns??80;u>0&&(a(Se.cursorUp(u)),a(Se.clearToEnd));let R=0;for(let E=0;E<e.length;E+=1){let A=e[E],z=E===i,ee=z?k.cyan("\u25B6"):" ",F=A.disabled?k.grey(A.label):z?k.bold(k.cyan(A.label)):A.label,Ce=A.description?` ${k.dim(A.description)}`:"",Ue=` ${ee} ${F}${Ce}`;a(`\r${Ue}
|
|
916
|
+
`),R+=hi(Ue,$)}u=R},v=()=>{l.removeListener("data",w),l.setRawMode?.(d??!1),l.pause(),a(Se.showCursor)},g=$=>{let R=i;for(let E=0;E<e.length;E+=1)if(R=(R+$+e.length)%e.length,!e[R].disabled){i=R;return}},w=$=>{let R=$.toString("utf8");if(R===""||R==="q"){v(),a(`
|
|
917
|
+
`),s(new Error("aborted"));return}if(R==="\r"||R===`
|
|
918
|
+
`){let A=e[i];if(A.disabled)return;v(),n(A.value);return}if(R==="\x1B[A"||R==="k"){g(-1),h();return}if(R==="\x1B[B"||R==="j"){g(1),h();return}let E=Number(R);Number.isFinite(E)&&E>=1&&E<=e.length&&!e[E-1].disabled&&(i=E-1,h())};l.on("data",w),h()})}function Pd(t,e){return`${br(t)}${" ".repeat(Math.max(0,e-t.length))}`}var uy=t=>new Promise(e=>setTimeout(e,t));function Ed(t){let e=t.toRecordType?`${t.toSource}/${t.toRecordType}`:t.toSource,r=t.reason?` reason="${t.reason}"`:"",n=t.fromExternalId?` ext=${t.fromExternalId}`:"",s=t.toMasterTable&&t.toMasterRowId?` master=${t.toMasterTable}/${t.toMasterRowId}`:"";return`[${t.updatedAt}] ${Pd(t.state,9)} ${t.conduitId} \u2192 ${e}${n} hop=${t.hop}${s}${r}`}async function Ad(t,e,r={}){let n=r.sink??(u=>{process.stdout.write(`${u}
|
|
919
|
+
`)}),s=r.sleep??uy,o=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,l="";for(let u of[...i].reverse())n(Ed(u)),a+=1,u.updatedAt>l&&(l=u.updatedAt);if(!r.follow)return a;let d=r.maxPolls??Number.POSITIVE_INFINITY;for(let u=0;u<d;u+=1){await s(o);let h=await t.conduitEvents(e,{since:l||void 0,limit:200});for(let v of[...h].reverse())n(Ed(v)),a+=1,v.updatedAt>l&&(l=v.updatedAt)}return a}function py(t){let e=t.externalId??"\u2014",r=t.createdByConduit?` via=${t.createdByConduit}`:"",n=t.lastError?` last_error="${t.lastError}"`:"";return`${t.id} ${Pd(t.writeStatus,9)} ${t.sourceSystem}/${e} role=${t.role} master=${t.masterTable}/${t.masterRowId}${r}${n}`}async function Id(t,e={}){let r=e.sink??(s=>{process.stdout.write(`${s}
|
|
920
|
+
`)});if(e.retry){let s=await t.retryBinding(e.retry);return r(`binding: re-enqueued fan-out for ${s.id} \u2192 ${s.sourceSystem} (master ${s.masterTable}/${s.masterRowId}).`),{mode:"retry",id:s.id,retried:s.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 s of n)r(py(s));return r(`
|
|
921
|
+
binding: ${n.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:n.length}}wi();function Od(t){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?{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}).`}:null}var vi=".github/workflows/turbobase-release-deploy.yml",gy=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
922
|
+
# Turbobase release deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR repo)
|
|
923
|
+
#
|
|
924
|
+
# Epic #775 "GitHub is just a link": Turbobase hosts nothing and clones nothing.
|
|
925
|
+
# This workflow runs in YOUR GitHub repo, on YOUR runner. On every merge to your
|
|
926
|
+
# default branch it ships your SDF customization project to Turbobase by running
|
|
927
|
+
# the \`turbobase\` CLI, which UPLOADS the bytes from this checkout. Turbobase
|
|
928
|
+
# never fetches your code, never holds a GitHub App key, and never mints an
|
|
929
|
+
# installation token \u2014 the ONLY credential is a personal access token (PAT) that
|
|
930
|
+
# YOU mint and store as a GitHub Actions secret (one-time setup below).
|
|
931
|
+
#
|
|
932
|
+
# \u2500\u2500 One-time setup \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
933
|
+
# 1. Mint a \`releases:write\` PAT (you, in your Turbobase app):
|
|
934
|
+
# Settings \u2192 Access tokens \u2192 "New token"
|
|
935
|
+
# Scope: releases:write (the only scope this workflow needs)
|
|
936
|
+
# Copy the token \u2014 it starts with \`tb_pat_\u2026\` and is shown only once.
|
|
937
|
+
#
|
|
938
|
+
# 2. Store the PAT as a GitHub Actions SECRET in this repo (you, in GitHub):
|
|
939
|
+
# Repo \u2192 Settings \u2192 Secrets and variables \u2192 Actions \u2192 "New repository secret"
|
|
940
|
+
# Name: TURBOBASE_RELEASE_PAT
|
|
941
|
+
# Value: <the tb_pat_\u2026 token from step 1>
|
|
942
|
+
# The PAT lives ONLY in your GitHub secret store. Turbobase never sees your
|
|
943
|
+
# GitHub credentials, and you never paste a Turbobase secret into this file.
|
|
944
|
+
#
|
|
945
|
+
# 3. Store your instance base URL as a repo VARIABLE (not a secret \u2014 it isn't
|
|
946
|
+
# sensitive) so the workflow knows which instance to deploy to:
|
|
947
|
+
# Repo \u2192 Settings \u2192 Secrets and variables \u2192 Actions \u2192 Variables \u2192 "New"
|
|
948
|
+
# Name: TURBOBASE_BASE_URL
|
|
949
|
+
# Value: https://<your-slug>.turbobase.app
|
|
950
|
+
#
|
|
951
|
+
# 4. Put this file at \`.github/workflows/turbobase-release-deploy.yml\` (or run
|
|
952
|
+
# \`turbobase project ci\`, which writes it there for you), commit, and merge.
|
|
953
|
+
# The next merge to your default branch deploys.
|
|
954
|
+
#
|
|
955
|
+
# \u2500\u2500 What it deliberately does NOT do \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
956
|
+
# \u2022 No GitHub App, no installation token, no server-side clone \u2014 Turbobase
|
|
957
|
+
# receives ONLY the bytes this checkout uploads.
|
|
958
|
+
# \u2022 Defaults to \`--target auto\`. An approval-gated deploy is a guarded,
|
|
959
|
+
# human-approved action (\`--target approved --approved-by you@co.com\`) and is
|
|
960
|
+
# intentionally NOT wired to fire automatically on merge.
|
|
961
|
+
# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
962
|
+
name: Turbobase release deploy
|
|
963
|
+
|
|
964
|
+
on:
|
|
965
|
+
push:
|
|
966
|
+
# Change \`main\` to your repo's default branch if it differs (e.g. master).
|
|
967
|
+
branches: [main]
|
|
968
|
+
|
|
969
|
+
# Least privilege: this workflow only READS your checkout to upload it. It never
|
|
970
|
+
# writes to your repo, and it does NOT use GITHUB_TOKEN to reach Turbobase \u2014 the
|
|
971
|
+
# PAT secret is the only credential that leaves the runner.
|
|
972
|
+
permissions:
|
|
973
|
+
contents: read
|
|
974
|
+
|
|
975
|
+
# One deploy at a time per branch; a newer merge supersedes any in-flight run.
|
|
976
|
+
concurrency:
|
|
977
|
+
group: turbobase-release-\${{ github.ref }}
|
|
978
|
+
cancel-in-progress: false
|
|
979
|
+
|
|
980
|
+
jobs:
|
|
981
|
+
deploy:
|
|
982
|
+
runs-on: ubuntu-latest
|
|
983
|
+
steps:
|
|
984
|
+
# The checkout IS the upload source. \`turbobase release deploy\` reads the
|
|
985
|
+
# SDF project's src/ from this working tree and uploads those bytes;
|
|
986
|
+
# nothing is fetched server-side.
|
|
987
|
+
- name: Check out the merged commit
|
|
988
|
+
uses: actions/checkout@v4
|
|
989
|
+
|
|
990
|
+
- name: Set up Node
|
|
991
|
+
uses: actions/setup-node@v4
|
|
992
|
+
with:
|
|
993
|
+
node-version: '22'
|
|
994
|
+
|
|
995
|
+
# Install the \`turbobase\` CLI. The package is scoped; the command it
|
|
996
|
+
# installs is plain \`turbobase\`. Pin a version (\`@turbobase/cli@1.2.3\`)
|
|
997
|
+
# if you would rather CI not track the current release.
|
|
998
|
+
- name: Install the turbobase CLI
|
|
999
|
+
run: npm install -g @turbobase/cli
|
|
1000
|
+
|
|
1001
|
+
# Authenticate headlessly: store the PAT for this instance. The token is read
|
|
1002
|
+
# from the GitHub secret via env (never interpolated into the command line,
|
|
1003
|
+
# so it can't leak into the run logs).
|
|
1004
|
+
- name: Authenticate to Turbobase
|
|
1005
|
+
env:
|
|
1006
|
+
TURBOBASE_RELEASE_PAT: \${{ secrets.TURBOBASE_RELEASE_PAT }}
|
|
1007
|
+
run: |
|
|
1008
|
+
turbobase auth login \\
|
|
1009
|
+
--base-url "\${{ vars.TURBOBASE_BASE_URL }}" \\
|
|
1010
|
+
--token "$TURBOBASE_RELEASE_PAT"
|
|
1011
|
+
|
|
1012
|
+
# Ship it. \`--ref \${{ github.sha }}\` records the exact commit these bytes
|
|
1013
|
+
# were built from (a provenance LINK only \u2014 Turbobase never fetches it).
|
|
1014
|
+
# \`--project .\` uploads this checkout's SDF src/; \`--follow\` waits for the
|
|
1015
|
+
# server-side deploy job and fails the run if the deploy fails.
|
|
1016
|
+
- name: Deploy the release
|
|
1017
|
+
run: |
|
|
1018
|
+
turbobase release deploy \\
|
|
1019
|
+
--target auto \\
|
|
1020
|
+
--ref "\${{ github.sha }}" \\
|
|
1021
|
+
--project . \\
|
|
1022
|
+
--follow
|
|
1023
|
+
`,yy=".github/workflows/turbobase-tables-plan.yml",by=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1024
|
+
# Turbobase table check \u2014 REUSABLE TEMPLATE (drop this into YOUR app repo)
|
|
1025
|
+
#
|
|
1026
|
+
# Runs \`turbobase tables plan\` against your instance on every pull request. It
|
|
1027
|
+
# WRITES NOTHING \u2014 it reads the \`tables\` block in public/turbobase.json, asks
|
|
1028
|
+
# the instance what applying it would do, and fails this check if that would
|
|
1029
|
+
# conflict with a table another app already declares.
|
|
1030
|
+
#
|
|
1031
|
+
# Why a check and not just a deploy-time error: several apps on one instance can
|
|
1032
|
+
# declare the same table, and the instance MERGES their declarations. Two apps
|
|
1033
|
+
# declaring the SAME field name at DIFFERENT types is the one case that cannot
|
|
1034
|
+
# merge \u2014 a column has one type, and silently picking one would break the other
|
|
1035
|
+
# app's reads. Without this check you meet that as a 409 on the ship, after
|
|
1036
|
+
# review, when you are trying to release. With it, you meet it as a red PR check
|
|
1037
|
+
# naming the app you collided with.
|
|
1038
|
+
#
|
|
1039
|
+
# \u2500\u2500 One-time setup \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1040
|
+
# 1. Mint an \`extensions:deploy\` PAT (Settings \u2192 Access tokens \u2192 "New token").
|
|
1041
|
+
# That is the same scope \`apps push\` / \`apps deploy\` already use, so a PAT
|
|
1042
|
+
# you already have for shipping this app works here.
|
|
1043
|
+
# 2. Store it as a repo SECRET named TURBOBASE_PAT.
|
|
1044
|
+
# 3. Store your instance URL as a repo VARIABLE named TURBOBASE_BASE_URL
|
|
1045
|
+
# (https://<your-slug>.turbobase.app) \u2014 it is not sensitive.
|
|
1046
|
+
#
|
|
1047
|
+
# Delete this file if your app declares no tables; it has nothing to check.
|
|
1048
|
+
# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1049
|
+
name: Turbobase table check
|
|
1050
|
+
|
|
1051
|
+
on:
|
|
1052
|
+
pull_request:
|
|
1053
|
+
push:
|
|
1054
|
+
# Change \`main\` to your repo's default branch if it differs.
|
|
1055
|
+
branches: [main]
|
|
1056
|
+
|
|
1057
|
+
# Least privilege: reads the checkout, writes nothing anywhere.
|
|
1058
|
+
permissions:
|
|
1059
|
+
contents: read
|
|
1060
|
+
|
|
1061
|
+
concurrency:
|
|
1062
|
+
group: turbobase-tables-\${{ github.ref }}
|
|
1063
|
+
cancel-in-progress: true
|
|
1064
|
+
|
|
1065
|
+
jobs:
|
|
1066
|
+
plan:
|
|
1067
|
+
runs-on: ubuntu-latest
|
|
1068
|
+
# Skips \u2014 rather than fails \u2014 until the one-time setup above is done. A
|
|
1069
|
+
# scaffolded workflow that is red on a brand-new repo trains its author to
|
|
1070
|
+
# ignore the check, which is worse than not having it.
|
|
1071
|
+
if: vars.TURBOBASE_BASE_URL != ''
|
|
1072
|
+
steps:
|
|
1073
|
+
- name: Check out the branch
|
|
1074
|
+
uses: actions/checkout@v4
|
|
1075
|
+
|
|
1076
|
+
- name: Set up Node
|
|
1077
|
+
uses: actions/setup-node@v4
|
|
1078
|
+
with:
|
|
1079
|
+
node-version: '22'
|
|
1080
|
+
|
|
1081
|
+
- name: Install the turbobase CLI
|
|
1082
|
+
run: npm install -g @turbobase/cli
|
|
1083
|
+
|
|
1084
|
+
# The token is passed via env, never interpolated into the command line,
|
|
1085
|
+
# so it cannot land in the run log.
|
|
1086
|
+
- name: Authenticate to Turbobase
|
|
1087
|
+
env:
|
|
1088
|
+
TURBOBASE_PAT: \${{ secrets.TURBOBASE_PAT }}
|
|
1089
|
+
run: |
|
|
1090
|
+
turbobase auth login \\
|
|
1091
|
+
--base-url "\${{ vars.TURBOBASE_BASE_URL }}" \\
|
|
1092
|
+
--token "$TURBOBASE_PAT"
|
|
1093
|
+
|
|
1094
|
+
# Exits non-zero on a conflict, printing which app declared the clashing
|
|
1095
|
+
# field and at what type. Writes nothing to the instance either way.
|
|
1096
|
+
- name: Plan the declared tables
|
|
1097
|
+
run: turbobase tables plan .
|
|
1098
|
+
`;function Nd(){return[{path:vi,content:gy}]}function jd(){return[{path:yy,content:by}]}var wy=[".mcp.json"];function Ld(t,e=wy){let r=i=>i.replace(/^\//,""),n=new Set(t.split(`
|
|
922
1099
|
`).map(i=>i.trim()).filter(i=>i!==""&&!i.startsWith("#")).map(r)),s=e.filter(i=>!n.has(r(i)));return s.length===0?null:`${t===""||t.endsWith(`
|
|
923
1100
|
`)?t:`${t}
|
|
924
1101
|
`}
|
|
925
|
-
# Added by the
|
|
1102
|
+
# Added by the Turbobase scaffold.
|
|
926
1103
|
${s.join(`
|
|
927
1104
|
`)}
|
|
928
|
-
`}var
|
|
1105
|
+
`}var vy=`# Turbobase Extensions \u2014 extension project
|
|
929
1106
|
|
|
930
|
-
This directory authors **
|
|
1107
|
+
This directory authors **Turbobase extensions** (hooks today; conduits later)
|
|
931
1108
|
against a live instance. The \`turbobase\` CLI is the engine; Claude Code drives it
|
|
932
1109
|
through the local MCP server (\`.mcp.json\`) and the skills under \`.claude/skills/\`.
|
|
933
1110
|
|
|
@@ -977,10 +1154,10 @@ knowledge-base claim, the row goes in \`## Knowledge-base corrections\` instead
|
|
|
977
1154
|
gets caught. A finding added without its entry is half-done. Neither waits for
|
|
978
1155
|
the end of a task, and neither waits to be asked.
|
|
979
1156
|
|
|
980
|
-
## Feed problems back to
|
|
1157
|
+
## Feed problems back to Turbobase \u2014 continuously
|
|
981
1158
|
|
|
982
1159
|
Keep **\`TURBOBASE-FEEDBACK.md\`** up to date AS YOU WORK. It is the channel to the
|
|
983
|
-
|
|
1160
|
+
Turbobase product team, and the entries worth most are the ones written the
|
|
984
1161
|
moment they cost you time \u2014 they evaporate from memory otherwise.
|
|
985
1162
|
|
|
986
1163
|
Append an entry whenever the PLATFORM itself (not your own code) causes trouble:
|
|
@@ -994,8 +1171,8 @@ order is the signal, and it is the part the product team reads first.
|
|
|
994
1171
|
|
|
995
1172
|
Do this WITHOUT being asked \u2014 treat it as part of finishing a task, like
|
|
996
1173
|
updating a test. It is checked into the repo so the whole team sees it.
|
|
997
|
-
`,
|
|
998
|
-
`;function
|
|
1174
|
+
`,Sy=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)+`
|
|
1175
|
+
`;function _y(t){return`---
|
|
999
1176
|
name: generate-types
|
|
1000
1177
|
description: Regenerate ${t} from the signed-in instance's catalog. Use before authoring or whenever the schema may have changed.
|
|
1001
1178
|
---
|
|
@@ -1006,7 +1183,7 @@ write \`${t}\`. Import the generated record interfaces for typed rows.
|
|
|
1006
1183
|
|
|
1007
1184
|
The OpenAPI half is cookie-session-gated, so a headless run with a stored token
|
|
1008
1185
|
degrades to record shapes only and says so \u2014 that is expected, not a failure.
|
|
1009
|
-
`}var
|
|
1186
|
+
`}var $y=`---
|
|
1010
1187
|
name: mock-test
|
|
1011
1188
|
description: Dry-run a hook against samples/ fixtures using the production sandbox. Use after editing a hook, before deploy.
|
|
1012
1189
|
---
|
|
@@ -1015,7 +1192,7 @@ Run \`turbobase ext test hooks/<file>.ts\`. It bundles the hook through the same
|
|
|
1015
1192
|
self-contained-fence esbuild + isolated-vm the live runtime uses, then runs it
|
|
1016
1193
|
against every \`samples/*.json\` fixture and reports pass/reject per sample. Add a
|
|
1017
1194
|
fixture for each branch (a passing record and a rejecting record).
|
|
1018
|
-
`,
|
|
1195
|
+
`,ky=`---
|
|
1019
1196
|
name: deploy
|
|
1020
1197
|
description: Deploy a hook to your instance. Use only after mock-test is green.
|
|
1021
1198
|
---
|
|
@@ -1023,9 +1200,9 @@ description: Deploy a hook to your instance. Use only after mock-test is green.
|
|
|
1023
1200
|
Run \`turbobase ext deploy hooks/<file>.ts\`. It POSTs the hook source to
|
|
1024
1201
|
/v1/extensions with the stored admin PAT; the hook lands **active**. Re-deploying
|
|
1025
1202
|
the same id overwrites it (idempotent). Tail with \`turbobase ext logs <id>\`.
|
|
1026
|
-
`;function
|
|
1203
|
+
`;function xy(t){return`# ${t} \u2014 Turbobase app
|
|
1027
1204
|
|
|
1028
|
-
This directory is a **hosted
|
|
1205
|
+
This directory is a **hosted Turbobase app**: a Vite + React + TS SPA served
|
|
1029
1206
|
same-origin by the instance at \`/a/${t}\`. The \`turbobase\` CLI ships it; you
|
|
1030
1207
|
(Claude Code) reach the instance through the two MCP servers in \`.mcp.json\`.
|
|
1031
1208
|
|
|
@@ -1074,7 +1251,7 @@ Check them before you trust a result.
|
|
|
1074
1251
|
(\`entity_type=eq.vendor\`, \`source_system=eq.netsuite\`) or you will label a
|
|
1075
1252
|
vendor with a customer's name.
|
|
1076
1253
|
4. **\`created_at\` / \`updated_at\` / \`synced_at\` / \`last_modified_pg\` are MIRROR
|
|
1077
|
-
timestamps** \u2014 when
|
|
1254
|
+
timestamps** \u2014 when Turbobase wrote the row. After a bulk sync they are
|
|
1078
1255
|
identical across the table, so ordering by one gives sync batch order, not
|
|
1079
1256
|
business order. Use \`source_modified\`, or the source's own date in \`raw\`.
|
|
1080
1257
|
5. **A column can exist and be empty on every row.** \`currency_name\` and
|
|
@@ -1188,10 +1365,10 @@ task, and neither waits to be asked.
|
|
|
1188
1365
|
Same discipline as the feedback file, different audience: that one is about the
|
|
1189
1366
|
platform, this one is about the business.
|
|
1190
1367
|
|
|
1191
|
-
## Feed problems back to
|
|
1368
|
+
## Feed problems back to Turbobase \u2014 continuously
|
|
1192
1369
|
|
|
1193
1370
|
Keep **\`TURBOBASE-FEEDBACK.md\`** up to date AS YOU WORK. It is the channel to the
|
|
1194
|
-
|
|
1371
|
+
Turbobase product team, and the entries worth most are the ones written the
|
|
1195
1372
|
moment they cost you time \u2014 they evaporate from memory otherwise.
|
|
1196
1373
|
|
|
1197
1374
|
Append an entry whenever the PLATFORM itself (not your own code) causes trouble:
|
|
@@ -1208,7 +1385,7 @@ a test. \`turbobase apps deploy\` reads both files and queues what it finds for
|
|
|
1208
1385
|
review, so what you write reaches the knowledge base and the product team instead
|
|
1209
1386
|
of evaporating at the end of the session. Keep the section headings exactly as
|
|
1210
1387
|
they are \u2014 the ingest finds entries by heading, not by filename.
|
|
1211
|
-
`}var
|
|
1388
|
+
`}var Ty="---\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",Ry=`---
|
|
1212
1389
|
name: ship-app
|
|
1213
1390
|
description: Push the app's source to the instance and deploy it live. Use once the app has been previewed and works.
|
|
1214
1391
|
---
|
|
@@ -1251,7 +1428,7 @@ Text files only \u2014 \`push\` skips \`node_modules/\`, \`dist/\`, \`build/\`,
|
|
|
1251
1428
|
non-text, so images and fonts belong in the build pipeline or object storage, not
|
|
1252
1429
|
the source tree. \`INSTANCE-LEARNINGS.md\` and \`TURBOBASE-FEEDBACK.md\` sit at the
|
|
1253
1430
|
project root and DO travel \u2014 deploy reads them.
|
|
1254
|
-
`;function
|
|
1431
|
+
`;function Ey(t){return`---
|
|
1255
1432
|
name: record-learning
|
|
1256
1433
|
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.
|
|
1257
1434
|
---
|
|
@@ -1278,7 +1455,7 @@ Then, in the same edit, add the other half:
|
|
|
1278
1455
|
knowledge-base claim disagrees with the live data: the claim, the live value,
|
|
1279
1456
|
and a verdict (stale / refuted / confirmed / rule broken).
|
|
1280
1457
|
|
|
1281
|
-
**\`TURBOBASE-FEEDBACK.md\` \u2014 about the PLATFORM.** Where
|
|
1458
|
+
**\`TURBOBASE-FEEDBACK.md\` \u2014 about the PLATFORM.** Where Turbobase itself cost you
|
|
1282
1459
|
time \u2014 never your own bugs. Each entry records what you expected, what happened
|
|
1283
1460
|
(the error verbatim, because a misleading message IS the finding), the concrete
|
|
1284
1461
|
cost, and the fix or workaround. Typical entries:
|
|
@@ -1296,7 +1473,7 @@ the product team acts on first, so it is maintained with the entries.
|
|
|
1296
1473
|
|
|
1297
1474
|
Do not reword the three headings. The deploy-side ingest recognises entries by
|
|
1298
1475
|
heading, not by filename, so a renamed section is a finding nobody receives.
|
|
1299
|
-
`}function
|
|
1476
|
+
`}function Py(t){return`# What this instance's source system actually does
|
|
1300
1477
|
|
|
1301
1478
|
Findings from ${t?`building the ${t.slug} app against the live mirror`:"authoring extensions against the live instance"}.
|
|
1302
1479
|
Written for the knowledge base, and **everything here is verified against real
|
|
@@ -1365,7 +1542,34 @@ finding has not been handed to the knowledge base yet.
|
|
|
1365
1542
|
|
|
1366
1543
|
| KB claim | Live value | Verdict |
|
|
1367
1544
|
|---|---|---|
|
|
1368
|
-
|
|
1545
|
+
|
|
1546
|
+
## Agent rules
|
|
1547
|
+
|
|
1548
|
+
<!-- A rule that must hold on EVERY turn, not one that should be findable when
|
|
1549
|
+
somebody asks. This is the difference that decides which section a finding
|
|
1550
|
+
belongs in:
|
|
1551
|
+
|
|
1552
|
+
Knowledge base -> RETRIEVED. Ranked against the question's own text, so
|
|
1553
|
+
a page is in context when someone asks near it. Right
|
|
1554
|
+
for narrative \u2014 how a process works, why a threshold
|
|
1555
|
+
exists.
|
|
1556
|
+
|
|
1557
|
+
Agent rules -> INJECTED. Placed in the agent's instructions verbatim,
|
|
1558
|
+
every matching turn, whether or not the question
|
|
1559
|
+
mentions it. Right for a constraint that is wrong to
|
|
1560
|
+
miss.
|
|
1561
|
+
|
|
1562
|
+
The test: would an agent get this wrong if nobody reminded it? Then it is a
|
|
1563
|
+
rule. Would a person only need it when they went looking? Then it is a page.
|
|
1564
|
+
|
|
1565
|
+
Write each one as an instruction, not an observation \u2014 "always filter
|
|
1566
|
+
\`entity\` by \`entity_type\`", not "the entity table is shared". Keep it short;
|
|
1567
|
+
it is paying for space in every prompt.
|
|
1568
|
+
|
|
1569
|
+
\`turbobase skills push\` writes these as DRAFT rules. Nothing is injected
|
|
1570
|
+
until an admin publishes them. -->
|
|
1571
|
+
|
|
1572
|
+
`}function Ay(t){return`# Feedback for the Turbobase team \u2014 what ${t?`building the ${t.slug} app`:"authoring extensions here"} actually hit
|
|
1369
1573
|
|
|
1370
1574
|
Everything below cost time or produced a wrong result. Not speculation, and not
|
|
1371
1575
|
a wishlist. This file is about the PLATFORM \u2014 scaffold, catalog, CLI, MCP, API.
|
|
@@ -1421,7 +1625,7 @@ Expected / happened / cost / fix.
|
|
|
1421
1625
|
|
|
1422
1626
|
<!-- Rank the findings above by how much time each would have saved. Position is
|
|
1423
1627
|
the signal \u2014 1 is the biggest win. -->
|
|
1424
|
-
`}function
|
|
1628
|
+
`}function Iy(t,e){let r=e?`
|
|
1425
1629
|
# INSTANCE.md \u2014 the instance's grounding brief (see CLAUDE.md). Reuse the
|
|
1426
1630
|
# --records focus a previous run stamped into the file, so a refresh never
|
|
1427
1631
|
# narrows what an agent deliberately widened.
|
|
@@ -1434,160 +1638,61 @@ turbobase project grounding \${records:+--records "$records"} --query ${JSON.str
|
|
|
1434
1638
|
# session still starts (types just won't refresh).
|
|
1435
1639
|
set -euo pipefail
|
|
1436
1640
|
turbobase project types -o ${t} >/dev/null 2>&1 || echo "turbobase: types refresh skipped (not signed in?)" >&2
|
|
1437
|
-
${r}`}var
|
|
1438
|
-
`,
|
|
1641
|
+
${r}`}var Cy=JSON.stringify({hooks:{SessionStart:[{hooks:[{type:"command",command:"bash .claude/hooks/session-start-refresh-types.sh"}]}]}},null,2)+`
|
|
1642
|
+
`,zd="",Oy=t=>`node_modules/
|
|
1439
1643
|
|
|
1440
1644
|
# Holds a live personal access token (written by \`turbobase ${t?"apps":"project"} init\`).
|
|
1441
1645
|
.mcp.json
|
|
1442
1646
|
|
|
1443
1647
|
.DS_Store
|
|
1444
|
-
`;function
|
|
1445
|
-
`))r(i)}return n}async function
|
|
1446
|
-
`)}),n=e.sleep??
|
|
1447
|
-
`)},
|
|
1448
|
-
`)};function
|
|
1449
|
-
|
|
1450
|
-
`;await
|
|
1451
|
-
`);for(let n of r.slice(0,
|
|
1452
|
-
`)),x(
|
|
1453
|
-
`))}catch(
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
#
|
|
1464
|
-
# \u2500\u2500 One-time setup \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1465
|
-
# 1. Mint a \`releases:write\` PAT (you, in your TurboBase app):
|
|
1466
|
-
# Settings \u2192 Access tokens \u2192 "New token"
|
|
1467
|
-
# Scope: releases:write (the only scope this workflow needs)
|
|
1468
|
-
# Copy the token \u2014 it starts with \`tb_pat_\u2026\` and is shown only once.
|
|
1469
|
-
#
|
|
1470
|
-
# 2. Store the PAT as a GitHub Actions SECRET in this repo (you, in GitHub):
|
|
1471
|
-
# Repo \u2192 Settings \u2192 Secrets and variables \u2192 Actions \u2192 "New repository secret"
|
|
1472
|
-
# Name: TURBOBASE_RELEASE_PAT
|
|
1473
|
-
# Value: <the tb_pat_\u2026 token from step 1>
|
|
1474
|
-
# The PAT lives ONLY in your GitHub secret store. TurboBase never sees your
|
|
1475
|
-
# GitHub credentials, and you never paste a TurboBase secret into this file.
|
|
1476
|
-
#
|
|
1477
|
-
# 3. Store your instance base URL as a repo VARIABLE (not a secret \u2014 it isn't
|
|
1478
|
-
# sensitive) so the workflow knows which instance to deploy to:
|
|
1479
|
-
# Repo \u2192 Settings \u2192 Secrets and variables \u2192 Actions \u2192 Variables \u2192 "New"
|
|
1480
|
-
# Name: TURBOBASE_BASE_URL
|
|
1481
|
-
# Value: https://<your-slug>.turbobase.app
|
|
1482
|
-
#
|
|
1483
|
-
# 4. Put this file at \`.github/workflows/turbobase-release-deploy.yml\` (or run
|
|
1484
|
-
# \`turbobase project ci\`, which writes it there for you), commit, and merge.
|
|
1485
|
-
# The next merge to your default branch deploys.
|
|
1486
|
-
#
|
|
1487
|
-
# \u2500\u2500 What it deliberately does NOT do \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1488
|
-
# \u2022 No GitHub App, no installation token, no server-side clone \u2014 TurboBase
|
|
1489
|
-
# receives ONLY the bytes this checkout uploads.
|
|
1490
|
-
# \u2022 Defaults to \`--target auto\`. An approval-gated deploy is a guarded,
|
|
1491
|
-
# human-approved action (\`--target approved --approved-by you@co.com\`) and is
|
|
1492
|
-
# intentionally NOT wired to fire automatically on merge.
|
|
1493
|
-
# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1494
|
-
name: TurboBase release deploy
|
|
1495
|
-
|
|
1496
|
-
on:
|
|
1497
|
-
push:
|
|
1498
|
-
# Change \`main\` to your repo's default branch if it differs (e.g. master).
|
|
1499
|
-
branches: [main]
|
|
1500
|
-
|
|
1501
|
-
# Least privilege: this workflow only READS your checkout to upload it. It never
|
|
1502
|
-
# writes to your repo, and it does NOT use GITHUB_TOKEN to reach TurboBase \u2014 the
|
|
1503
|
-
# PAT secret is the only credential that leaves the runner.
|
|
1504
|
-
permissions:
|
|
1505
|
-
contents: read
|
|
1506
|
-
|
|
1507
|
-
# One deploy at a time per branch; a newer merge supersedes any in-flight run.
|
|
1508
|
-
concurrency:
|
|
1509
|
-
group: turbobase-release-\${{ github.ref }}
|
|
1510
|
-
cancel-in-progress: false
|
|
1511
|
-
|
|
1512
|
-
jobs:
|
|
1513
|
-
deploy:
|
|
1514
|
-
runs-on: ubuntu-latest
|
|
1515
|
-
steps:
|
|
1516
|
-
# The checkout IS the upload source. \`turbobase release deploy\` reads the
|
|
1517
|
-
# SDF project's src/ from this working tree and uploads those bytes;
|
|
1518
|
-
# nothing is fetched server-side.
|
|
1519
|
-
- name: Check out the merged commit
|
|
1520
|
-
uses: actions/checkout@v4
|
|
1521
|
-
|
|
1522
|
-
- name: Set up Node
|
|
1523
|
-
uses: actions/setup-node@v4
|
|
1524
|
-
with:
|
|
1525
|
-
node-version: '22'
|
|
1526
|
-
|
|
1527
|
-
# Install the \`turbobase\` CLI. The package is scoped; the command it
|
|
1528
|
-
# installs is plain \`turbobase\`. Pin a version (\`@turbobase/cli@1.2.3\`)
|
|
1529
|
-
# if you would rather CI not track the current release.
|
|
1530
|
-
- name: Install the turbobase CLI
|
|
1531
|
-
run: npm install -g @turbobase/cli
|
|
1532
|
-
|
|
1533
|
-
# Authenticate headlessly: store the PAT for this instance. The token is read
|
|
1534
|
-
# from the GitHub secret via env (never interpolated into the command line,
|
|
1535
|
-
# so it can't leak into the run logs).
|
|
1536
|
-
- name: Authenticate to TurboBase
|
|
1537
|
-
env:
|
|
1538
|
-
TURBOBASE_RELEASE_PAT: \${{ secrets.TURBOBASE_RELEASE_PAT }}
|
|
1539
|
-
run: |
|
|
1540
|
-
turbobase auth login \\
|
|
1541
|
-
--base-url "\${{ vars.TURBOBASE_BASE_URL }}" \\
|
|
1542
|
-
--token "$TURBOBASE_RELEASE_PAT"
|
|
1543
|
-
|
|
1544
|
-
# Ship it. \`--ref \${{ github.sha }}\` records the exact commit these bytes
|
|
1545
|
-
# were built from (a provenance LINK only \u2014 TurboBase never fetches it).
|
|
1546
|
-
# \`--project .\` uploads this checkout's SDF src/; \`--follow\` waits for the
|
|
1547
|
-
# server-side deploy job and fails the run if the deploy fails.
|
|
1548
|
-
- name: Deploy the release
|
|
1549
|
-
run: |
|
|
1550
|
-
turbobase release deploy \\
|
|
1551
|
-
--target auto \\
|
|
1552
|
-
--ref "\${{ github.sha }}" \\
|
|
1553
|
-
--project . \\
|
|
1554
|
-
--follow
|
|
1555
|
-
`;function Bd(){return[{path:vi,content:Qy}]}import ms from"node:fs/promises";import sn from"node:path";var _i={esbuild:"0.28.1","isolated-vm":"6.1.2"},Si="@turbobase/isolated-vm-prebuilds";function $i(t,e){return`${t}-${e}`}function ki(t=process.versions){return`abi${t.modules}`}var Fd=["darwin-x64","win32-arm64"];async function Hd(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=$i(e,r),s=sn.join(t.home,"node_modules"),o=sn.join(s,...Si.split("/"),"prebuilds",n),i=sn.join(s,"isolated-vm","prebuilds",n),a;try{a=await ms.readdir(o)}catch{return[]}let l=[];await ms.mkdir(i,{recursive:!0});for(let u of a){if(!u.endsWith(".node"))continue;let p=sn.join(i,u);try{await ms.copyFile(sn.join(o,u),p,ms.constants?.COPYFILE_EXCL??1),l.push(u)}catch{}}return l}import{homedir as Xy}from"node:os";import{join as Kd}from"node:path";import{promises as xi}from"node:fs";function Gd(){let t=process.env.TURBOBASE_HOME??Kd(Xy(),".turbobase");return{dir:t,file:Kd(t,"sandboxes.json")}}var eb={s:1e3,m:6e4,h:36e5,d:864e5};function tb(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*eb[e[2]]}function rb(t,e=Date.now()){return new Date(e+tb(t)).toISOString()}function nb(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function sb(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 ob(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 s=0;s<t.length;s+=r)n.push(t[s]);return n}var ib="[REDACTED]",on=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},Ti=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 ab(t,e,r){let n={};for(let[s,o]of Object.entries(e)){let i=r[s];if(i===void 0)throw new Ti(t,s,"column has no PII classification (unknown = unsafe)");i==="pii"?n[s]=o==null?o:ib:n[s]=o}return n}function cb(t,e,r){return e.map(n=>ab(t,n,r))}var Vd=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),lb=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function db(t){let e=t.trim();try{let s=new URL(e);if(s.hostname)return s.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 Ri(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 lb)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=db(t);if(!Vd.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...Vd].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function ub(t,e=pb){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function pb(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function fb(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function hb(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function Ei(){let{file:t}=Gd();try{let e=await xi.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function Wd(t){let{dir:e,file:r}=Gd();await xi.mkdir(e,{recursive:!0}),await xi.writeFile(r,`${JSON.stringify(t,null,2)}
|
|
1556
|
-
`,{mode:384})}async function mb(t){let e=await Ei();e.push(t),await Wd(e)}async function Jd(t){let e=await Ei(),r=e.findIndex(s=>s.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Wd(e),n??null}async function gs(){return Ei()}function Pi(t,e=Date.now()){let r=[],n=[];for(let s of t)nb(s.expiresAt,e)?n.push(s):r.push(s);return{active:r,expired:n}}async function Zd(t,e){Ri(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new on(r);let n=sb(e.sample),s=e.now??Date.now(),o=(e.nameGen??(u=>ub(u)))(e.fromTenant),i=fb(o);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let u of a){let p=ob(u.rows,n),d=cb(u.table,p,u.classification);d.length>0&&await t.copyRows(i,u.table,d)}let l={name:o,fromTenant:e.fromTenant,database:i,createdAt:new Date(s).toISOString(),expiresAt:rb(e.ttl,s),sampleFraction:n,url:hb(o,e.baseUrl)};return await mb(l),l}async function Yd(t,e){Ri(t.target());let n=(await gs()).find(s=>s.name===e);return n?(await t.dropDatabase(n.database),await Jd(e),n):null}async function Ai(t,e=Date.now()){Ri(t.target());let r=await gs(),{expired:n}=Pi(r,e),s=[];for(let o of n){try{await t.dropDatabase(o.database)}catch{continue}await Jd(o.name),s.push(o)}return s}var an={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","data:read"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},XR=Object.keys(an).filter(t=>an[t].mintable);var rE=an.pat.prefix,gb=Object.entries(an).map(([t,e])=>[e.prefix,t]),yb=/^[A-Za-z0-9_-]{20,}$/;function bb(t){if(typeof t!="string")return null;for(let[e,r]of gb)if(t.startsWith(e)&&yb.test(t.slice(e.length)))return r;return null}function Qd(t){return bb(t)==="pat"}var cn="bundle.json",ys="turbobase";function eu(t){let e;try{e=JSON.parse(t)}catch(l){throw new Error(`bundle.json is not valid JSON: ${l instanceof Error?l.message:String(l)}`)}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 s=l=>Array.isArray(l)?l:[],o=r.sync??{},i=r.guardrails??{},a={version:1,...typeof r.tenant=="string"?{tenant:r.tenant}:{},hooks:s(r.hooks),conduits:s(r.conduits),sync:{fields:s(o.fields),tables:s(o.tables)},guardrails:{validationHooks:s(i.validationHooks),fieldRules:s(i.fieldRules),conduits:s(i.conduits)},schedules:s(r.schedules)};return wb(a)}function wb(t){let e=r=>(n,s)=>r(n)<r(s)?-1:r(n)>r(s)?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(Xd)),tables:[...t.sync.tables].sort(e(r=>r.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(Xd)),conduits:[...t.guardrails.conduits].sort(e(r=>r.conduitId))},schedules:[...t.schedules].sort(e(r=>r.name))}}function Xd(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function tu(t,e){let r=(e??"").trim();if(!r)return{ok:!1,reason:"target instance slug is unknown \u2014 cannot confirm a promote"};let n=(t??"").trim();return n?n!==r?{ok:!1,reason:`--confirm "${n}" does not match the target instance "${r}" \u2014 refusing to apply`}:{ok:!0}:{ok:!1,reason:`--confirm <slug> is required for promote (expected "${r}")`}}async function j0(t,e){try{let r=await fetch(`${t.replace(/\/+$/,"")}/auth/pat-exchange`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)return null;let n=await r.json();return typeof n.token=="string"&&n.token.length>0?n.token:null}catch{return null}}async function z0(t){let e=await Rt();e.length===0&&k("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Jt()||k("this command needs an explicit <base-url> in a non-interactive shell.");try{return await Zt(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{k("cancelled.")}}async function L0(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(s){return{ok:!1,kind:"unreachable",detail:s instanceof Error?s.message:String(s)}}let n=(r.headers.get("content-type")??"").includes("application/json");return r.status===200||r.status===403?{ok:!0}:r.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${r.status}`}:n?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${r.status}`}}async function D0(t,e,r){let n=await Ql({baseUrl:t,token:e}),s=(await Rt()).length-1;if(x(`signed in to ${n.baseUrl} \u2014 now the active instance`+(s>0?` (${s} other${s===1?"":"s"} stored; commands default here).`:".")),!r)return;let o=await L0(n.baseUrl,e);o.ok||(o.kind==="wrong-host"?(ye(`warning: ${n.baseUrl} did not respond to the TurboBase API (/v1) \u2014 got ${o.detail}.`),ye(" In local dev the TurboBase API is on :4100, not the app dev-server port (e.g. :5173)."),ye(" The token is stored, but commands will fail against this base-url until it points at the API.")):o.kind==="bad-token"?ye(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):ye(`warning: could not reach ${n.baseUrl} to verify the token (${o.detail}). Stored anyway.`))}async function M0(t){let e=await Xr(t),r=l=>{let u=new RegExp(`${l}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(e);return u?u[2]:void 0},n=/\bdefineConduit\s*[<(]/.test(e),s=r("id");if(n){let l=r("on"),u=r("recordType"),p=r("source");return(!s||!u||!l||!p)&&k(`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`),{id:s,recordType:u,event:l,source:p,sourceCode:e,extensionKind:"conduit"}}let o=r("recordType"),i=r("event"),a=r("source")??"standalone";return(!s||!o||!i)&&k(`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`),{id:s,recordType:o,event:i,source:a,sourceCode:e,extensionKind:"hook"}}async function Hr(t,e,r,n){try{return await oe.access(t),"skipped"}catch{}return await oe.mkdir(Qn(t),{recursive:!0}),await oe.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await oe.chmod(t,n),"wrote"}async function Zm(t,e){if(Ym(t)!==".gitignore")return Hr(t,e.content,e.executable,e.mode);let r=await oe.readFile(t,"utf8").catch(()=>null);if(r===null)return Hr(t,e.content,e.executable,e.mode);let n=Pd(r);return n===null?"skipped":(await oe.writeFile(t,n,"utf8"),"merged")}function Rl(t){if(t!==void 0){if(t==="junit"||t==="json")return t;k(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function q0(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",s=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:s,type:n}})}}function U0(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 B0(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 Ol({includeInternal:t=!0}={}){let e=new N0;e.name("turbobase").description("Build apps, author extensions, and drive your TurboBase instance.").version("1.1.10").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",f=>f.command.parent?"":`${fi()}
|
|
1557
|
-
`),e.hook("preAction",(f,m)=>{Id(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."),s=e.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),o=e.command("kb").description("Write into the instance's knowledge base.");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 f=>{let m=Ve(f.baseUrl);f.token||k(`auth login needs --token. Mint a PAT in your TurboBase app (Settings \u203A Access tokens), then:
|
|
1558
|
-
${rn} auth login --base-url ${m} --token tb_pat_\u2026`),Qd(f.token)||k("--token does not look like a TurboBase PAT (tb_pat_\u2026)."),await D0(m,f.token,f.verify)}),r.command("status").description("Show the active instance (the no-`--base-url` default) and every stored sign-in.").action(async()=>{let f=await Rt();if(f.length===0){x("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`.");return}let m=await pt(),y=b=>!!m&&b.baseUrl===m.baseUrl;if(Me())x(tn(f.map(b=>[y(b)?R.green("*"):" ",R.bold(b.baseUrl),R.dim(b.updatedAt)]),{head:["","instance","updated"]}));else for(let b of f)x(`${y(b)?"* ":" "}${b.baseUrl} (updated ${b.updatedAt})`);m||ye("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}),r.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async f=>{let m=f??await z0("Pick the active instance:"),y=await is(m);if(!y){let b=await Rt();k(`no stored sign-in for ${Ve(m)}.`+(b.length?` Stored: ${b.map(S=>S.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${Ve(m)} --token tb_pat_\u2026\`.`)}x(`active instance \u2192 ${y.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 f=>{if(f.all){let b=await Rt();for(let S of b)await ri(S.baseUrl);x(`removed ${b.length} stored sign-in${b.length===1?"":"s"}.`);return}let m=await ri(f.baseUrl);m||k(f.baseUrl?`no stored sign-in for ${Ve(f.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let y=await pt();x(`signed out of ${m}.`+(y?` Active instance \u2192 ${y.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 f=>{let{baseUrl:m,token:y}=await le(f.baseUrl),b;try{b=await Tt({baseUrl:m,token:y,recordsOnly:f.recordsOnly})}catch(w){let $=w instanceof Error?w.message:String(w);if(!f.recordsOnly&&/openapi\.json failed \(401/.test($)){let E=await j0(m,y);if(E)try{b=await Tt({baseUrl:m,token:E,recordsOnly:!1});let A=ce(process.cwd(),f.out);await oe.writeFile(A,b,"utf8"),x(`wrote ${A} (${b.split(`
|
|
1559
|
-
`).length} lines).`);return}catch{}ye("types-gen: /v1/catalog/openapi.json needs a session \u2014 emitting record shapes only. To get the OpenAPI half headlessly, mint a PAT with the `data:read` scope (Settings \u203A Tokens); the CLI then exchanges it for a short-lived session automatically.");try{b=await Tt({baseUrl:m,token:y,recordsOnly:!0})}catch(A){k(`types generation failed: ${A instanceof Error?A.message:String(A)}`)}}else k(`types generation failed: ${$}`)}let S=ce(process.cwd(),f.out);await oe.writeFile(S,b,"utf8"),x(`wrote ${S} (${b.split(`
|
|
1560
|
-
`).length} lines).`)}),Od(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 f=>{let{baseUrl:m,token:y}=await le(f.baseUrl),b=new URLSearchParams;f.records&&b.set("records",f.records),f.query&&b.set("query",f.query);let S=b.toString(),w=await fetch(`${m}/v1/catalog/grounding${S?`?${S}`:""}`,{headers:{Authorization:`Bearer ${y}`,Accept:"application/json"}});w.ok||k(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${w.status}`);let E=((await w.json()).markdown??"").trim(),A=ce(process.cwd(),f.out),I=f.records?` records=${f.records}`:"",C=`<!-- GENERATED by \`turbobase project grounding\` against ${m}${I} \u2014 do not edit; re-run to refresh. -->
|
|
1561
|
-
|
|
1562
|
-
`;await oe.writeFile(A,C+(E?`${E}
|
|
1648
|
+
`;function Si(t={}){let e=Sy.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",s=r?{slug:t.appSlug}:void 0,o=[{path:".mcp.json",content:e,mode:384},{path:".gitignore",content:Oy(r)},{path:"INSTANCE-LEARNINGS.md",content:Py(s)},{path:"TURBOBASE-FEEDBACK.md",content:Ay(s)},{path:".claude/settings.json",content:Cy},{path:".claude/skills/generate-types/SKILL.md",content:_y(n)},{path:".claude/skills/record-learning/SKILL.md",content:Ey(s)},{path:".claude/hooks/session-start-refresh-types.sh",content:Iy(n,s),executable:!0}];return r?[{path:"CLAUDE.md",content:xy(t.appSlug)},...o,{path:".claude/skills/preview-app/SKILL.md",content:Ty},{path:".claude/skills/ship-app/SKILL.md",content:Ry},...jd()]:[{path:"CLAUDE.md",content:vy},...o,{path:".claude/skills/mock-test/SKILL.md",content:$y},{path:".claude/skills/deploy/SKILL.md",content:ky},{path:"hooks/.gitkeep",content:zd},{path:"samples/.gitkeep",content:zd}]}import{promises as qd}from"node:fs";import{resolve as Ly}from"node:path";ls();mr();var Ny=t=>new Promise(e=>setTimeout(e,t));function Ud(t){return t.stage==="completed"||t.stage==="failed"}function jy(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function zy(t,e,r){let n=t.outputTail??"";if(n&&n!==e){let o=(n.startsWith(e)?n.slice(e.length):n).replace(/\n+$/,"");if(o)for(let i of o.split(`
|
|
1649
|
+
`))r(i)}return n}async function _i(t,e={}){let r=e.sink??(v=>{process.stdout.write(`${v}
|
|
1650
|
+
`)}),n=e.sleep??Ny,s=e.intervalMs??2e3,o=e.maxPolls??Number.POSITIVE_INFINITY,i=e.onStage??(v=>r(jy(v))),a=e.onPoll,l="",d="",u=v=>{a?.(v),v.stage!==d&&i(v),l=zy(v,l,r),d=v.stage},h=await t();if(u(h),Ud(h))return h;for(let v=0;v<o;v+=1)if(await n(s),h=await t(),u(h),Ud(h))return h;return h}var x=t=>{process.stdout.write(`${t}
|
|
1651
|
+
`)},pe=t=>{process.stderr.write(`${t}
|
|
1652
|
+
`)};function T(t){pe(k.red(`turbobase: ${t}`)),process.exit(1)}var rn=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function Dd(t,e){let r=e.json===!0||typeof e.reporter=="string";(t.color===!1||r)&&gi(!1)}async function V(t){let e=await ht(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let r=await Ct();if(t){let n=r.length?` Stored instances: ${r.map(s=>s.baseUrl).join(", ")}.`:"";T(`not signed in to ${Ge(t)}.${n} Run \`turbobase auth login --base-url ${Ge(t)} --token tb_pat_\u2026\`.`)}if(r.length===0&&T("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),_t())try{let n=await $t("Multiple instances stored \u2014 pick the active one:",r.map(o=>({value:o.baseUrl,label:o.baseUrl,description:`updated ${o.updatedAt}`})));await cs(n);let s=await ht();if(s)return{baseUrl:s.baseUrl,token:s.token}}catch{}T(`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 ye(t,e,r){if(!(t instanceof ue)||t.status!==403)return;t.body?.error==="approval_required"&&T(`${r} denied (403): an approval-gated deploy needs a recorded approval \u2014 pass --approved-by <email>.`),T(`${r} forbidden (403) \u2014 the stored PAT lacks the '${e}' scope. Re-run \`turbobase auth login\` with a token that has it.`)}async function $i(t,e,r){let n=r?Number(r):void 0;if(ms()){let o=bi(e),i;try{i=await _i(t,{intervalMs:n,sink:a=>o.log(a),onStage:()=>{},onPoll:a=>o.status({stage:a.stage,percent:a.percent??void 0,runStatus:a.runStatus??void 0})})}catch(a){o.stop(),T(`${e} --follow failed: ${a instanceof Error?a.message:String(a)}`)}o.done({stage:i.stage,percent:i.percent??void 0,runStatus:i.runStatus??void 0}),i.stage==="failed"&&process.exit(1);return}let s;try{s=await _i(t,{sink:x,intervalMs:n})}catch(o){T(`${e} --follow failed: ${o instanceof Error?o.message:String(o)}`)}s.stage==="failed"&&T(`${e} failed${s.runStatus?` (${s.runStatus})`:""}.`),x(`${e} ${s.stage}.`)}var Uy=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function Dy(t){try{let e=await qd.readFile(t,"utf8");return Uy.exec(e)?.[1]??null}catch{return null}}function Md(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 V(e.baseUrl),s=Ly(process.cwd(),e.out),o=e.since?.trim()||await Dy(s),i=new URLSearchParams;o&&i.set("since",o);let a=i.toString(),l=await fetch(`${r}/v1/catalog/adopt-notes${a?`?${a}`:""}`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/json"}});l.ok||T(`adopt fetch failed: GET /v1/catalog/adopt-notes \u2192 ${l.status}`);let d=await l.json();if(!d.available){x(`${r} ships no release notes to adopt from (nothing written).`);return}let u=d.releases.reduce((g,w)=>g+w.items.length,0);if(u===0){x(`up to date${o?` since v${o.replace(/^v/,"")}`:""}${d.currentVersion?` (instance is on v${d.currentVersion})`:""} \u2014 ${s} left untouched.`);return}let h=d.currentVersion??d.releases[0]?.version??"",v=`<!-- GENERATED by \`turbobase project adopt\` against ${r} \u2014 adopted-through=${h}. Re-run to refresh; delete this file once every line is done. -->
|
|
1653
|
+
|
|
1654
|
+
`;await qd.writeFile(s,v+d.markdown,"utf8"),x(`wrote ${s} \u2014 ${u} item(s) across ${d.releases.length} release(s)${o?` since v${o.replace(/^v/,"")}`:""}.`)})}mr();var nn=["suggested_kb_edit","kb_correction"];var qy=[{heading:"Suggested KB edits",section:"suggested_kb_edit",ranked:!1},{heading:"Knowledge-base corrections",section:"kb_correction",ranked:!1},{heading:"What would have helped most, in order",section:"platform_feedback",ranked:!0},{heading:"Agent rules",section:"agent_rule",ranked:!1}];function My(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var ZR=new Map(qy.map(t=>[My(t.heading),t]));function By(t){return t.diff??!!t.dryRun}var Fy={update_page:"append to the existing page",new_page:"create a NEW page"},kt=(t,e)=>` ${k.dim(t.padEnd(11))}${e}`,Fd=t=>t.ownerEmail??t.ownerId,gs=t=>k.green(t?` + ${t}`:" +"),Hy=t=>k.red(t?` - ${t}`:" -"),Xt=t=>k.dim(` ${t}`),Ky=` ${k.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,ki=80;function Vy(t){let e=[Ky];t.target?(e.push(Xt(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(Hy(`visibility: ${t.target.visibility}`)),e.push(gs("visibility: admin"))):e.push(Xt(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(Xt("title, slug, evidence: untouched")),e.push(Xt("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(Xt("turbobase.document \xB7 new")),e.push(gs(`title: ${t.pageTitle}`)),e.push(gs("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(Xt('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(Xt('appended under "## From app developers":'));let r=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
|
|
1655
|
+
`);for(let n of r.slice(0,ki))e.push(gs(n?` ${n}`:""));return r.length>ki&&e.push(k.yellow(` \u2026 ${r.length-ki} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function Gy(t,e={}){let r=[];return t.forEach((n,s)=>{let{target:o,entries:i}=n;if(r.push(`${String(s+1).padStart(2)}. ${k.bold(n.pageTitle)}`),r.push(kt("page",o?`${o.title} (${o.slug}) [${o.visibility}]`:k.dim("new \u2014 no existing page matches"))),r.push(kt("action",n.needsPageRef?k.red("SKIP \u2014 nothing is written"):Fy[n.action])),n.needsPageRef){let a=[...new Set(i.map(l=>l.kb_page_ref?.trim()).filter(l=>!!l))];r.push(kt("unresolved",k.red((a.length>0?`no page matches ${a.map(l=>`"${l}"`).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(kt("findings",`${i.length} ${i.length===1?"finding":"findings"} from ${[...new Set(i.map(a=>a.app_slug))].join(", ")}`)),i.forEach(a=>{let l=a.verdict?` ${k.dim(`\xB7 ${a.verdict}`)}`:"",d=a.kb_page_ref?` ${k.dim(`(${a.kb_page_ref})`)}`:"";r.push(` ${k.dim("\xB7")} ${a.title.trim()}${d}${l}`)}),r.push(kt("confidence",n.withdraws?k.red("WITHDRAWN from readers (text untouched)"):k.dim("untouched"))),n.supersedes&&r.push(kt("supersedes",k.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(kt("blocked",k.red(`unpublished work on this page belongs to ${Fd(n.blockedBy)} \u2014 this page will be SKIPPED`))),n.alsoMatched.length>0&&r.push(kt("ambiguous",k.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(l=>{let d=t.findIndex(h=>h.key===l),u=d>=0?t[d]:void 0;return u?`#${d+1} "${u.pageTitle}"`:l});r.push(kt("similar",k.yellow(`this new page looks related to ${a.join(", ")} \u2014 nothing was merged. If they are one page, push one now and re-run: the rest will resolve onto it.`)))}e.diff&&!n.needsPageRef&&r.push(...Vy(n)),r.push("")}),r}function Wy(t){let e=d=>t.filter(d).length,r=t.reduce((d,u)=>d+u.entries.length,0),n=e(d=>d.withdraws),s=e(d=>d.blockedBy!=null),o=e(d=>d.needsPageRef),i=[`${r} finding${r===1?"":"s"}`,`${t.length-o} page(s)`,`${e(d=>d.action==="update_page"&&!d.needsPageRef)} appended`,`${e(d=>d.action==="new_page"&&!d.needsPageRef)} created (unpublished)`,...o>0?[k.red(`${o} SKIPPED \u2014 correction with no page to correct`)]:[]],a=n>0?k.red(`${n} page(s) WITHDRAWN from readers`):k.dim("no page withdrawn"),l=s>0?` \xB7 ${k.red(`${s} page(s) BLOCKED by another editor`)}`:"";return`${i.join(" \xB7 ")} \xB7 ${a}${l}`}function Jy(t,e){let r=new Map(e.map(s=>[s.key,s])),n=[];for(let s of t){let o=r.get(s.key),i=s.pageTitle||o?.pageTitle||s.key;if(s.skipped==="blocked_by_draft_owner"){n.push(`${k.yellow("skipped")} ${i} \u2014 unpublished work belongs to ${s.blockedBy?Fd(s.blockedBy):"another editor"}; its findings stay pending`);continue}if(s.skipped==="unresolved_page_ref"){let l=[...new Set((o?.entries??[]).map(d=>d.kb_page_ref?.trim()).filter(d=>!!d))];n.push(`${k.yellow("skipped")} ${i} \u2014 `+(l.length>0?`no page matches ${l.map(d=>`"${d}"`).join(", ")}`:"the correction names no page")+"; nothing was written and its findings stay pending");continue}if(s.skipped){n.push(`${k.yellow("skipped")} ${i} \u2014 ${s.skipped.replace(/_/g," ")}`);continue}let a=s.created?k.green("created "):k.green("appended");n.push(`${a} ${i} \u2014 ${s.appliedEntryIds.length} finding(s) \u2192 page ${k.bold(s.documentId??"?")}`+(s.created?k.dim(" (unpublished)"):"")),s.confidence==="downgraded"?n.push(` ${k.red("withdrawn from readers:")} ${i}`):s.confidence==="already_withdrawn"?n.push(` ${k.dim("page was already unpublished \u2014 left as is")}`):s.confidence==="missing"&&n.push(` ${k.yellow("page vanished between plan and push \u2014 nothing withdrawn")}`)}return n}function Bd(t){if(t instanceof ue){let e=t.body;t.status===403&&e?.reason==="admin_required"&&T("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&&T("this instance does not serve /v1/learnings \u2014 it predates the app-developer learning loop. Ask for an instance upgrade.")}ye(t,"extensions:deploy","learnings push-kb")}async function Hd(t,e=r=>new K(r)){t.section&&!nn.includes(t.section.trim())&&T(`unknown --section "${t.section}" \u2014 expected one of ${nn.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&T("--limit must be a positive integer.");let r=await V(t.baseUrl),n=e(r),s={...t.app?{app:t.app}:{},...t.section?{section:t.section.trim()}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{}},o;try{o=await le("reading the pending queue",()=>n.learningsPending(s))}catch(l){Bd(l),T(`could not read the pending queue: ${l instanceof Error?l.message:String(l)}`)}if(o.items.length===0){pe(o.pendingTotal===0?"nothing pending \u2014 no ingested findings are waiting on a knowledge-base decision.":`nothing matched \u2014 ${o.pendingTotal} pending finding(s) exist but not under these filters.`);return}if(x(Gy(o.items,{diff:By(t)}).join(`
|
|
1656
|
+
`)),x(Wy(o.items)),t.dryRun){pe(k.dim("dry run \u2014 nothing was written."));return}let i=o.items.filter(l=>!l.needsPageRef);if(i.length===0){pe(k.yellow(`nothing to write \u2014 all ${o.items.length} group(s) are corrections with no page to correct. Fix the refs above (or write the pages) and re-run; the findings stay pending.`));return}let a=i.reduce((l,d)=>l+d.entries.length,0);if(!t.yes){if(!_t()){pe(k.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 $t(`Push ${a} finding(s) into the knowledge base as ${i.length} page(s)?`,[{value:"yes",label:"Yes \u2014 push to the knowledge base",description:"pages land unpublished; corrections withdraw the pages listed above"},{value:"no",label:"No \u2014 leave the queue untouched"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){pe("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{let l=await le("writing pages",()=>n.learningsPushKb(o.planToken,s));x(Jy(l.applied,o.items).join(`
|
|
1657
|
+
`))}catch(l){if(l instanceof ue&&l.status===409){pe(k.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),pe(`re-run \`${rn} kb push\` to review the current plan.`),process.exitCode=2;return}Bd(l),pe(k.red(`turbobase: ${l instanceof Error?l.message:String(l)}`)),process.exitCode=2}}mr();function Zy(t){return t.diff??!!t.dryRun}function Yy(t,e){let r=[];return t.forEach((n,s)=>{let o=n.action==="new_rule"?k.green("new rule"):k.yellow("amend rule"),i=n.targetPublished?` ${k.yellow("[currently live]")}`:"";r.push(`${s+1}. ${o} ${k.bold(n.slug)}${i}`),r.push(` ${n.name}`);for(let a of n.entries)r.push(` ${k.dim("\xB7")} ${k.dim(a.app_slug)} ${a.title}`);if(e.diff){r.push("");for(let a of n.bodyMarkdown.split(`
|
|
1658
|
+
`))r.push(` ${k.dim("|")} ${a}`)}r.push("")}),r}function Qy(t){let e=t.reduce((s,o)=>s+o.entries.length,0),r=t.filter(s=>s.targetPublished).length,n=[`${e} finding(s) \u2192 ${t.length} rule(s)`];return r>0&&n.push(k.yellow(`${r} amend a rule that is currently live`)),n.join(" \xB7 ")}async function Kd(t,e=r=>new K(r)){t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&T("--limit must be a positive integer.");let r=await V(t.baseUrl),n=e(r),s={...t.app?{app:t.app}:{},...t.limit!==void 0?{limit:t.limit}:{}},o;try{o=await le("reading the pending rules",()=>n.rulesPending(s))}catch(a){ye(a,"extensions:deploy","read the pending rules"),T(`could not read the pending queue: ${a instanceof Error?a.message:String(a)}`)}if(o.items.length===0){pe(o.pendingTotal===0?"nothing pending \u2014 no findings are waiting under `## Agent rules`.":`nothing matched \u2014 ${o.pendingTotal} pending rule finding(s) exist but not under these filters.`);return}if(x(Yy(o.items,{diff:Zy(t)}).join(`
|
|
1659
|
+
`)),x(Qy(o.items)),t.dryRun){pe(k.dim("dry run \u2014 nothing was written."));return}let i=o.items.reduce((a,l)=>a+l.entries.length,0);if(!t.yes){if(!_t()){pe(k.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 $t(`Push ${i} finding(s) as ${o.items.length} draft rule(s)?`,[{value:"yes",label:"Yes \u2014 write them as draft rules",description:"they land DISABLED; an admin publishes them before anything is injected"},{value:"no",label:"No \u2014 leave the queue untouched"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){pe("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{await le("writing the rules",()=>n.rulesPush(o.planToken,s))}catch(a){a instanceof ue&&a.status===409&&T("the pending queue changed while you were reading the plan \u2014 nothing was written. Re-run to see the new plan."),T(`push failed: ${a instanceof Error?a.message:String(a)}`)}x(k.green(`wrote ${o.items.length} draft rule(s).`)),pe(k.dim("They are DRAFT and DISABLED \u2014 nothing is injected yet. An admin reviews and publishes them under Settings \u203A Skills."))}import{promises as Vd}from"node:fs";import{join as Xy,relative as eb,resolve as tb,sep as rb}from"node:path";var nb=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),sb=new Set([".mcp.json",".env"]);function ob(t){return sb.has(t)||t.startsWith(".env.")&&t!==".env.example"}function ib(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function ab(t){return t.includes(0)}async function Gd(t){let e=tb(t),r={},n=[],s=[],o=[];async function i(a){let l=await Vd.readdir(a,{withFileTypes:!0});for(let d of l){let u=Xy(a,d.name);if(d.isDirectory()){if(nb.has(d.name))continue;await i(u);continue}if(!d.isFile())continue;let h=eb(e,u).split(rb).join("/");if(ob(d.name)){s.push(h);continue}let v=await Vd.readFile(u);if(!ib(v)){n.push(h);continue}ab(v)&&o.push(h),r[h]=v.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:s,unstorable:o}}import{randomBytes as cb}from"node:crypto";var lb="/_tb/app-assets",db=16,ub=/^[0-9a-f]{32}$/;function Wd(){return cb(db).toString("hex")}function pb(t){return ub.test(t)}function Jd(t){if(!pb(t))throw new Error(`not a build id: ${t}`);return`${lb}/${t}/`}var Zd=7;import ys from"node:fs/promises";import sn from"node:path";var xi={esbuild:"0.28.1","isolated-vm":"6.1.2"},Ti="@turbobase/isolated-vm-prebuilds";function Ri(t,e){return`${t}-${e}`}function Ei(t=process.versions){return`abi${t.modules}`}var Yd=["darwin-x64","win32-arm64"];async function Qd(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=Ri(e,r),s=sn.join(t.home,"node_modules"),o=sn.join(s,...Ti.split("/"),"prebuilds",n),i=sn.join(s,"isolated-vm","prebuilds",n),a;try{a=await ys.readdir(o)}catch{return[]}let l=[];await ys.mkdir(i,{recursive:!0});for(let d of a){if(!d.endsWith(".node"))continue;let u=sn.join(i,d);try{await ys.copyFile(sn.join(o,d),u,ys.constants?.COPYFILE_EXCL??1),l.push(d)}catch{}}return l}import{homedir as fb}from"node:os";import{join as Xd}from"node:path";import{promises as Pi}from"node:fs";function tu(){let t=process.env.TURBOBASE_HOME??Xd(fb(),".turbobase");return{dir:t,file:Xd(t,"sandboxes.json")}}var hb={s:1e3,m:6e4,h:36e5,d:864e5};function mb(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*hb[e[2]]}function gb(t,e=Date.now()){return new Date(e+mb(t)).toISOString()}function yb(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function bb(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 wb(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 s=0;s<t.length;s+=r)n.push(t[s]);return n}var vb="[REDACTED]",on=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},Ai=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 Sb(t,e,r){let n={};for(let[s,o]of Object.entries(e)){let i=r[s];if(i===void 0)throw new Ai(t,s,"column has no PII classification (unknown = unsafe)");i==="pii"?n[s]=o==null?o:vb:n[s]=o}return n}function _b(t,e,r){return e.map(n=>Sb(t,n,r))}var eu=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),$b=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function kb(t){let e=t.trim();try{let s=new URL(e);if(s.hostname)return s.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 Ii(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 $b)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=kb(t);if(!eu.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...eu].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function xb(t,e=Tb){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function Tb(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function Rb(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function Eb(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function Ci(){let{file:t}=tu();try{let e=await Pi.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function ru(t){let{dir:e,file:r}=tu();await Pi.mkdir(e,{recursive:!0}),await Pi.writeFile(r,`${JSON.stringify(t,null,2)}
|
|
1660
|
+
`,{mode:384})}async function Pb(t){let e=await Ci();e.push(t),await ru(e)}async function nu(t){let e=await Ci(),r=e.findIndex(s=>s.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await ru(e),n??null}async function bs(){return Ci()}function Oi(t,e=Date.now()){let r=[],n=[];for(let s of t)yb(s.expiresAt,e)?n.push(s):r.push(s);return{active:r,expired:n}}async function su(t,e){Ii(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new on(r);let n=bb(e.sample),s=e.now??Date.now(),o=(e.nameGen??(d=>xb(d)))(e.fromTenant),i=Rb(o);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let d of a){let u=wb(d.rows,n),h=_b(d.table,u,d.classification);h.length>0&&await t.copyRows(i,d.table,h)}let l={name:o,fromTenant:e.fromTenant,database:i,createdAt:new Date(s).toISOString(),expiresAt:gb(e.ttl,s),sampleFraction:n,url:Eb(o,e.baseUrl)};return await Pb(l),l}async function ou(t,e){Ii(t.target());let n=(await bs()).find(s=>s.name===e);return n?(await t.dropDatabase(n.database),await nu(e),n):null}async function Ni(t,e=Date.now()){Ii(t.target());let r=await bs(),{expired:n}=Oi(r,e),s=[];for(let o of n){try{await t.dropDatabase(o.database)}catch{continue}await nu(o.name),s.push(o)}return s}var an={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","data:read"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},wE=Object.keys(an).filter(t=>an[t].mintable);var _E=an.pat.prefix,Ab=Object.entries(an).map(([t,e])=>[e.prefix,t]),Ib=/^[A-Za-z0-9_-]{20,}$/;function Cb(t){if(typeof t!="string")return null;for(let[e,r]of Ab)if(t.startsWith(e)&&Ib.test(t.slice(e.length)))return r;return null}function iu(t){return Cb(t)==="pat"}var cn="bundle.json",ws="turbobase";function cu(t){let e;try{e=JSON.parse(t)}catch(l){throw new Error(`bundle.json is not valid JSON: ${l instanceof Error?l.message:String(l)}`)}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 s=l=>Array.isArray(l)?l:[],o=r.sync??{},i=r.guardrails??{},a={version:1,...typeof r.tenant=="string"?{tenant:r.tenant}:{},hooks:s(r.hooks),conduits:s(r.conduits),sync:{fields:s(o.fields),tables:s(o.tables)},guardrails:{validationHooks:s(i.validationHooks),fieldRules:s(i.fieldRules),conduits:s(i.conduits)},schedules:s(r.schedules)};return Ob(a)}function Ob(t){let e=r=>(n,s)=>r(n)<r(s)?-1:r(n)>r(s)?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(au)),tables:[...t.sync.tables].sort(e(r=>r.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(au)),conduits:[...t.guardrails.conduits].sort(e(r=>r.conduitId))},schedules:[...t.schedules].sort(e(r=>r.name))}}function au(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function lu(t,e){let r=(e??"").trim();if(!r)return{ok:!1,reason:"target instance slug is unknown \u2014 cannot confirm a promote"};let n=(t??"").trim();return n?n!==r?{ok:!1,reason:`--confirm "${n}" does not match the target instance "${r}" \u2014 refusing to apply`}:{ok:!0}:{ok:!1,reason:`--confirm <slug> is required for promote (expected "${r}")`}}async function ZT(t,e){try{let r=await fetch(`${t.replace(/\/+$/,"")}/auth/pat-exchange`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)return null;let n=await r.json();return typeof n.token=="string"&&n.token.length>0?n.token:null}catch{return null}}async function YT(t){let e=await Ct();e.length===0&&T("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),_t()||T("this command needs an explicit <base-url> in a non-interactive shell.");try{return await $t(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{T("cancelled.")}}async function QT(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(s){return{ok:!1,kind:"unreachable",detail:s instanceof Error?s.message:String(s)}}let n=(r.headers.get("content-type")??"").includes("application/json");return r.status===200||r.status===403?{ok:!0}:r.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${r.status}`}:n?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${r.status}`}}async function XT(t,e,r){let n=await sd({baseUrl:t,token:e}),s=(await Ct()).length-1;if(x(`signed in to ${n.baseUrl} \u2014 now the active instance`+(s>0?` (${s} other${s===1?"":"s"} stored; commands default here).`:".")),!r)return;let o=await QT(n.baseUrl,e);o.ok||(o.kind==="wrong-host"?(pe(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${o.detail}.`),pe(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),pe(" The token is stored, but commands will fail against this base-url until it points at the API.")):o.kind==="bad-token"?pe(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):pe(`warning: could not reach ${n.baseUrl} to verify the token (${o.detail}). Stored anyway.`))}async function e0(t){let e=await en(t),r=l=>{let d=new RegExp(`${l}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(e);return d?d[2]:void 0},n=/\bdefineConduit\s*[<(]/.test(e),s=r("id");if(n){let l=r("on"),d=r("recordType"),u=r("source");return(!s||!d||!l||!u)&&T(`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`),{id:s,recordType:d,event:l,source:u,sourceCode:e,extensionKind:"conduit"}}let o=r("recordType"),i=r("event"),a=r("source")??"standalone";return(!s||!o||!i)&&T(`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`),{id:s,recordType:o,event:i,source:a,sourceCode:e,extensionKind:"hook"}}async function Kr(t,e,r,n){try{return await ce.access(t),"skipped"}catch{}return await ce.mkdir(Qn(t),{recursive:!0}),await ce.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await ce.chmod(t,n),"wrote"}async function ng(t,e){if(sg(t)!==".gitignore")return Kr(t,e.content,e.executable,e.mode);let r=await ce.readFile(t,"utf8").catch(()=>null);if(r===null)return Kr(t,e.content,e.executable,e.mode);let n=Ld(r);return n===null?"skipped":(await ce.writeFile(t,n,"utf8"),"merged")}function Il(t){if(t!==void 0){if(t==="junit"||t==="json")return t;T(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function t0(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",s=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:s,type:n}})}}function r0(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 n0(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 Ll({includeInternal:t=!0}={}){let e=new JT;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.1.12").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",p=>p.command.parent?"":`${yi()}
|
|
1661
|
+
`),e.hook("preAction",(p,f)=>{Dd(e.opts(),f.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."),s=e.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),o=e.command("kb").description("Write into the instance's knowledge base."),i=e.command("skills").description("Write standing rules into the instance's agent skills.");r.command("login").description("Sign in to an instance by pasting a personal access token (PAT), stored in ~/.turbobase/credentials.").requiredOption("--base-url <url>","Instance base URL, e.g. https://acme.turbobase.app").option("--token <tb_pat_\u2026>","The PAT to store. Mint one in your app under Settings \u203A Access tokens.").option("--no-verify","Skip the post-login connectivity/token probe.").action(async p=>{let f=Ge(p.baseUrl);p.token||T(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
|
|
1662
|
+
${rn} auth login --base-url ${f} --token tb_pat_\u2026`),iu(p.token)||T("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await XT(f,p.token,p.verify)}),r.command("status").description("Show the active instance (the no-`--base-url` default) and every stored sign-in.").action(async()=>{let p=await Ct();if(p.length===0){x("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`.");return}let f=await ht(),y=b=>!!f&&b.baseUrl===f.baseUrl;if(qe())x(Qt(p.map(b=>[y(b)?k.green("*"):" ",k.bold(b.baseUrl),k.dim(b.updatedAt)]),{head:["","instance","updated"]}));else for(let b of p)x(`${y(b)?"* ":" "}${b.baseUrl} (updated ${b.updatedAt})`);f||pe("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}),r.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async p=>{let f=p??await YT("Pick the active instance:"),y=await cs(f);if(!y){let b=await Ct();T(`no stored sign-in for ${Ge(f)}.`+(b.length?` Stored: ${b.map(_=>_.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${Ge(f)} --token tb_pat_\u2026\`.`)}x(`active instance \u2192 ${y.baseUrl}.`)}),r.command("logout").description("Remove a stored sign-in (defaults to the active instance).").option("--base-url <url>","Which instance to remove (defaults to the active/single one).").option("--all","Remove every stored sign-in.").action(async p=>{if(p.all){let b=await Ct();for(let _ of b)await ii(_.baseUrl);x(`removed ${b.length} stored sign-in${b.length===1?"":"s"}.`);return}let f=await ii(p.baseUrl);f||T(p.baseUrl?`no stored sign-in for ${Ge(p.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let y=await ht();x(`signed out of ${f}.`+(y?` Active instance \u2192 ${y.baseUrl}.`:""))}),n.command("types").description("Generate types.ts from the signed-in instance's catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("-o, --out <file>","Output file","types.ts").option("--records-only","Emit only record-shape interfaces (skip the OpenAPI half).").action(async p=>{let{baseUrl:f,token:y}=await V(p.baseUrl),b;try{b=await It({baseUrl:f,token:y,recordsOnly:p.recordsOnly})}catch(m){let S=m instanceof Error?m.message:String(m);if(!p.recordsOnly&&/openapi\.json failed \(401/.test(S)){let P=await ZT(f,y);if(P)try{b=await It({baseUrl:f,token:P,recordsOnly:!1});let I=ae(process.cwd(),p.out);await ce.writeFile(I,b,"utf8"),x(`wrote ${I} (${b.split(`
|
|
1663
|
+
`).length} lines).`);return}catch{}pe("types-gen: /v1/catalog/openapi.json needs a session \u2014 emitting record shapes only. To get the OpenAPI half headlessly, mint a PAT with the `data:read` scope (Settings \u203A Tokens); the CLI then exchanges it for a short-lived session automatically.");try{b=await It({baseUrl:f,token:y,recordsOnly:!0})}catch(I){T(`types generation failed: ${I instanceof Error?I.message:String(I)}`)}}else T(`types generation failed: ${S}`)}let _=ae(process.cwd(),p.out);await ce.writeFile(_,b,"utf8"),x(`wrote ${_} (${b.split(`
|
|
1664
|
+
`).length} lines).`)}),Md(n),n.command("grounding").description("Write the instance's grounding brief (source primer + record anatomy + KB retrieval) to a file for agent sessions.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--records <list>","Comma-separated record types to focus, e.g. purchaseOrder,itemReceipt.").option("--query <text>","Retrieval question for the knowledge base (e.g. what the app is about).").option("-o, --out <file>","Output file","INSTANCE.md").action(async p=>{let{baseUrl:f,token:y}=await V(p.baseUrl),b=new URLSearchParams;p.records&&b.set("records",p.records),p.query&&b.set("query",p.query);let _=b.toString(),m=await fetch(`${f}/v1/catalog/grounding${_?`?${_}`:""}`,{headers:{Authorization:`Bearer ${y}`,Accept:"application/json"}});m.ok||T(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${m.status}`);let P=((await m.json()).markdown??"").trim(),I=ae(process.cwd(),p.out),C=p.records?` records=${p.records}`:"",O=`<!-- GENERATED by \`turbobase project grounding\` against ${f}${C} \u2014 do not edit; re-run to refresh. -->
|
|
1665
|
+
|
|
1666
|
+
`;await ce.writeFile(I,O+(P?`${P}
|
|
1563
1667
|
`:`(no grounding available yet)
|
|
1564
|
-
`),"utf8"),x(`wrote ${
|
|
1565
|
-
${E===0?R.green(A):R.yellow(A)}`),E>0&&process.exit(1)}),s.command("deploy").argument("[file]","The extension file to deploy (single-file mode; omit with --to).").description("Deploy one extension (POST /v1/extensions) or the whole bundle (--to \u2192 /v1/config/apply).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--to <env>","Deploy the WHOLE bundle (turbobase/bundle.json) to this env (sandbox|prod).").action(async(f,m)=>{if(m.to){let $=await El(),{baseUrl:E,token:A}=await le(m.baseUrl),I=new ae({baseUrl:E,token:A});try{let C=await me(`applying bundle to ${m.to}`,()=>I.configApply($));x(`applied bundle to ${m.to}: +${C.applied.add} ~${C.applied.change} -${C.applied.destroy}`+(C.backfillsQueued.length?` (${C.backfillsQueued.length} backfill(s) queued)`:""))}catch(C){C instanceof pe&&C.status===403&&k("apply forbidden (403) \u2014 the stored PAT is not for an admin."),k(`bundle apply failed: ${C instanceof Error?C.message:String(C)}`)}return}f||k("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:y,token:b}=await le(m.baseUrl),S=await M0(ce(process.cwd(),f)),w=new ae({baseUrl:y,token:b});try{let $=await me(`deploying ${Ym(f)}`,()=>w.deploy(S));Me()?x(Pt("Deployed",[`${R.bold($.id)} ${mr($.status)} ${R.dim($.outcome)}`])):x(`deployed ${$.id} \u2192 status=${$.status} (${$.outcome}).`)}catch($){$ instanceof pe&&$.status===403&&k("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),k(`deploy failed: ${$ instanceof Error?$.message:String($)}`)}});let a=e.command("apps").description("Manage hosted apps served in your TurboBase app.");a.command("deploy").description("Build the app (if needed) and deploy it \u2014 cuts a new live version at /a/<slug>.").argument("<app>","App slug or id.").argument("[dir]","Source or built directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--no-build","Upload the directory as-is; it is already a built bundle.").option("--no-install","Skip `npm install` (assume deps are present).").option("--no-pull","Do not pull generated source even when the dir has no package.json.").option("--entry <file>","SPA entrypoint served for unknown routes.","index.html").option("--create","Create the app first if it does not exist yet.").option("--proposal <id>","Widget proposal this ship realizes (defaults to .turbobase/proposal.json).").option("--preview","Deploy to a preview URL instead of going live. Nothing about /a/<slug> changes until you `apps promote` it.").option("--label <text>","Label for the preview, so several open previews are tellable apart.").action(async(f,m,y)=>{let b=ce(process.cwd(),m??".");await oe.mkdir(b,{recursive:!0});let S=y.proposal??await v(b),{baseUrl:w,token:$}=await le(y.baseUrl),E=new ae({baseUrl:w,token:$}),A=!1;try{A=(await E.appsList()).some(J=>J.slug===f||J.id===f)}catch(J){st(J,"extensions:deploy","deploy"),k(`could not reach ${w}: ${J instanceof Error?J.message:String(J)}`)}if(!A){y.create||k(`no app "${f}" on ${w} \u2014 create it with \`turbobase apps create ${f}\`, or pass --create.`);let J=await me(`creating app ${f}`,()=>u(w,$,{slug:f},{tolerateExisting:!0}));J.existed||x(`created ${J.slug??f}.`)}let I=J=>oe.stat(Kt(b,J)).then(()=>!0).catch(()=>!1),C=f,G=b,q=y.build!==!1;if(q&&!await I("package.json"))if(await I("index.html"))x("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),q=!1;else if(y.pull===!1)k(`${b} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let J=await me(`pulling ${f}`,()=>p(w,$,f));C=J.slug??f,await d(b,J.files,!0),x(`pulled generated source (rev ${J.rev}).`)}let ie;if(q){let J=Md();if(ie={buildId:J,assetBase:qd(J)},y.install!==!1&&!await I("node_modules")){x("installing dependencies\u2026");try{await T(["install"],b)}catch(Ke){k(`npm install failed: ${Ke instanceof Error?Ke.message:String(Ke)}`)}}x("building\u2026");try{await T(["run","build"],b,{TURBOBASE_ASSET_BASE:ie.assetBase})}catch(Ke){k(`build failed: ${Ke instanceof Error?Ke.message:String(Ke)}`)}await I("dist")||k(`no dist/ after build in ${b} \u2014 check the app's build script.`),G=Kt(b,"dist")}y.preview&&!ie&&k(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${C}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let X=await Q(w,$,C,G,y.entry,S,ie,y.preview?{label:y.label}:void 0);if(y.preview){let J=X.previewUrl??"(no url returned)",Ke=X.expiresAt?new Date(X.expiresAt).toLocaleDateString():`${Ud} days`;Me()?x(Pt("Preview deployed",[`${R.bold(C)} ${R.green(`v${X.version??"?"}`)} ${R.dim("not live")}`,`${R.bold(J)}`,R.dim(`expires ${Ke}`)])):x(`preview ${C} v${X.version??"?"} \u2192 ${J} (expires ${Ke}; /a/${C} unchanged).`),x(`next: turbobase apps promote ${C} ${X.previewId??"<preview-id>"} # make it live`),x(` turbobase apps preview discard ${X.previewId??"<preview-id>"}`);return}Me()?x(Pt("Deployed",[`${R.bold(C)} ${R.green(`v${X.version??"?"}`)} ${R.dim(X.url??`/a/${C}`)}`])):x(`deployed ${C} \u2192 v${X.version??"?"} (${X.url??`/a/${C}`}).`),B(X)}),a.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(f,m,y)=>{let{baseUrl:b,token:S}=await le(y.baseUrl),w=await me(`promoting ${m}`,()=>N(b,S,f,"promote",{previewId:m}));Me()?x(Pt("Promoted",[`${R.bold(f)} ${R.green(`v${w.version??"?"}`)} ${R.dim(w.url??`/a/${f}`)}`])):x(`promoted ${f} \u2192 v${w.version??"?"} is now live at ${w.url??`/a/${f}`}.`),B(w)});let l=a.command("preview").description("Inspect and manage an app's open previews.");l.command("list").description("List an app's open previews (newest first).").argument("<app>","App slug or id.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(f,m)=>{let{baseUrl:y,token:b}=await le(m.baseUrl),S=await D(y,b,f);if(S.previews.length===0){x(`no open previews for ${f}.`);return}for(let w of S.previews){let $=w.label?` ${w.label}`:"",E=w.expiresAt?new Date(w.expiresAt).toLocaleDateString():"?";x(`v${w.version} ${w.previewId}${$} ${w.url} (expires ${E})`)}}),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(f,m,y)=>{let{baseUrl:b,token:S}=await le(y.baseUrl);await me(`discarding ${m}`,()=>N(b,S,f,"discard",{previewId:m})),x(`discarded ${m}.`)}),a.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(f,m)=>{let{baseUrl:y,token:b}=await le(m.baseUrl),S=await me(`creating ${f}`,()=>u(y,b,{slug:f,name:m.name,description:m.description})),w=S.slug??f;Me()?x(Pt("Created",[`${R.bold(w)} ${R.dim(S.url??`/a/${w}`)}`])):x(`created ${w} (${S.url??`/a/${w}`}).`),x(`next: turbobase apps push ${w} . # store the source`),x(` turbobase apps deploy ${w} # build + go live`)});async function u(f,m,y,b={}){let S=`${f.replace(/\/+$/,"")}/v1/apps`,w;try{w=await fetch(S,{method:"POST",headers:{Authorization:`Bearer ${m}`,"content-type":"application/json"},body:JSON.stringify({slug:y.slug,name:y.name??y.slug,description:y.description})})}catch($){k(`create request failed: ${$ instanceof Error?$.message:String($)}`)}if(w.status===401&&k("create unauthorized (401) \u2014 re-run `turbobase auth login`."),w.status===403&&k("create forbidden (403) \u2014 the PAT is not for an admin."),w.status===409){if(b.tolerateExisting)return{slug:y.slug,existed:!0};k(`an app with slug "${y.slug}" already exists.`)}return w.ok||k(`create failed: HTTP ${w.status} ${(await w.text().catch(()=>"")).slice(0,200)}`),await w.json().catch(()=>({}))}async function p(f,m,y){let b=`${f.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(y)}/pull`,S;try{S=await fetch(b,{headers:{Authorization:`Bearer ${m}`}})}catch(w){k(`pull request failed: ${w instanceof Error?w.message:String(w)}`)}return S.status===401&&k("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),S.status===403&&k("pull forbidden (403) \u2014 the PAT is not for an admin."),S.status===404&&k(`no generated source for "${y}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),S.ok||k(`pull failed: HTTP ${S.status} ${(await S.text().catch(()=>"")).slice(0,200)}`),await S.json()}async function d(f,m,y){let b=ce(f),S=0;for(let[w,$]of Object.entries(m)){let E=ce(b,w);E!==b&&!E.startsWith(b+Il)&&k(`refusing to write outside ${b}: ${w}`),y||await oe.stat(E).then(()=>!0).catch(()=>!1)&&k(`${E} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await oe.mkdir(Qn(E),{recursive:!0}),await oe.writeFile(E,$,"utf8"),S+=1}return S}function h(f){let m=f.indexOf(","),y=f.startsWith("data:")?m>=0?f.slice(m+1):"":f;if(!y)return null;try{let b=Buffer.from(y,"base64");return b.length>0?new Uint8Array(b):null}catch{return null}}async function g(f,m,y){let b=ce(f),S=async($,E)=>{let A=ce(b,$);A!==b&&!A.startsWith(b+Il)&&k(`refusing to write outside ${b}: ${$}`),y||await oe.stat(A).then(()=>!0).catch(()=>!1)&&k(`${A} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await oe.mkdir(Qn(A),{recursive:!0}),await oe.writeFile(A,E)},w=`# ${m.title||"App change request"}
|
|
1668
|
+
`),"utf8"),x(`wrote ${I}${P?"":" (instance returned no grounding \u2014 connect a source first?)"}`)}),o.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 (${nn.join(" | ")}).`).option("--limit <n>","Cap how many findings to act on.",p=>Number.parseInt(p,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each page\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--no-group","Plan every finding on its own instead of merging the ones that look related \u2014 N findings for one page become N sequential appends.").option("--yes","Skip the confirmation (for scripted runs).").action(p=>Hd(p)),i.command("push").description("Write pending `## Agent rules` findings as draft agent rules, one per rule. Shows the plan and asks first; rules land unpublished and disabled.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--limit <n>","Cap how many findings to act on.",p=>Number.parseInt(p,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each rule\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--yes","Skip the confirmation (for scripted runs).").action(p=>Kd(p));let a=s.command("new").description("Scaffold a new extension file.");a.command("hook").description("Scaffold a hook file under hooks/.").requiredOption("--record <type>","Record type the hook targets, e.g. salesOrder").option("--event <event>","Lifecycle event","before_save").option("--template <name>","require-field | enforce-format | blank","require-field").option("--field <name>","Field name (for require-field / enforce-format)").option("--regex <pattern>","Pattern (for enforce-format)").option("--source <source>","Source id (netsuite, stripe, \u2026)").option("--id <id>","Override the generated hook id").action(async p=>{let f;try{f=wr("hook",{recordType:p.record,event:p.event,template:p.template,field:p.field,regex:p.regex,source:p.source,id:p.id})}catch(_){T(_ instanceof Error?_.message:String(_))}let y=ae(process.cwd(),f.relativePath);await Kr(y,f.content)==="skipped"&&T(`refusing to overwrite existing file: ${y}`),x(`wrote ${y}`)}),a.command("conduit").description("Scaffold a conduit file under conduits/ (cross-source bridge).").requiredOption("--source <source>","Origin source the record arrives from, e.g. shopify").requiredOption("--record <type>","Canonical record type the conduit triggers on, e.g. order").requiredOption("--to <source>","Target source the conduit bridges into, e.g. netsuite").option("--to-record <type>","Target record type (defaults to the trigger record type)").option("--event <event>","Cross-source lifecycle event","after_canonicalize_inbound").option("--id <id>","Override the generated conduit id").action(async p=>{let f;try{f=wr("conduit",{recordType:p.record,source:p.source,to:p.to,toRecordType:p.toRecord,event:p.event,id:p.id})}catch(_){T(_ instanceof Error?_.message:String(_))}let y=ae(process.cwd(),f.relativePath);await Kr(y,f.content)==="skipped"&&T(`refusing to overwrite existing file: ${y}`),x(`wrote ${y}`)}),s.command("test").argument("<file>","The extension file to dry-run").description("Dry-run an extension against samples/ fixtures (production sandbox parity).").option("--samples <dir>","Samples directory","samples").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").option("--ci","CI mode \u2014 alias for the non-zero-on-failure exit (always on for `test`).").action(async(p,f)=>{let y=Il(f.reporter),b=await en(ae(process.cwd(),p)),_=ae(process.cwd(),f.samples),m=await Xr(_);m.length===0&&!y&&x(`no samples found under ${_} \u2014 add JSON fixtures to dry-run against.`);let S;try{S=await ps(b,m.map(C=>C.fixture))}catch(C){T(`bundle failed: ${C instanceof Error?C.message:String(C)}`)}if(y){let C=t0(S);x(hs(C,y)),C.cases.some(O=>O.status==="failed")&&process.exit(1);return}let P=0;for(let C of S){let O=C.pass?k.green("PASS"):k.red("FAIL");C.pass||(P+=1);let J=C.error?` (error: ${C.error})`:C.observed!==C.expected?` (expected ${C.expected}, observed ${C.observed})`:C.rejection?` (rejected: ${C.rejection.code??"rejected"})`:"";x(` ${O} ${C.name}${J}`)}let I=`${S.length-P}/${S.length} sample(s) passed.`;x(`
|
|
1669
|
+
${P===0?k.green(I):k.yellow(I)}`),P>0&&process.exit(1)}),s.command("deploy").argument("[file]","The extension file to deploy (single-file mode; omit with --to).").description("Deploy one extension (POST /v1/extensions) or the whole bundle (--to \u2192 /v1/config/apply).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--to <env>","Deploy the WHOLE bundle (turbobase/bundle.json) to this env (sandbox|prod).").action(async(p,f)=>{if(f.to){let S=await Cl(),{baseUrl:P,token:I}=await V(f.baseUrl),C=new K({baseUrl:P,token:I});try{let O=await le(`applying bundle to ${f.to}`,()=>C.configApply(S));x(`applied bundle to ${f.to}: +${O.applied.add} ~${O.applied.change} -${O.applied.destroy}`+(O.backfillsQueued.length?` (${O.backfillsQueued.length} backfill(s) queued)`:""))}catch(O){O instanceof ue&&O.status===403&&T("apply forbidden (403) \u2014 the stored PAT is not for an admin."),T(`bundle apply failed: ${O instanceof Error?O.message:String(O)}`)}return}p||T("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:y,token:b}=await V(f.baseUrl),_=await e0(ae(process.cwd(),p)),m=new K({baseUrl:y,token:b});try{let S=await le(`deploying ${sg(p)}`,()=>m.deploy(_));qe()?x(Nt("Deployed",[`${k.bold(S.id)} ${br(S.status)} ${k.dim(S.outcome)}`])):x(`deployed ${S.id} \u2192 status=${S.status} (${S.outcome}).`)}catch(S){S instanceof ue&&S.status===403&&T("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),T(`deploy failed: ${S instanceof Error?S.message:String(S)}`)}});let l=e.command("apps").description("Manage hosted apps served in your Turbobase app.");l.command("deploy").description("Build the app (if needed) and deploy it \u2014 cuts a new live version at /a/<slug>.").argument("<app>","App slug or id.").argument("[dir]","Source or built directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--no-build","Upload the directory as-is; it is already a built bundle.").option("--no-install","Skip `npm install` (assume deps are present).").option("--no-pull","Do not pull generated source even when the dir has no package.json.").option("--entry <file>","SPA entrypoint served for unknown routes.","index.html").option("--create","Create the app first if it does not exist yet.").option("--proposal <id>","Widget proposal this ship realizes (defaults to .turbobase/proposal.json).").option("--preview","Deploy to a preview URL instead of going live. Nothing about /a/<slug> changes until you `apps promote` it.").option("--label <text>","Label for the preview, so several open previews are tellable apart.").action(async(p,f,y)=>{let b=ae(process.cwd(),f??".");await ce.mkdir(b,{recursive:!0});let _=y.proposal??await $(b),{baseUrl:m,token:S}=await V(y.baseUrl),P=new K({baseUrl:m,token:S}),I=!1;try{I=(await P.appsList()).some(Y=>Y.slug===p||Y.id===p)}catch(Y){ye(Y,"extensions:deploy","deploy"),T(`could not reach ${m}: ${Y instanceof Error?Y.message:String(Y)}`)}if(!I){y.create||T(`no app "${p}" on ${m} \u2014 create it with \`turbobase apps create ${p}\`, or pass --create.`);let Y=await le(`creating app ${p}`,()=>u(m,S,{slug:p},{tolerateExisting:!0}));Y.existed||x(`created ${Y.slug??p}.`)}let C=Y=>ce.stat(Pt(b,Y)).then(()=>!0).catch(()=>!1),O=p,J=b,M=y.build!==!1;if(M&&!await C("package.json"))if(await C("index.html"))x("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),M=!1;else if(y.pull===!1)T(`${b} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let Y=await le(`pulling ${p}`,()=>h(m,S,p));O=Y.slug??p,await v(b,Y.files,!0),x(`pulled generated source (rev ${Y.rev}).`)}let de;if(M){let Y=Wd();if(de={buildId:Y,assetBase:Jd(Y)},y.install!==!1&&!await C("node_modules")){x("installing dependencies\u2026");try{await E(["install"],b)}catch(Ve){T(`npm install failed: ${Ve instanceof Error?Ve.message:String(Ve)}`)}}x("building\u2026");try{await E(["run","build"],b,{TURBOBASE_ASSET_BASE:de.assetBase})}catch(Ve){T(`build failed: ${Ve instanceof Error?Ve.message:String(Ve)}`)}await C("dist")||T(`no dist/ after build in ${b} \u2014 check the app's build script.`),J=Pt(b,"dist")}y.preview&&!de&&T(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${O}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let te=await F(m,S,O,J,y.entry,_,de,y.preview?{label:y.label}:void 0);if(y.preview){let Y=te.previewUrl??"(no url returned)",Ve=te.expiresAt?new Date(te.expiresAt).toLocaleDateString():`${Zd} days`;qe()?x(Nt("Preview deployed",[`${k.bold(O)} ${k.green(`v${te.version??"?"}`)} ${k.dim("not live")}`,`${k.bold(Y)}`,k.dim(`expires ${Ve}`)])):x(`preview ${O} v${te.version??"?"} \u2192 ${Y} (expires ${Ve}; /a/${O} unchanged).`),x(`next: turbobase apps promote ${O} ${te.previewId??"<preview-id>"} # make it live`),x(` turbobase apps preview discard ${te.previewId??"<preview-id>"}`);return}qe()?x(Nt("Deployed",[`${k.bold(O)} ${k.green(`v${te.version??"?"}`)} ${k.dim(te.url??`/a/${O}`)}`])):x(`deployed ${O} \u2192 v${te.version??"?"} (${te.url??`/a/${O}`}).`),Ce(te)}),l.command("promote").description("Make a preview the live version at /a/<slug>. Promotes the exact reviewed bytes \u2014 no rebuild.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to promote (from `apps preview list`).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,f,y)=>{let{baseUrl:b,token:_}=await V(y.baseUrl),m=await le(`promoting ${f}`,()=>z(b,_,p,"promote",{previewId:f}));qe()?x(Nt("Promoted",[`${k.bold(p)} ${k.green(`v${m.version??"?"}`)} ${k.dim(m.url??`/a/${p}`)}`])):x(`promoted ${p} \u2192 v${m.version??"?"} is now live at ${m.url??`/a/${p}`}.`),Ce(m)});let d=l.command("preview").description("Inspect and manage an app's open previews.");d.command("list").description("List an app's open previews (newest first).").argument("<app>","App slug or id.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,f)=>{let{baseUrl:y,token:b}=await V(f.baseUrl),_=await ee(y,b,p);if(_.previews.length===0){x(`no open previews for ${p}.`);return}for(let m of _.previews){let S=m.label?` ${m.label}`:"",P=m.expiresAt?new Date(m.expiresAt).toLocaleDateString():"?";x(`v${m.version} ${m.previewId}${S} ${m.url} (expires ${P})`)}}),d.command("discard").description("Close a preview. The URL stops resolving; the version stays in deploy history.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to discard.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,f,y)=>{let{baseUrl:b,token:_}=await V(y.baseUrl);await le(`discarding ${f}`,()=>z(b,_,p,"discard",{previewId:f})),x(`discarded ${f}.`)}),l.command("create").description("Create a new hosted app (a bare app row) so a build can be shipped to it.").argument("<slug>","URL slug the app is served under: /a/<slug>.").option("--name <name>","Display name (defaults to the slug).").option("--description <text>","Optional description.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,f)=>{let{baseUrl:y,token:b}=await V(f.baseUrl),_=await le(`creating ${p}`,()=>u(y,b,{slug:p,name:f.name,description:f.description})),m=_.slug??p;qe()?x(Nt("Created",[`${k.bold(m)} ${k.dim(_.url??`/a/${m}`)}`])):x(`created ${m} (${_.url??`/a/${m}`}).`),x(`next: turbobase apps push ${m} . # store the source`),x(` turbobase apps deploy ${m} # build + go live`)});async function u(p,f,y,b={}){let _=`${p.replace(/\/+$/,"")}/v1/apps`,m;try{m=await fetch(_,{method:"POST",headers:{Authorization:`Bearer ${f}`,"content-type":"application/json"},body:JSON.stringify({slug:y.slug,name:y.name??y.slug,description:y.description})})}catch(S){T(`create request failed: ${S instanceof Error?S.message:String(S)}`)}if(m.status===401&&T("create unauthorized (401) \u2014 re-run `turbobase auth login`."),m.status===403&&T("create forbidden (403) \u2014 the PAT is not for an admin."),m.status===409){if(b.tolerateExisting)return{slug:y.slug,existed:!0};T(`an app with slug "${y.slug}" already exists.`)}return m.ok||T(`create failed: HTTP ${m.status} ${(await m.text().catch(()=>"")).slice(0,200)}`),await m.json().catch(()=>({}))}async function h(p,f,y){let b=`${p.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(y)}/pull`,_;try{_=await fetch(b,{headers:{Authorization:`Bearer ${f}`}})}catch(m){T(`pull request failed: ${m instanceof Error?m.message:String(m)}`)}return _.status===401&&T("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),_.status===403&&T("pull forbidden (403) \u2014 the PAT is not for an admin."),_.status===404&&T(`no generated source for "${y}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),_.ok||T(`pull failed: HTTP ${_.status} ${(await _.text().catch(()=>"")).slice(0,200)}`),await _.json()}async function v(p,f,y){let b=ae(p),_=0;for(let[m,S]of Object.entries(f)){let P=ae(b,m);P!==b&&!P.startsWith(b+jl)&&T(`refusing to write outside ${b}: ${m}`),y||await ce.stat(P).then(()=>!0).catch(()=>!1)&&T(`${P} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await ce.mkdir(Qn(P),{recursive:!0}),await ce.writeFile(P,S,"utf8"),_+=1}return _}function g(p){let f=p.indexOf(","),y=p.startsWith("data:")?f>=0?p.slice(f+1):"":p;if(!y)return null;try{let b=Buffer.from(y,"base64");return b.length>0?new Uint8Array(b):null}catch{return null}}async function w(p,f,y){let b=ae(p),_=async(S,P)=>{let I=ae(b,S);I!==b&&!I.startsWith(b+jl)&&T(`refusing to write outside ${b}: ${S}`),y||await ce.stat(I).then(()=>!0).catch(()=>!1)&&T(`${I} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await ce.mkdir(Qn(I),{recursive:!0}),await ce.writeFile(I,P)},m=`# ${f.title||"App change request"}
|
|
1566
1670
|
|
|
1567
|
-
> Widget proposal \`${
|
|
1568
|
-
> \`turbobase apps deploy ${
|
|
1671
|
+
> Widget proposal \`${f.proposalId}\` \u2014 build this change, then ship it with
|
|
1672
|
+
> \`turbobase apps deploy ${f.appSlug}\`. The deploy stamps this proposal complete.
|
|
1569
1673
|
|
|
1570
|
-
${
|
|
1674
|
+
${f.bodyMarkdown||"_No description provided._"}
|
|
1571
1675
|
|
|
1572
1676
|
## Screen context
|
|
1573
1677
|
|
|
1574
|
-
`+(
|
|
1575
|
-
`);if(await
|
|
1576
|
-
`)}async function v(f){try{let m=await oe.readFile(Kt(f,".turbobase","proposal.json"),"utf8"),y=JSON.parse(m);return typeof y.proposalId=="string"&&y.proposalId?y.proposalId:void 0}catch{return}}async function _(f,m,y,b,S,w){let $=new ae({baseUrl:f,token:m});try{return await $.appsPush(y,b,{note:S,proposalId:w})}catch(E){if(E instanceof pe){let A=E.body;if(E.status===401&&k("push unauthorized (401) \u2014 re-run `turbobase auth login`."),E.status===403&&A?.error==="admin_required"&&k("push forbidden (403) \u2014 the PAT is not for an admin."),E.status===403&&st(E,"extensions:deploy","push app source"),E.status===404&&k(`no app "${y}" on this instance \u2014 create it with \`turbobase apps create ${y}\`.`),E.status===413&&(A?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&k("push rejected: the request body exceeded the instance limit."),k(`push rejected: ${A?.error??"too large"} (limit ${A?.limit??"?"}).`)),E.status===400){let I=A?.path?` in ${A.path}`:"",C=A?.reason?` (${A.reason})`:"";k(`push rejected: ${A?.error??"bad request"}${C}${I}.`)}}k(`push failed: ${E instanceof Error?E.message:String(E)}`)}}function T(f,m,y){return new Promise((b,S)=>{let w=Cl("npm",f,{cwd:m,stdio:"inherit",...y?{env:{...process.env,...y}}:{}});w.on("error",S),w.on("exit",$=>$===0?b():S(new Error(`npm ${f.join(" ")} exited ${$??"?"}`)))})}async function P(f,m,y,b){let S=`${f.replace(/\/+$/,"")}${y}`,w;try{w=await fetch(S,{method:b.method,headers:{Authorization:`Bearer ${m}`,...b.body?{"content-type":"application/json"}:{}},...b.body?{body:JSON.stringify(b.body)}:{}})}catch($){k(`request failed: ${$ instanceof Error?$.message:String($)}`)}if(w.status===401&&k("unauthorized (401) \u2014 re-run `turbobase auth login`."),w.status===403&&k("forbidden (403) \u2014 the PAT is not for an admin."),!w.ok){let $=await w.text().catch(()=>""),E=$.slice(0,300);try{let A=JSON.parse($);E=A.message??A.error??E}catch{}k(`failed: HTTP ${w.status} ${E}`)}return await w.json().catch(()=>({}))}async function N(f,m,y,b,S){return await P(f,m,`/v1/apps/${encodeURIComponent(y)}/preview/${b}`,{method:"POST",body:S})}async function D(f,m,y){return{previews:(await P(f,m,`/v1/apps/${encodeURIComponent(y)}/previews`,{method:"GET"})).previews??[]}}async function Q(f,m,y,b,S,w,$,E){let A;try{A=await me(`zipping ${b}`,()=>md(b))}catch(q){k(`could not zip ${b}: ${q instanceof Error?q.message:String(q)}`)}A.fileCount===0&&k(`${b} is empty \u2014 the build produced nothing.`);let I={Authorization:`Bearer ${m}`,"Content-Type":"application/zip"};S&&(I["x-app-entry"]=S),w&&(I["x-proposal-id"]=w),$&&(I["x-app-build-id"]=$.buildId,I["x-app-asset-base"]=$.assetBase),E&&(I["x-app-channel"]="preview",E.label&&(I["x-app-preview-label"]=encodeURIComponent(E.label)));let C=`${f.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(y)}/deploy`,G;try{G=await me(`deploying ${y} (${A.fileCount} file${A.fileCount===1?"":"s"})`,()=>fetch(C,{method:"POST",headers:I,body:new Uint8Array(A.buffer)}))}catch(q){k(`deploy request failed: ${q instanceof Error?q.message:String(q)}`)}if(G.status===401&&k("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),G.status===403&&k("deploy forbidden (403) \u2014 the PAT is not for an admin."),G.status===404&&k(`no app "${y}" on ${f} \u2014 create it with \`turbobase apps create ${y}\`.`),!G.ok){let q=await G.text().catch(()=>""),ie=q.slice(0,300);try{let X=JSON.parse(q);ie=X.message??X.error??ie}catch{}k(`deploy failed: HTTP ${G.status} ${ie}`)}return await G.json().catch(()=>({}))}function B(f){let m=Rd(f);m&&x(m.level==="warn"?R.yellow(m.message):R.dim(m.message))}a.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(f,m,y)=>{let{baseUrl:b,token:S}=await le(y.baseUrl);if(y.proposal){let A=new ae({baseUrl:b,token:S}),I;try{I=await me(`fetching proposal ${y.proposal}`,()=>A.appPullContext(y.proposal))}catch(X){st(X,"extensions:deploy","pull proposal"),X instanceof pe&&X.status===404&&k(`no widget proposal "${y.proposal}" on ${b}.`),k(`could not fetch proposal ${y.proposal}: ${X instanceof Error?X.message:String(X)}`)}let C=await me(`pulling ${I.appSlug}`,()=>p(b,S,I.appSlug)),G=m??f,q=ce(process.cwd(),G??I.appSlug);await oe.mkdir(q,{recursive:!0});let ie=await d(q,C.files,!!y.force);await g(q,I,!!y.force),x(`pulled ${ie} file${ie===1?"":"s"} \u2192 ${q} (rev ${C.rev}), linked to proposal ${I.proposalId}.`),x(`next: cd ${qo(process.cwd(),q)||"."} && turbobase apps deploy ${I.appSlug}`);return}f||k("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let w=await me(`pulling ${f}`,()=>p(b,S,f)),$=ce(process.cwd(),m??w.slug??f);await oe.mkdir($,{recursive:!0});let E=await d($,w.files,!!y.force);x(`pulled ${E} file${E===1?"":"s"} \u2192 ${$} (rev ${w.rev}).`),x(`next: cd ${qo(process.cwd(),$)||"."} && turbobase apps deploy ${w.slug}`)}),a.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(f,m,y)=>{let b=ce(process.cwd(),m??f),S=await pt(y.baseUrl).catch(()=>null),{scaffoldAppFiles:w,starterApp:$}=await Promise.resolve().then(()=>(gu(),mu)),E=y.title??f,A=w({slug:f,title:E,appTsx:$(E),instanceOrigin:S?.baseUrl});await oe.mkdir(b,{recursive:!0});let I=await d(b,A,!!y.force);if(x(`scaffolded ${I} file${I===1?"":"s"} \u2192 ${b}`),y.claude!==!1){let G=gi({baseUrl:S?.baseUrl,token:S?.token,appSlug:f}),q=0;for(let ie of G){let X=await Zm(Kt(b,ie.path),ie);(X==="wrote"||X==="merged")&&(q+=1)}x(`wired Claude Code: ${q} file${q===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),S||ye("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 C=qo(process.cwd(),b)||".";x(`next: cd ${C} && npm install && npm run dev`),x(` turbobase apps create ${f}`),x(` turbobase apps push ${f} .`),x(` turbobase apps deploy ${f} .`)}),a.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 f=>{let{baseUrl:m,token:y}=await le(f.baseUrl),b=new ae({baseUrl:m,token:y}),S;try{S=await b.appsList()}catch(w){st(w,"extensions:deploy","list apps"),k(`list apps failed: ${w instanceof Error?w.message:String(w)}`)}if(f.json)return x(JSON.stringify(S,null,2));if(S.length===0)return x("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");x(tn(S.map(w=>[w.slug,w.name,w.deployed?"yes":"no",w.sourceRev===null?"\u2014":`rev ${w.sourceRev}`,w.audience]),{head:["SLUG","NAME","LIVE","SOURCE","AUDIENCE"]}))}),a.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(f,m,y)=>{let b=ce(process.cwd(),m??".");await oe.stat(b).then(X=>X.isDirectory()).catch(()=>!1)||k(`${b} is not a directory.`);let{baseUrl:w,token:$}=await le(y.baseUrl),E=y.proposal??await v(b),{files:A,skipped:I,secrets:C,unstorable:G}=await Dd(b),q=Object.keys(A).length;if(q===0&&k(`no source files found under ${b} (build output and node_modules are skipped).`),G.length>0){for(let X of G)ye(`${X} contains a NUL byte (U+0000), which cannot be stored.`);k(`push aborted: ${G.length} ${G.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let X of I)ye(R.dim(`skipped binary file ${X}`));for(let X of C)ye(R.dim(`skipped ${X} (holds credentials \u2014 never pushed)`));let ie=await me(`pushing ${q} file${q===1?"":"s"}`,()=>_(w,$,f,A,y.note,E));x(`pushed ${ie.files} file${ie.files===1?"":"s"} \u2192 ${ie.slug} rev ${ie.rev} (source only, nothing deployed).`),x(`next: turbobase apps deploy ${ie.slug}`)}),s.command("plan").description("Diff the local bundle (turbobase/bundle.json) against a target env (no writes).").option("--from <env>","Source env the bundle was authored against (advisory).").option("--to <env>","Target env to diff against (sandbox|prod).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async f=>{let m=await El(),{baseUrl:y,token:b}=await le(f.baseUrl),S=new ae({baseUrl:y,token:b}),w;try{w=await me(`planning against ${f.to??y}`,()=>S.configPlan(m))}catch($){k(`plan failed: ${$ instanceof Error?$.message:String($)}`)}H0(w,f.to??y)}),s.command("promote").description("Promote the bundle from one env to another behind a confirm-slug gate (fail-closed).").requiredOption("--from <env>","Source env (e.g. sandbox).").requiredOption("--to <env>","Target env (e.g. prod).").requiredOption("--confirm <slug>","Type the EXACT target instance slug to confirm (fail-closed).").option("--base-url <url>","Target instance base URL (defaults to the active instance).").action(async f=>{let m=await El(),{baseUrl:y,token:b}=await le(f.baseUrl),S=m.tenant??K0(y),w=tu(f.confirm,S);w.ok||k(`promote refused (fail-closed): ${w.reason}`);let $=new ae({baseUrl:y,token:b});try{let E=await me(`promoting ${f.from} \u2192 ${f.to} (${S})`,()=>$.configApply(m));if(Me()){let A=[`${R.bold(`${f.from} \u2192 ${f.to}`)} ${R.dim(S??"")}`,`${Et.add(String(E.applied.add))} ${Et.change(String(E.applied.change))} ${Et.destroy(String(E.applied.destroy))}`];E.backfillsQueued.length&&A.push(R.dim(`${E.backfillsQueued.length} backfill(s) queued`)),x(Pt("Promoted",A))}else x(`promoted ${f.from} \u2192 ${f.to} (${S}): +${E.applied.add} ~${E.applied.change} -${E.applied.destroy}`+(E.backfillsQueued.length?` (${E.backfillsQueued.length} backfill(s) queued)`:""))}catch(E){E instanceof pe&&E.status===403&&k("promote forbidden (403) \u2014 the stored PAT is not for an admin."),k(`promote failed: ${E instanceof Error?E.message:String(E)}`)}});let Le=async(f,m)=>{let{baseUrl:y,token:b}=await le(m.baseUrl),S=new ae({baseUrl:y,token:b}),w=m.limit?Number(m.limit):void 0;if(m.follow){try{await kd(S,f,{follow:!0,limit:w,intervalMs:m.intervalMs?Number(m.intervalMs):void 0,sink:x})}catch($){k(`logs --follow failed: ${$ instanceof Error?$.message:String($)}`)}return}try{let $=await S.logs(f,w);$.length===0&&x(`no logs for ${f}.`);for(let E of $)x(` [${E.level}] ${E.ts??""} ${E.message}`)}catch($){k(`logs failed: ${$ instanceof Error?$.message:String($)}`)}};s.command("logs").argument("<id>","Extension id (default) or conduit id (with --follow)").description("Read an extension's logs; with --follow, stream a conduit's run ledger.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--limit <n>","Max log lines").option("--follow","Stream the conduit_event run ledger for the given conduit id.").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(Le),s.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(f,m)=>{let y=Rl(m.reporter),b=ce(process.cwd(),f),S=await Xr(b),w=yd(S);y?x(ps(U0(f,w),y)):x(bd(f,w,{warn:R.yellow,ok:R.green,dim:R.dim})),m.ci&&w.warnings.length>0&&process.exit(1)}),s.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(f,m)=>{let y=Rl(m.reporter),b=await ld(ce(process.cwd(),f));if(m.against){m.against!=="sandbox"&&k(`unknown --against target '${m.against}' (only 'sandbox' is supported).`);try{await ad(li(b))}catch($){k($ instanceof Error?$.message:String($))}return}m.fixture||k("replay needs a --fixture <file> (offline) or --against sandbox (online).");let S;try{S=await cd(ce(process.cwd(),m.fixture))}catch($){k(`could not read fixture ${m.fixture}: ${$ instanceof Error?$.message:String($)}`)}let w=await id(b,S,m.fixture);if(y){let $=B0(w);x(ps($,y)),$.cases.some(E=>E.status==="failed")&&process.exit(1);return}x(dd(w,!!m.trace)),w.error&&process.exit(1)}),s.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 f=>{let{baseUrl:m,token:y}=await le(f.baseUrl),b=new ae({baseUrl:m,token:y});try{await xd(b,{status:f.status,retry:f.retry,limit:f.limit?Number(f.limit):void 0,sink:x})}catch(S){S instanceof pe&&S.status===403&&k("forbidden (403) \u2014 binding --retry requires an admin PAT."),S instanceof pe&&S.status===409&&k("binding is not retryable (only divergent/blocked bindings can be retried)."),k(`ext binding failed: ${S instanceof Error?S.message:String(S)}`)}}),s.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(f,m)=>{let y=f.lastIndexOf("@"),b=y>0?f.slice(0,y):f,S=y>0?f.slice(y+1):void 0,w=ni();w||k(`marketplace not configured \u2014 set ${pr} and ${cs}.
|
|
1577
|
-
Ask
|
|
1578
|
-
Ask
|
|
1579
|
-
project init: ${b} written, ${
|
|
1580
|
-
project ci: ${
|
|
1581
|
-
Next: mint a releases:write PAT in your
|
|
1582
|
-
`;
|
|
1583
|
-
samples init: ${
|
|
1584
|
-
${b.length} active sandbox(es).`)}m.length>0&&x(`(reaped ${m.length} expired sandbox(es).)`)}),s.command("export").description("Snapshot the live instance into turbobase/bundle.json.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",ys).action(async f=>{let{baseUrl:m,token:y}=await le(f.baseUrl),b=new ae({baseUrl:m,token:y}),S;try{S=await me("exporting instance config",()=>b.configExport())}catch(E){E instanceof pe&&(E.status===401||E.status===403)&&k("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),k(`ext export failed: ${E instanceof Error?E.message:String(E)}`)}let w=typeof S.serialized=="string"?S.serialized:`${JSON.stringify(S.manifest??S,null,2)}
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
${
|
|
1589
|
-
|
|
1590
|
-
${S.length}
|
|
1591
|
-
|
|
1592
|
-
|
|
1678
|
+
`+(f.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.
|
|
1679
|
+
`);if(await _("PROPOSAL.md",m),f.screenshot){let S=g(f.screenshot);S&&await _("proposal-screenshot.png",S)}await _(Pt(".turbobase","proposal.json"),`${JSON.stringify({proposalId:f.proposalId},null,2)}
|
|
1680
|
+
`)}async function $(p){try{let f=await ce.readFile(Pt(p,".turbobase","proposal.json"),"utf8"),y=JSON.parse(f);return typeof y.proposalId=="string"&&y.proposalId?y.proposalId:void 0}catch{return}}async function R(p,f,y,b,_,m){let S=new K({baseUrl:p,token:f});try{return await S.appsPush(y,b,{note:_,proposalId:m})}catch(P){if(P instanceof ue){let I=P.body;if(P.status===401&&T("push unauthorized (401) \u2014 re-run `turbobase auth login`."),P.status===403&&I?.error==="admin_required"&&T("push forbidden (403) \u2014 the PAT is not for an admin."),P.status===403&&ye(P,"extensions:deploy","push app source"),P.status===404&&T(`no app "${y}" on this instance \u2014 create it with \`turbobase apps create ${y}\`.`),P.status===413&&(I?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&T("push rejected: the request body exceeded the instance limit."),T(`push rejected: ${I?.error??"too large"} (limit ${I?.limit??"?"}).`)),P.status===400){let C=I?.path?` in ${I.path}`:"",O=I?.reason?` (${I.reason})`:"";T(`push rejected: ${I?.error??"bad request"}${O}${C}.`)}}T(`push failed: ${P instanceof Error?P.message:String(P)}`)}}function E(p,f,y){return new Promise((b,_)=>{let m=zl("npm",p,{cwd:f,stdio:"inherit",...y?{env:{...process.env,...y}}:{}});m.on("error",_),m.on("exit",S=>S===0?b():_(new Error(`npm ${p.join(" ")} exited ${S??"?"}`)))})}async function A(p,f,y,b){let _=`${p.replace(/\/+$/,"")}${y}`,m;try{m=await fetch(_,{method:b.method,headers:{Authorization:`Bearer ${f}`,...b.body?{"content-type":"application/json"}:{}},...b.body?{body:JSON.stringify(b.body)}:{}})}catch(S){T(`request failed: ${S instanceof Error?S.message:String(S)}`)}if(m.status===401&&T("unauthorized (401) \u2014 re-run `turbobase auth login`."),m.status===403&&T("forbidden (403) \u2014 the PAT is not for an admin."),!m.ok){let S=await m.text().catch(()=>""),P=S.slice(0,300);try{let I=JSON.parse(S);P=I.message??I.error??P}catch{}T(`failed: HTTP ${m.status} ${P}`)}return await m.json().catch(()=>({}))}async function z(p,f,y,b,_){return await A(p,f,`/v1/apps/${encodeURIComponent(y)}/preview/${b}`,{method:"POST",body:_})}async function ee(p,f,y){return{previews:(await A(p,f,`/v1/apps/${encodeURIComponent(y)}/previews`,{method:"GET"})).previews??[]}}async function F(p,f,y,b,_,m,S,P){let I;try{I=await le(`zipping ${b}`,()=>Sd(b))}catch(M){T(`could not zip ${b}: ${M instanceof Error?M.message:String(M)}`)}I.fileCount===0&&T(`${b} is empty \u2014 the build produced nothing.`);let C={Authorization:`Bearer ${f}`,"Content-Type":"application/zip"};_&&(C["x-app-entry"]=_),m&&(C["x-proposal-id"]=m),S&&(C["x-app-build-id"]=S.buildId,C["x-app-asset-base"]=S.assetBase),P&&(C["x-app-channel"]="preview",P.label&&(C["x-app-preview-label"]=encodeURIComponent(P.label)));let O=`${p.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(y)}/deploy`,J;try{J=await le(`deploying ${y} (${I.fileCount} file${I.fileCount===1?"":"s"})`,()=>fetch(O,{method:"POST",headers:C,body:new Uint8Array(I.buffer)}))}catch(M){T(`deploy request failed: ${M instanceof Error?M.message:String(M)}`)}if(J.status===401&&T("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),J.status===403&&T("deploy forbidden (403) \u2014 the PAT is not for an admin."),J.status===404&&T(`no app "${y}" on ${p} \u2014 create it with \`turbobase apps create ${y}\`.`),!J.ok){let M=await J.text().catch(()=>""),de=M.slice(0,300);try{let te=JSON.parse(M);de=te.message??te.error??de}catch{}T(`deploy failed: HTTP ${J.status} ${de}`)}return await J.json().catch(()=>({}))}function Ce(p){let f=Od(p);f&&x(f.level==="warn"?k.yellow(f.message):k.dim(f.message))}l.command("pull").description("Write an app's generated source tree to disk (from the proposal that generated it).").argument("[app]","App slug or id. Omit when using --proposal (the app is derived from it).").argument("[dir]","Directory to write into (default ./<slug>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--force","Overwrite existing files.").option("--proposal <id>","Pull the app behind a widget proposal + its request context.").action(async(p,f,y)=>{let{baseUrl:b,token:_}=await V(y.baseUrl);if(y.proposal){let I=new K({baseUrl:b,token:_}),C;try{C=await le(`fetching proposal ${y.proposal}`,()=>I.appPullContext(y.proposal))}catch(te){ye(te,"extensions:deploy","pull proposal"),te instanceof ue&&te.status===404&&T(`no widget proposal "${y.proposal}" on ${b}.`),T(`could not fetch proposal ${y.proposal}: ${te instanceof Error?te.message:String(te)}`)}let O=await le(`pulling ${C.appSlug}`,()=>h(b,_,C.appSlug)),J=f??p,M=ae(process.cwd(),J??C.appSlug);await ce.mkdir(M,{recursive:!0});let de=await v(M,O.files,!!y.force);await w(M,C,!!y.force),x(`pulled ${de} file${de===1?"":"s"} \u2192 ${M} (rev ${O.rev}), linked to proposal ${C.proposalId}.`),x(`next: cd ${Ho(process.cwd(),M)||"."} && turbobase apps deploy ${C.appSlug}`);return}p||T("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let m=await le(`pulling ${p}`,()=>h(b,_,p)),S=ae(process.cwd(),f??m.slug??p);await ce.mkdir(S,{recursive:!0});let P=await v(S,m.files,!!y.force);x(`pulled ${P} file${P===1?"":"s"} \u2192 ${S} (rev ${m.rev}).`),x(`next: cd ${Ho(process.cwd(),S)||"."} && turbobase apps deploy ${m.slug}`)}),l.command("init").description("Scaffold a new app project locally, wired to your instance and to Claude Code.").argument("<app>","App slug \u2014 also the /a/<slug> mount path the build is pinned to.").argument("[dir]","Directory to scaffold into (default ./<app>).").option("--title <text>","Display title used in index.html and the starter component.").option("--base-url <url>","Instance to wire the project to (defaults to the active instance).").option("--no-claude","Skip the Claude Code wiring (CLAUDE.md, .mcp.json, .claude/).").option("--force","Overwrite existing files.").action(async(p,f,y)=>{let b=ae(process.cwd(),f??p),_=await ht(y.baseUrl).catch(()=>null),{scaffoldAppFiles:m,starterApp:S}=await Promise.resolve().then(()=>(ku(),$u)),P=y.title??p,I=m({slug:p,title:P,appTsx:S(P),instanceOrigin:_?.baseUrl});await ce.mkdir(b,{recursive:!0});let C=await v(b,I,!!y.force);if(x(`scaffolded ${C} file${C===1?"":"s"} \u2192 ${b}`),y.claude!==!1){let J=Si({baseUrl:_?.baseUrl,token:_?.token,appSlug:p}),M=0;for(let de of J){let te=await ng(Pt(b,de.path),de);(te==="wrote"||te==="merged")&&(M+=1)}x(`wired Claude Code: ${M} file${M===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),_||pe("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 O=Ho(process.cwd(),b)||".";x(`next: cd ${O} && npm install && npm run dev`),x(` turbobase apps create ${p}`),x(` turbobase apps push ${p} .`),x(` turbobase apps deploy ${p} .`)}),l.command("list").description("List the hosted apps on your instance.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async p=>{let{baseUrl:f,token:y}=await V(p.baseUrl),b=new K({baseUrl:f,token:y}),_;try{_=await b.appsList()}catch(m){ye(m,"extensions:deploy","list apps"),T(`list apps failed: ${m instanceof Error?m.message:String(m)}`)}if(p.json)return x(JSON.stringify(_,null,2));if(_.length===0)return x("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");x(Qt(_.map(m=>[m.slug,m.name,m.deployed?"yes":"no",m.sourceRev===null?"\u2014":`rev ${m.sourceRev}`,m.audience]),{head:["SLUG","NAME","LIVE","SOURCE","AUDIENCE"]}))}),l.command("push").description("Record the local source tree as the app's newest source revision (does NOT deploy).").argument("<app>","App slug or id.").argument("[dir]","Source directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--note <text>","Short note stored with the revision.").option("--proposal <id>","Widget proposal this rev works (defaults to .turbobase/proposal.json).").action(async(p,f,y)=>{let b=ae(process.cwd(),f??".");await ce.stat(b).then(te=>te.isDirectory()).catch(()=>!1)||T(`${b} is not a directory.`);let{baseUrl:m,token:S}=await V(y.baseUrl),P=y.proposal??await $(b),{files:I,skipped:C,secrets:O,unstorable:J}=await Gd(b),M=Object.keys(I).length;if(M===0&&T(`no source files found under ${b} (build output and node_modules are skipped).`),J.length>0){for(let te of J)pe(`${te} contains a NUL byte (U+0000), which cannot be stored.`);T(`push aborted: ${J.length} ${J.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let te of C)pe(k.dim(`skipped binary file ${te}`));for(let te of O)pe(k.dim(`skipped ${te} (holds credentials \u2014 never pushed)`));let de=await le(`pushing ${M} file${M===1?"":"s"}`,()=>R(m,S,p,I,y.note,P));x(`pushed ${de.files} file${de.files===1?"":"s"} \u2192 ${de.slug} rev ${de.rev} (source only, nothing deployed).`),x(`next: turbobase apps deploy ${de.slug}`)}),s.command("plan").description("Diff the local bundle (turbobase/bundle.json) against a target env (no writes).").option("--from <env>","Source env the bundle was authored against (advisory).").option("--to <env>","Target env to diff against (sandbox|prod).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async p=>{let f=await Cl(),{baseUrl:y,token:b}=await V(p.baseUrl),_=new K({baseUrl:y,token:b}),m;try{m=await le(`planning against ${p.to??y}`,()=>_.configPlan(f))}catch(S){T(`plan failed: ${S instanceof Error?S.message:String(S)}`)}o0(m,p.to??y)}),s.command("promote").description("Promote the bundle from one env to another behind a confirm-slug gate (fail-closed).").requiredOption("--from <env>","Source env (e.g. sandbox).").requiredOption("--to <env>","Target env (e.g. prod).").requiredOption("--confirm <slug>","Type the EXACT target instance slug to confirm (fail-closed).").option("--base-url <url>","Target instance base URL (defaults to the active instance).").action(async p=>{let f=await Cl(),{baseUrl:y,token:b}=await V(p.baseUrl),_=f.tenant??i0(y),m=lu(p.confirm,_);m.ok||T(`promote refused (fail-closed): ${m.reason}`);let S=new K({baseUrl:y,token:b});try{let P=await le(`promoting ${p.from} \u2192 ${p.to} (${_})`,()=>S.configApply(f));if(qe()){let I=[`${k.bold(`${p.from} \u2192 ${p.to}`)} ${k.dim(_??"")}`,`${Ot.add(String(P.applied.add))} ${Ot.change(String(P.applied.change))} ${Ot.destroy(String(P.applied.destroy))}`];P.backfillsQueued.length&&I.push(k.dim(`${P.backfillsQueued.length} backfill(s) queued`)),x(Nt("Promoted",I))}else x(`promoted ${p.from} \u2192 ${p.to} (${_}): +${P.applied.add} ~${P.applied.change} -${P.applied.destroy}`+(P.backfillsQueued.length?` (${P.backfillsQueued.length} backfill(s) queued)`:""))}catch(P){P instanceof ue&&P.status===403&&T("promote forbidden (403) \u2014 the stored PAT is not for an admin."),T(`promote failed: ${P instanceof Error?P.message:String(P)}`)}});let Ue=async(p,f)=>{let{baseUrl:y,token:b}=await V(f.baseUrl),_=new K({baseUrl:y,token:b}),m=f.limit?Number(f.limit):void 0;if(f.follow){try{await Ad(_,p,{follow:!0,limit:m,intervalMs:f.intervalMs?Number(f.intervalMs):void 0,sink:x})}catch(S){T(`logs --follow failed: ${S instanceof Error?S.message:String(S)}`)}return}try{let S=await _.logs(p,m);S.length===0&&x(`no logs for ${p}.`);for(let P of S)x(` [${P.level}] ${P.ts??""} ${P.message}`)}catch(S){T(`logs failed: ${S instanceof Error?S.message:String(S)}`)}};s.command("logs").argument("<id>","Extension id (default) or conduit id (with --follow)").description("Read an extension's logs; with --follow, stream a conduit's run ledger.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--limit <n>","Max log lines").option("--follow","Stream the conduit_event run ledger for the given conduit id.").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(Ue),s.command("lint").argument("<file>","The hook or conduit definition file to lint").description("Statically lint a hook/conduit for semantic foot-guns (offline).").option("--ci","Exit non-zero when any warning fires (else exit 0).").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").action(async(p,f)=>{let y=Il(f.reporter),b=ae(process.cwd(),p),_=await en(b),m=$d(_);y?x(hs(r0(p,m),y)):x(kd(p,m,{warn:k.yellow,ok:k.green,dim:k.dim})),f.ci&&m.warnings.length>0&&process.exit(1)}),s.command("replay").argument("<file>","The conduit file to replay").description("Dry-run a conduit through dispatch\u2192transform\u2192apply (offline against a fixture).").option("--fixture <file>","JSON conduit-trigger fixture to replay against.").option("--against <target>","Replay against a running sandbox (online; deferred without a local DB).").option("--trace","Emit the per-stage trace (guards, atlas, apply-branch, bindings).").option("--reporter <fmt>","Emit machine-readable output: junit | json (one case per stage).").action(async(p,f)=>{let y=Il(f.reporter),b=await md(ae(process.cwd(),p));if(f.against){f.against!=="sandbox"&&T(`unknown --against target '${f.against}' (only 'sandbox' is supported).`);try{await fd(fi(b))}catch(S){T(S instanceof Error?S.message:String(S))}return}f.fixture||T("replay needs a --fixture <file> (offline) or --against sandbox (online).");let _;try{_=await hd(ae(process.cwd(),f.fixture))}catch(S){T(`could not read fixture ${f.fixture}: ${S instanceof Error?S.message:String(S)}`)}let m=await pd(b,_,f.fixture);if(y){let S=n0(m);x(hs(S,y)),S.cases.some(P=>P.status==="failed")&&process.exit(1);return}x(gd(m,!!f.trace)),m.error&&process.exit(1)}),s.command("binding").description("List conduit source bindings (--status divergent) or re-enqueue one (--retry <id>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <status>","Filter by write_status (ok|pending|blocked|divergent|muted).").option("--retry <id>","Re-enqueue the fan-out write for this binding id (admin-only).").option("--limit <n>","Max rows listed").action(async p=>{let{baseUrl:f,token:y}=await V(p.baseUrl),b=new K({baseUrl:f,token:y});try{await Id(b,{status:p.status,retry:p.retry,limit:p.limit?Number(p.limit):void 0,sink:x})}catch(_){_ instanceof ue&&_.status===403&&T("forbidden (403) \u2014 binding --retry requires an admin PAT."),_ instanceof ue&&_.status===409&&T("binding is not retryable (only divergent/blocked bindings can be retried)."),T(`ext binding failed: ${_ instanceof Error?_.message:String(_)}`)}}),s.command("install").argument("<spec>","Extension name, optionally name@version").description("Install an extension from the marketplace into your instance's extension store.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--connection <id>",'Bind this connection id (required when the extension declares a { type:"connection" } input).').action(async(p,f)=>{let y=p.lastIndexOf("@"),b=y>0?p.slice(0,y):p,_=y>0?p.slice(y+1):void 0,m=ai();m||T(`marketplace not configured \u2014 set ${hr} and ${ds}.
|
|
1681
|
+
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let S=ci(m.registryUrl);S&&T(S);let{baseUrl:P,token:I}=await V(f.baseUrl),C=new Yr(m),O;try{O=await le(`fetching ${p}`,()=>C.fetchBundle(b,_))}catch(Y){T(`marketplace fetch failed for ${p}: ${Y instanceof Error?Y.message:String(Y)}`)}let J=ns(O.manifest),M=null;if(J.length>0){if(!f.connection){let Y=J.map(Ve=>Ve.source_system).join(", ");T(`${O.name}@${O.version} declares a connection input (source: ${Y}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}M=f.connection}let de=s0(O.bundle,O.name,O.kind),te=new K({baseUrl:P,token:I});try{let Y=await le(`installing ${O.name}@${O.version}`,()=>te.deploy({...de,provenance:"marketplace",...M?{connectionId:M}:{}}));x(`installed ${O.name}@${O.version} \u2192 ${Y.id} (status=${Y.status}, ${Y.outcome})`+(M?` bound to connection ${M}.`:"."))}catch(Y){Y instanceof ue&&Y.status===403&&T("install forbidden (403) \u2014 the stored PAT is not for an admin."),T(`install failed: ${Y instanceof Error?Y.message:String(Y)}`)}}),s.command("publish").description("Publish an authored extension to the public marketplace (publisher allowlist required).").argument("<file>","The extension file to publish (defineHook/defineConduit source).").requiredOption("--name <name>","Marketplace package name (lowercase, e.g. acme-recipes).").requiredOption("--pkg-version <version>","Semver-ish package version (e.g. 1.0.0).").option("--manifest <file>","Path to a JSON manifest (declared inputs[], capabilities).").action(async(p,f)=>{let y=ai();y||T(`marketplace not configured \u2014 set ${hr} and ${ds}.
|
|
1682
|
+
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let b=ci(y.registryUrl);b&&T(b);let _=ae(process.cwd(),p),m=await en(_),S=/\bdefineConduit\s*[<(]/.test(m)?"conduit":"hook",P={};if(f.manifest){let O=ae(process.cwd(),f.manifest),J;try{J=await ce.readFile(O,"utf8")}catch{T(`manifest not found at ${f.manifest}.`)}let M;try{M=JSON.parse(J)}catch{T(`manifest is not valid JSON: ${f.manifest}.`)}(typeof M!="object"||M===null||Array.isArray(M))&&T("manifest must be a JSON object."),P=M}try{Go(P,m)}catch(O){O instanceof At&&T(O.message),T(`manifest validation failed: ${O instanceof Error?O.message:String(O)}`)}let I=new Yr(y);try{await le(`publishing ${f.name}@${f.pkgVersion}`,()=>I.publish({name:f.name,version:f.pkgVersion,kind:S,bundle:m,manifest:P}))}catch(O){O instanceof ue&&O.status===403&&T("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),O instanceof ue&&O.status===409&&T(`version already published \u2014 ${f.name}@${f.pkgVersion} exists. Bump the version.`),T(`publish failed: ${O instanceof Error?O.message:String(O)}`)}let C=ns(P);x(`published ${f.name}@${f.pkgVersion} (kind=${S}) to the marketplace.`),C.length>0&&x(` declares ${C.length} connection input(s): ${C.map(O=>O.source_system).join(", ")} \u2014 bound at install.`)}),n.command("init").description("Scaffold a Claude-Code extension project in the current dir.").option("--base-url <url>","Instance to wire .mcp.json to (defaults to the active instance).").action(async p=>{let f=await ht(p.baseUrl).catch(()=>null),y=Si({baseUrl:f?.baseUrl,token:f?.token}),b=0,_=0,m=0;for(let S of y){let P=ae(process.cwd(),S.path),I=await ng(P,S);I==="wrote"?(b+=1,x(` wrote ${S.path}`)):I==="merged"?(m+=1,x(` merged ${S.path} (added the .mcp.json rule)`)):(_+=1,x(` skipped ${S.path} (exists)`))}x(`
|
|
1683
|
+
project init: ${b} written, ${m} merged, ${_} skipped.`)}),n.command("ci").description(`Write the reusable release-deploy GitHub Action to ${vi} (non-destructive).`).action(async()=>{let p=Nd(),f=0,y=0;for(let b of p){let _=ae(process.cwd(),b.path);await Kr(_,b.content,b.executable)==="wrote"?(f+=1,x(` wrote ${b.path}`)):(y+=1,x(` skipped ${b.path} (exists)`))}x(`
|
|
1684
|
+
project ci: ${f} written, ${y} skipped.`),f>0&&(x(`
|
|
1685
|
+
Next: mint a releases:write PAT in your Turbobase app (Settings \u203A Access tokens),`),x("store it as the GitHub Actions secret TURBOBASE_RELEASE_PAT, and set the repo"),x("variable TURBOBASE_BASE_URL \u2014 the workflow header has the step-by-step."))}),n.command("samples").description("Generate samples/<recordType>.json fixtures from the live instance catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Output directory for the fixtures","samples").option("--event <event>","Lifecycle event to stamp on each fixture","before_save").option("--force","Overwrite existing fixture files (default: skip files that exist).").action(async p=>{let{baseUrl:f,token:y}=await V(p.baseUrl),b=new K({baseUrl:f,token:y}),_;try{_=await b.catalogRecords()}catch(C){C instanceof ue&&(C.status===401||C.status===403)&&T("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),T(`catalog fetch failed: ${C instanceof Error?C.message:String(C)}`)}if(_.length===0){x("no records in the instance catalog \u2014 nothing to generate.");return}let m=ae(process.cwd(),p.out),S=bd(_,{event:p.event}),P=0,I=0;for(let{recordType:C,fixture:O}of S){let J=Pt(m,`${C}.json`),M=`${JSON.stringify(O,null,2)}
|
|
1686
|
+
`;p.force?(await ce.mkdir(Qn(J),{recursive:!0}),await ce.writeFile(J,M,{mode:420}),P+=1,x(` wrote ${p.out}/${C}.json`)):await Kr(J,M)==="wrote"?(P+=1,x(` wrote ${p.out}/${C}.json`)):(I+=1,x(` skipped ${p.out}/${C}.json (exists \u2014 use --force to overwrite)`))}x(`
|
|
1687
|
+
samples init: ${P} written, ${I} skipped.`)});let ft=e.command("guardrails").description("Control PG\u2192source write-back with DENY rules (staged write rollout)."),Vr=p=>[p.name,p.enabled?k.green("on"):k.dim("off"),p.source,p.record,p.when||k.dim("(always)"),p.note??""];ft.command("list").description("List every write guardrail on your instance.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async p=>{let{baseUrl:f,token:y}=await V(p.baseUrl),b=new K({baseUrl:f,token:y}),_;try{_=await b.guardrailsList()}catch(m){ye(m,"extensions:deploy","list guardrails"),T(`list guardrails failed: ${m instanceof Error?m.message:String(m)}`)}if(p.json)return x(JSON.stringify(_,null,2));if(_.length===0)return x(`no write guardrails \u2014 every record the admin entitlement allows is writable.
|
|
1688
|
+
`+k.dim("create one with `turbobase guardrails create <name> --source <s> --when '\u2026'`"));x(Qt(_.map(Vr),{head:["NAME","STATE","SOURCE","RECORD","WHEN","NOTE"]}))}),ft.command("create <name>").description("Create a DENY rule. Blocks PG\u2192source writes that match it.").option("--source <system>","Adapter id to scope to, or '*' for every source.","*").option("--record <type>","Record type to scope to, or '*' for every record.","*").option("--when <expr>","Condition, e.g. 'recordType not_in customer,invoice' or 'record.amount gt 10000'. Omit to deny unconditionally.").option("--message <text>","What a blocked writer is told.").option("--note <text>","Why this rule exists \u2014 for whoever reads `list` later.").option("--disabled","Create the rule parked, so it takes effect only when enabled.").option("--confirm-freeze-all","Required for an unconditional '*'/'*' rule.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,f)=>{let{baseUrl:y,token:b}=await V(f.baseUrl),_=new K({baseUrl:y,token:b}),m;try{m=await _.guardrailCreate({name:p,source:f.source,record:f.record,...f.when?{when:f.when}:{},...f.message?{message:f.message}:{},...f.note?{note:f.note}:{},...f.disabled?{enabled:!1}:{},...f.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(S){ye(S,"extensions:deploy","create a guardrail"),T(`create guardrail failed: ${S instanceof Error?S.message:String(S)}`)}x(`${k.green("\u2713")} guardrail ${k.bold(m.name)} created${m.enabled?"":k.dim(" (parked \u2014 enable it to take effect)")}`),x(k.dim(` denies ${m.source}/${m.record}${m.when?` where ${m.when}`:" (always)"}`)),x(k.dim(` verify with: turbobase guardrails test --source ${m.source==="*"?"<source>":m.source} --record <record>`))}),ft.command("edit <name>").description("Change a rule \u2014 most often widening its exception set as records are proven.").option("--when <expr>","New condition. Pass '' to make it unconditional.").option("--message <text>","What a blocked writer is told.").option("--note <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,f)=>{f.when===void 0&&f.message===void 0&&f.note===void 0&&T("edit: nothing to change \u2014 pass --when, --message or --note.");let{baseUrl:y,token:b}=await V(f.baseUrl),_=new K({baseUrl:y,token:b}),m;try{m=await _.guardrailUpdate(p,{...f.when!==void 0?{when:f.when}:{},...f.message!==void 0?{message:f.message}:{},...f.note!==void 0?{note:f.note}:{}})}catch(S){ye(S,"extensions:deploy","edit a guardrail"),T(`edit guardrail failed: ${S instanceof Error?S.message:String(S)}`)}x(`${k.green("\u2713")} guardrail ${k.bold(m.name)} updated`),x(k.dim(` denies ${m.source}/${m.record}${m.when?` where ${m.when}`:" (always)"}`))});for(let[p,f,y]of[["enable",!0,"enabled"],["disable",!1,"disabled"]])ft.command(`${p} <name>`).description(f?"Arm a parked rule.":"Park a rule without deleting it \u2014 the reversible move mid-rollout.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(b,_)=>{let{baseUrl:m,token:S}=await V(_.baseUrl),P=new K({baseUrl:m,token:S});try{await P.guardrailUpdate(b,{enabled:f})}catch(I){ye(I,"extensions:deploy",`${p} a guardrail`),T(`${p} guardrail failed: ${I instanceof Error?I.message:String(I)}`)}x(`${k.green("\u2713")} guardrail ${k.bold(b)} ${y}`),f||x(k.dim(" writes it was blocking are now permitted (subject to the other rules)."))});ft.command("delete <name>").description("Remove a rule. This OPENS a write path \u2014 prefer `disable` if unsure.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,f)=>{let{baseUrl:y,token:b}=await V(f.baseUrl),_=new K({baseUrl:y,token:b});try{await _.guardrailDelete(p)}catch(m){ye(m,"extensions:deploy","delete a guardrail"),T(`delete guardrail failed: ${m instanceof Error?m.message:String(m)}`)}x(`${k.green("\u2713")} guardrail ${k.bold(p)} deleted`)}),ft.command("test").description("Would a write be blocked? Runs the real evaluator; writes nothing.").requiredOption("--source <system>","Adapter id the write targets.").requiredOption("--record <type>","Record type the write targets.").option("--origin <origin>","Write origin to simulate ('user', 'agent').").option("--fields <json>","A candidate row as JSON, so `record.<column>` conditions can be decided.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON.").action(async p=>{let f;if(p.fields)try{f=JSON.parse(p.fields)}catch(S){T(`--fields must be valid JSON: ${S instanceof Error?S.message:String(S)}`)}let{baseUrl:y,token:b}=await V(p.baseUrl),_=new K({baseUrl:y,token:b}),m;try{m=await _.guardrailTest({source:p.source,record:p.record,...p.origin?{origin:p.origin}:{},...f?{fields:f}:{}})}catch(S){ye(S,"extensions:deploy","test guardrails"),T(`guardrails test failed: ${S instanceof Error?S.message:String(S)}`)}if(p.json)return x(JSON.stringify(m,null,2));m.allowed?x(`${k.green("\u2713")} ${p.source}/${p.record} \u2014 no guardrail blocks this write`):(x(`${k.red("\u2717")} ${p.source}/${p.record} \u2014 blocked by ${k.bold(m.blockedBy??"?")}`),m.message&&x(k.dim(` ${m.message}`))),m.undecided.length>0&&(x(k.yellow(` ${m.undecided.length} rule(s) need a row to decide: ${m.undecided.join(", ")}`)),x(k.dim(` re-run with --fields '{"\u2026":"\u2026"}' to evaluate them.`))),m.allowed||(process.exitCode=1)});let ot=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),Zt=(p,f={})=>{let y=`${k.bold(p.table)} ${k.dim(p.displayName)}`;x(p.exists===!1?`${y} ${k.dim("(new)")}`:y);for(let b of p.fields){let _=[b.required?"required":null].filter(Boolean).join(", "),m=f.showClaimants&&b.claimedBy?.length?` ${k.dim(`\u2190 ${b.claimedBy.join(", ")}`)}`:"";x(` ${b.column.padEnd(28)} ${b.type}${_?` (${_})`:""}${m}`)}f.showClaimants&&p.claimants.length>1&&x(k.dim(` claimed by ${p.claimants.join(", ")}`))};function fr(p){if(p instanceof ue&&p.status===409){let f=p.body;f?.error==="table_conflict"&&f.message&&(pe(f.message),process.exit(1))}T(`tables: ${p instanceof Error?p.message:String(p)}`)}let Gr=async p=>{let f=Pt(ae(process.cwd(),p),"public","turbobase.json"),y=await ce.readFile(f,"utf8").catch(()=>null);if(y===null)return null;let b;try{b=JSON.parse(y)}catch(m){T(`${f} is not valid JSON: ${m instanceof Error?m.message:String(m)}`)}let _=b.tables;return _===void 0?{tables:[],manifestPath:f}:(Array.isArray(_)||T(`${f}: "tables" must be an array.`),{tables:_,manifestPath:f})};ot.command("list").description("List the custom tables on your instance and who claims each one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async p=>{let{baseUrl:f,token:y}=await V(p.baseUrl),b=new K({baseUrl:f,token:y}),_;try{_=await b.tablesList()}catch(m){ye(m,"extensions:deploy","list tables"),T(`list tables failed: ${m instanceof Error?m.message:String(m)}`)}if(p.json)return x(JSON.stringify(_,null,2));if(_.length===0)return x("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");x(Qt(_.map(m=>[m.table,m.displayName,String(m.fields.length),m.status,m.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),ot.command("plan").description("Preview what this project's declared tables would do. Writes nothing; exits 1 on a conflict.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: the app slug in .turbobase, else cli).").action(async(p,f)=>{let y=await Gr(p??".");if(y||T(`no public/turbobase.json under ${ae(process.cwd(),p??".")}.`),y.tables.length===0)return x(`${y.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:b,token:_}=await V(f.baseUrl),m=new K({baseUrl:b,token:_}),S;try{S=await le("planning tables",()=>m.tablesPlan({claimedBy:f.as,tables:y.tables}))}catch(P){ye(P,"extensions:deploy","plan tables"),fr(P)}x(`claiming as ${k.bold(S.claimedBy)}`);for(let P of S.tables)Zt(P,{showClaimants:!0});x(""),x(k.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),ot.command("apply").description("Apply this project's declared tables to the instance.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: cli).").action(async(p,f)=>{let y=await Gr(p??".");if(y||T(`no public/turbobase.json under ${ae(process.cwd(),p??".")}.`),y.tables.length===0)return x(`${y.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:b,token:_}=await V(f.baseUrl),m=new K({baseUrl:b,token:_}),S;try{S=await le("applying tables",()=>m.tablesApply({claimedBy:f.as,tables:y.tables}))}catch(P){ye(P,"extensions:deploy","apply tables"),fr(P)}for(let P of S.tables)Zt(P,{showClaimants:!0});x(`applied ${S.tables.length} table${S.tables.length===1?"":"s"} as ${S.claimedBy}.`)}),ot.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(p,f)=>[...f??[],p],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,f)=>{let y=f.field.map(P=>{let[I,C,O]=P.split(":");return(!I||!C)&&T(`--field "${P}" must be name:type[:required] (e.g. title:text:required).`),O!==void 0&&O!=="required"&&T(`--field "${P}": the third part may only be "required".`),{name:I,type:C,...O==="required"?{required:!0}:{}}}),{baseUrl:b,token:_}=await V(f.baseUrl),m=new K({baseUrl:b,token:_}),S;try{S=await le(`creating cr_${p}`,()=>m.tablesApply({tables:[{slug:p,displayName:f.name??p,fields:y,...f.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(P){ye(P,"extensions:deploy","create a table"),fr(P)}for(let P of S.tables)Zt(P);x(""),x(k.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),ot.command("drop").description("Drop a table and everything in it. Irreversible.").argument("<slug>","Table slug (without the cr_ prefix).").requiredOption("--confirm <slug>","Type the EXACT slug to confirm (fail-closed).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,f)=>{f.confirm!==p&&T(`drop refused: --confirm "${f.confirm}" does not match "${p}".`);let{baseUrl:y,token:b}=await V(f.baseUrl),_=new K({baseUrl:y,token:b}),m;try{m=await le(`dropping cr_${p}`,()=>_.tablesDrop(p,f.confirm))}catch(S){ye(S,"extensions:deploy","drop a table"),T(`drop failed: ${S instanceof Error?S.message:String(S)}`)}if(!m.removed)return x(`no table named "${p}" on this instance \u2014 nothing dropped.`);x(`dropped ${m.table} and every row in it.`)});let Wr=e.command("sandbox").description("Ephemeral local authoring sandboxes.");Wr.command("create").description("Stand up a fresh local sandbox seeded with a sampled+redacted slice of an instance.").requiredOption("--from <instance>","Source instance to clone the data slice from.").option("--ttl <duration>","Time-to-live before reaping (e.g. 72h, 30m, 7d).","72h").option("--sample <pct>","Percent of each table to copy (e.g. 2%).","2%").option("--base-url <url>","Local base URL the sandbox is reachable at.").action(async p=>{process.env.TURBOBASE_SANDBOX="1";let f=Ol(),y;try{y=await su(f,{fromTenant:p.from,ttl:p.ttl,sample:p.sample,baseUrl:p.baseUrl})}catch(b){b instanceof on&&T(b.message),T(`sandbox create failed: ${b instanceof Error?b.message:String(b)}`)}x(`sandbox ${y.name} ready.`),x(` source: ${y.fromTenant} (sampled ${Math.round(y.sampleFraction*100)}%, redacted)`),x(` url: ${y.url}`),x(` expires: ${y.expiresAt}`)}),Wr.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async p=>{let f=Ol();await Ni(f).catch(()=>[]);let y;try{y=await ou(f,p)}catch(b){T(`sandbox destroy failed: ${b instanceof Error?b.message:String(b)}`)}y||T(`no sandbox named '${p}'.`),x(`destroyed sandbox ${y.name} (dropped ${y.database}).`)}),Wr.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let p=Ol(),f=await Ni(p).catch(()=>[]),y=await bs(),{active:b}=Oi(y);if(b.length===0)x("no active sandboxes.");else{for(let _ of b)x(` ${_.name} from=${_.fromTenant} expires=${_.expiresAt} ${_.url}`);x(`
|
|
1689
|
+
${b.length} active sandbox(es).`)}f.length>0&&x(`(reaped ${f.length} expired sandbox(es).)`)}),s.command("export").description("Snapshot the live instance into turbobase/bundle.json.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",ws).action(async p=>{let{baseUrl:f,token:y}=await V(p.baseUrl),b=new K({baseUrl:f,token:y}),_;try{_=await le("exporting instance config",()=>b.configExport())}catch(P){P instanceof ue&&(P.status===401||P.status===403)&&T("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),T(`ext export failed: ${P instanceof Error?P.message:String(P)}`)}let m=typeof _.serialized=="string"?_.serialized:`${JSON.stringify(_.manifest??_,null,2)}
|
|
1690
|
+
`,S=ae(process.cwd(),p.out,cn);await ce.mkdir(Qn(S),{recursive:!0}),await ce.writeFile(S,m,"utf8"),x(`wrote ${p.out}/${cn} (${m.split(`
|
|
1691
|
+
`).length} lines).`)});let Ul=s.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),og=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Dl=()=>process.env.TURBOBASE_HOME?.trim()||Pt(WT(),".turbobase"),ig=()=>"1.1.12",es=async()=>Promise.all(og.map(async p=>{try{return await import(p.name),{...p,present:!0}}catch{return{...p,present:!1}}}));Ul.command("status").description("Report which optional native packages are installed.").action(async()=>{let p=await es();for(let f of p)x(`${f.present?Ne.success("installed"):Ne.warn("missing")} ${k.bold(f.name)} \u2014 ${f.needs}`);p.some(f=>!f.present)&&x(`
|
|
1692
|
+
run \`${rn} ext extras install\` to fetch them into ${Dl()}.`)}),Ul.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let p=await es();if(p.every(I=>I.present)){x(Ne.success("extras already installed \u2014 nothing to do."));return}let f=Dl();await ce.mkdir(f,{recursive:!0});let y=p.filter(I=>!I.present).map(I=>I.name),b=Ri(process.platform,process.arch),_=async(I,C)=>{let{code:O,stderr:J}=await Xn("npm",["install","--prefix",f,"--no-audit","--no-fund",...I]);O!==0&&T(`extras install failed while installing ${C} (npm exited ${O}).
|
|
1693
|
+
${J.trim()}
|
|
1694
|
+
These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},m=y.filter(I=>I!=="isolated-vm");if(m.length>0){let I=m.map(C=>`${C}@${xi[C]??"latest"}`);x(`installing ${I.join(", ")} \u2192 ${f}/node_modules \u2026`),await _(I,m.join(", "))}if(y.includes("isolated-vm")){let I=`isolated-vm@${xi["isolated-vm"]}`;if(x(`installing ${I} \u2192 ${f}/node_modules \u2026`),await _(["--ignore-scripts",I],"isolated-vm"),Yd.includes(b)){let O=`${Ti}@${ig()}`;x(`fetching ${O} (no upstream binary for ${b}) \u2026`);let{code:J}=await Xn("npm",["install","--prefix",f,"--no-audit","--no-fund","--ignore-scripts",O]);J!==0&&x(Ne.warn(`could not fetch ${O} \u2014 falling back to a source build.`))}let C=await Qd({home:f});C.length>0&&x(` ${Ne.success("prebuilt")} ${C.join(", ")} \u2192 isolated-vm/prebuilds/${b}`)}let S=await es(),P=S.filter(I=>!I.present).map(I=>I.name);if(P.includes("isolated-vm")){x(Ne.warn(`no prebuilt isolated-vm for ${b} / Node ${process.versions.node} (${Ei()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:I}=await Xn("npm",["rebuild","--prefix",f,"isolated-vm"]);I===0&&(S=await es(),P=S.filter(C=>!C.present).map(C=>C.name))}P.length>0&&T(`npm succeeded but ${P.join(", ")} still will not load \u2014 no prebuilt binary for ${b} / Node ${process.versions.node} (${Ei()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),x(Ne.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let ts=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return ts.command("deploy").description("Enqueue a server-side release deploy. UPLOADS the SDF project src/ from the checkout (the producer swap) when present; else a solution-only live-fetch deploy. An approved target requires --approved-by.").requiredOption("--target <mode>","Deploy posture: auto (apply now) | approved (needs a recorded approval).").option("--solution <id>","The solution id the release delivers (omit for an upload-only deploy).").option("--project <dir>","SDF project dir whose src/ is uploaded (default: cwd).").option("--git-repo <repo>","Git provenance LINK: source repo (default $GITHUB_REPOSITORY or `git remote get-url origin`).").option("--git-ref <ref>","Git provenance LINK: ref/branch/tag (default $GITHUB_REF).").option("--ref <committish>","Git provenance: the ref/branch/tag/sha the upload was built from; resolved to a commit sha via `git rev-parse` (default $GITHUB_SHA or HEAD).").option("--pr-url <url>","Git provenance LINK: the PR this deploy came from (default $PR_URL).").option("--approved-by <email>","Record the approval (REQUIRED for --target approved).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async p=>{let f=p.target==="approved"?"approved":p.target==="auto"?"auto":null;f||T(`--target must be 'auto' or 'approved' (got '${p.target}').`);let y=await a0(ae(process.cwd(),p.project??".")),b=Object.keys(y).length;!p.solution&&b===0&&T("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let m=(p.ref?await Nl(["rev-parse",p.ref])??p.ref:null)??process.env.GITHUB_SHA??await Nl(["rev-parse","HEAD"]),S=p.gitRepo??process.env.GITHUB_REPOSITORY??await Nl(["remote","get-url","origin"]),P=p.gitRef??process.env.GITHUB_REF??null,I=p.prUrl??process.env.PR_URL??null,{baseUrl:C,token:O}=await V(p.baseUrl),J=new K({baseUrl:C,token:O}),M;try{M=await J.releaseDeploy({solutionId:p.solution??null,target:f,approvedBy:p.approvedBy??null,files:b>0?y:null,gitRepo:S,gitRef:P,gitSha:m,prUrl:I})}catch(de){ye(de,"releases:write","release deploy"),de instanceof ue&&de.status===404&&T("solution_not_found \u2014 no solution with that id."),T(`release deploy failed: ${de instanceof Error?de.message:String(de)}`)}x(`release ${M.releaseId} enqueued \u2192 taskId=${M.taskId} (target=${f}`+(b>0?`, uploaded ${b} bundle file(s)`:", live-fetch")+")."),p.follow&&await $i(()=>J.releaseStatus(M.releaseId),`release ${M.releaseId}`,p.intervalMs)}),ts.command("status").argument("<id>","The release id").description("Show a release deploy job's status; with --follow, poll to completion.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async(p,f)=>{let{baseUrl:y,token:b}=await V(f.baseUrl),_=new K({baseUrl:y,token:b});if(f.follow){await $i(()=>_.releaseStatus(p),`release ${p}`,f.intervalMs);return}let m;try{m=await _.releaseStatus(p)}catch(S){ye(S,"releases:write","release status"),S instanceof ue&&S.status===404&&T(`release ${p} not found.`),T(`release status failed: ${S instanceof Error?S.message:String(S)}`)}x(`release ${p}: status=${m.releaseStatus??"?"} stage=${m.stage} ${m.percent}%`+(m.runStatus?` (${m.runStatus})`:"")),m.outputTail&&x(m.outputTail.replace(/\n+$/,""))}),ts.command("rollback").argument("<id>","The release id to roll back").description("Roll back a live release (LIFO-guarded; server-side reverse deploy).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,f)=>{let{baseUrl:y,token:b}=await V(f.baseUrl),_=new K({baseUrl:y,token:b}),m;try{m=await _.releaseRollback(p)}catch(S){ye(S,"releases:write","release rollback"),S instanceof ue&&S.status===404&&T(`release ${p} not found.`),S instanceof ue&&S.status===409&&T(`release ${p} cannot be rolled back (not live, or a newer release advanced past it).`),T(`release rollback failed: ${S instanceof Error?S.message:String(S)}`)}x(`release ${m.releaseId} rolled back \u2192 status=${m.release?.status??"rolled_back"}.`)}),ts.command("list").description("List releases, newest-first, with delivered titles + latest status.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async p=>{let{baseUrl:f,token:y}=await V(p.baseUrl),b=new K({baseUrl:f,token:y}),_;try{_=await b.releaseList()}catch(m){ye(m,"releases:write","release list"),T(`release list failed: ${m instanceof Error?m.message:String(m)}`)}if(_.length===0){x("no releases.");return}if(qe())x(Qt(_.map(m=>[m.id,br(m.status),m.target,m.backend,m.solutionTitles?.length?m.solutionTitles.map(S=>`"${S}"`).join(", "):k.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let m of _){let S=m.solutionTitles?.length?` "${m.solutionTitles.join('", "')}"`:"";x(` ${m.id} ${m.status.padEnd(11)} target=${m.target} backend=${m.backend}${S}`)}x(`
|
|
1695
|
+
${_.length} release(s).`)}),e.command("mcp").description("Run the local stdio authoring MCP server, for clients pointed at a process rather than a URL. (The .mcp.json that `project init` writes uses the instance's HTTP servers instead.)").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async p=>{let{runAuthoringMcpServer:f}=await Promise.resolve().then(()=>(rg(),tg));await f({baseUrl:p.baseUrl})}),e.addHelpText("after",["","Common flows:"," turbobase auth login --base-url https://acme.turbobase.app --token tb_pat_\u2026"," turbobase project init && turbobase project types"," turbobase ext new hook --record salesOrder && turbobase ext test hooks/\u2026"," turbobase ext deploy --to prod"," turbobase apps deploy my-app ./app","","Run `turbobase <group> --help` for a group (auth, project, ext, apps, kb, sandbox, mcp).","Docs: https://docs.turbobase.io/cli/overview/"].join(`
|
|
1696
|
+
`)),t&&void 0,e}function s0(t,e,r){let n=s=>{let o=new RegExp(`${s}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return o?o[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 Cl(){let t=ae(process.cwd(),ws,cn),e;try{e=await ce.readFile(t,"utf8")}catch{T(`no bundle found at ${ws}/${cn} \u2014 run \`turbobase ext export\` first.`)}try{return cu(e)}catch(r){T(`bundle is invalid: ${r instanceof Error?r.message:String(r)}`)}}function o0(t,e){x(`plan against ${e}:`);for(let r of t.add)x(` ${Ot.add(`${r.kind} ${r.id}`)}`);for(let r of t.change)x(` ${Ot.change(`${r.kind} ${r.id}`)}`);for(let r of t.destroy)x(` ${Ot.destroy(`${r.kind} ${r.id}`)}`);x(`
|
|
1697
|
+
${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 i0(t){try{let r=new URL(t).hostname.split(".")[0];return r&&r!=="localhost"?r:void 0}catch{return}}function Xn(t,e,r){return new Promise(n=>{let s=zl(t,e,{stdio:["ignore","inherit","pipe"],env:{...process.env,...r}}),o="";s.stderr?.on("data",i=>{let a=i.toString();o+=a,process.stderr.write(a)}),s.on("error",i=>n({code:-1,stderr:i.message})),s.on("exit",i=>n({code:i??-1,stderr:o}))})}function Ol(){let t=process.env.SANDBOX_LOCAL_DATABASE_URL??"postgres://postgres:postgres@127.0.0.1:54322/postgres",e=async(r,n)=>{let s=n?t.replace(/\/[^/]*$/,`/${n}`):t,o=await Xn("psql",[s,"-v","ON_ERROR_STOP=1","-c",r]);if(o.code!==0)throw new Error(`psql failed (exit ${o.code}): ${o.stderr.trim()}`)};return{target:()=>t,createDatabase:async r=>{await e(`CREATE DATABASE ${r};`)},replayMigrations:async r=>{let n=t.replace(/\/[^/]*$/,`/${r}`),s=await Xn("supabase",["migration","up","--db-url",n]);if(s.code!==0)throw new Error(`supabase migration up failed (exit ${s.code}): ${s.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,s)=>{let o=Object.keys(s[0]??{});if(o.length===0)return;let i=s.map(a=>`(${o.map(l=>a[l]===null||a[l]===void 0?"NULL":`'${String(a[l]).replace(/'/g,"''")}'`).join(", ")})`).join(", ");await e(`INSERT INTO turbobase.${n} (${o.join(", ")}) VALUES ${i};`,r)},dropDatabase:async r=>{await e(`DROP DATABASE IF EXISTS ${r} WITH (FORCE);`)}}}async function a0(t){let e=ae(t,"src"),r={},n=async s=>{let o;try{o=await ce.readdir(s,{withFileTypes:!0})}catch{return}for(let i of o){let a=Pt(s,i.name);if(i.isDirectory())await n(a);else if(i.isFile()){let l=Ho(e,a).split(jl).join("/");r[l]=await ce.readFile(a,"utf8")}}};return await n(e),r}function Nl(t){return new Promise(e=>{let r=zl("git",t,{stdio:["ignore","pipe","ignore"]}),n="";r.stdout?.on("data",s=>{n+=s.toString()}),r.on("error",()=>e(null)),r.on("exit",s=>e(s===0&&n.trim()?n.trim():null))})}var c0=!1;c0&&Ll().parseAsync(process.argv).catch(t=>T(t instanceof Error?t.message:String(t)));Ll().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
|
|
1593
1698
|
`),process.exit(1)});
|