@turbobase/cli 1.1.15 → 1.1.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/turbobase-standalone.mjs +159 -133
- package/dist/turbobase.js +171 -145
- package/package.json +1 -1
package/dist/turbobase.js
CHANGED
|
@@ -1,27 +1,27 @@
|
|
|
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
|
|
5
|
-
* ${
|
|
4
|
+
var vg=Object.create;var Jo=Object.defineProperty;var Sg=Object.getOwnPropertyDescriptor;var kg=Object.getOwnPropertyNames;var _g=Object.getPrototypeOf,$g=Object.prototype.hasOwnProperty;var j=(t,e)=>()=>(t&&(e=t(t=0)),e);var L=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Kc=(t,e)=>{for(var n in e)Jo(t,n,{get:e[n],enumerable:!0})},xg=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of kg(e))!$g.call(t,s)&&s!==n&&Jo(t,s,{get:()=>e[s],enumerable:!(r=Sg(e,s))||r.enumerable});return t};var Vc=(t,e,n)=>(n=t!=null?vg(_g(t)):{},xg(e||!t||!t.__esModule?Jo(n,"default",{value:t,enumerable:!0}):n,t));function Xn(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var ss=j(()=>{});import{z as Yt}from"zod";function os(t){let e=Zo.safeParse(t);return e.success?(e.data.inputs??[]).filter(n=>n.type==="connection"):[]}function Yo(t,e){let n=Zo.safeParse(t);if(!n.success)throw new At(`invalid manifest: ${n.error.issues.map(s=>`${s.path.join(".")||"(root)"}: ${s.message}`).join("; ")}`);if(Gc.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 r=JSON.stringify(n.data);if(Gc.test(r))throw new At("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var Wc,Jc,Zo,At,Gc,Zc=j(()=>{Wc=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()}),Jc=Yt.discriminatedUnion("type",[Wc]),Zo=Yt.object({inputs:Yt.array(Jc).optional()}).passthrough(),At=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};Gc=/\bconnection[_-]?id\b["']?\s*[:=]/i});var is,Qo=j(()=>{is=["before_read","before_save","after_save","before_sync","after_sync","on_sync_failure"]});import{z as Oe}from"zod";var Xo,Yc,Qc=j(()=>{ss();Qo();Xo=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(is),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"})}),Yc=Xn({kind:"hook",schema:Xo,factoryName:"defineHook"})});var Xc=j(()=>{Qc();Qo()});var as,ei=j(()=>{as=["after_canonicalize_inbound","after_sync_success_outbound"]});import{z as $e}from"zod";var ti,eu,tu=j(()=>{ss();ei();ti=$e.object({id:$e.string().min(1,"conduit id must be non-empty"),on:$e.enum(as),from:$e.object({source:$e.string().min(1,"from.source must be non-empty"),recordType:$e.string().min(1,"from.recordType must be non-empty"),when:$e.unknown().optional()}),to:$e.object({source:$e.string().min(1,"to.source must be non-empty"),recordType:$e.string().min(1,"to.recordType must be non-empty")}),mode:$e.enum(["dual-bind","one-shot"]).optional(),transform:$e.unknown(),idempotencyKey:$e.unknown().optional(),cycleBudget:$e.number().int().positive().optional(),conflictStrategy:$e.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:$e.number().int().positive().optional(),description:$e.string().optional(),systemReserved:$e.boolean().optional()}).superRefine((t,e)=>{typeof t.transform!="function"&&e.addIssue({code:"custom",path:["transform"],message:"transform must be a function"});let n=t.from?.when;n!==void 0&&typeof n!="function"&&e.addIssue({code:"custom",path:["from","when"],message:"from.when, when present, must be a function"});let r=t.idempotencyKey;r!==void 0&&typeof r!="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"})}),eu=Xn({kind:"conduit",schema:ti,factoryName:"defineConduit"})});var nu=j(()=>{tu();ei()});async function Ag(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 n=await e.default(t,{defaultNonNullable:!1});return e.astToString(n)}async function ls(t,e={}){return(e.transform??Ag)(t)}var ni=j(()=>{});function ri(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 ru(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function si(t){return`${ru(t.source)}${ru(t.recordType)}`}function Ig(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function Cg(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 oi(t){let e=si(t),n=[`${t.source}:${t.recordType}`+(t.table?` \u2192 turbobase.${t.table}`:" (no backing table)")+`${t.listOnly?" (list-only)":""} \u2014 origin: ${t.origin}.`];t.description&&n.push(t.description);let r=n.length===1?`/** ${n[0]} */`:`/**
|
|
5
|
+
* ${n.join(`
|
|
6
6
|
* `)}
|
|
7
|
-
*/`;if(t.columns.length===0)return`${
|
|
7
|
+
*/`;if(t.columns.length===0)return`${r}
|
|
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=ri(o.pgType),a=o.nullable?"?":"",c=o.nullable?" | null":"";return` /** ${Cg(o)} */
|
|
12
|
+
${Ig(o.name)}${a}: ${i}${c};`});return`${r}
|
|
13
13
|
export interface ${e} {
|
|
14
14
|
${s.join(`
|
|
15
15
|
`)}
|
|
16
|
-
}`}function
|
|
16
|
+
}`}function cs(t){return[...t.records].sort((r,s)=>`${r.source}:${r.recordType}`.localeCompare(`${s.source}:${s.recordType}`)).map(oi).join(`
|
|
17
17
|
|
|
18
|
-
`)}function
|
|
19
|
-
`)}var
|
|
18
|
+
`)}function su(t){let e=new Map;for(let r of t.records){if(!r.table)continue;let s=e.get(r.table);s||e.set(r.table,s=new Map);for(let o of r.columns)s.set(o.name,(s.get(o.name)??!0)&&o.nullable)}let n={};for(let[r,s]of[...e].sort(([o],[i])=>o.localeCompare(i)))s.get("pg_row_id")===!1?n[r]="pg_row_id":s.get("external_id")===!1&&(n[r]="external_id");return n}function Og(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function ii(t){let e=su(t);return["/**"," * The column each table can be keyset-seeked on \u2014 pass it to `selectPage`:"," *"," * selectPage(`vendor_credit?select=*`, { sortKey: SEEK_KEYS.vendor_credit })"," *"," * A seek key must be NOT NULL and UNIQUE. Hard-coding one instead goes stale"," * silently: a table that gains `pg_row_id` has its `external_id` made"," * nullable in the same change, and seeking on a nullable column drops rows",' * with no error \u2014 the column still exists, so an "is it there?" check on the'," * override stays green. Read it from here and regenerating types fixes it."," *"," * A table with no entry has no safe single-column key (line tables: their key"," * is the composite `(parent_pg_row_id, line_index)`). Page those by filtering"," * to one parent rather than seeking across all of them."," */","export const SEEK_KEYS = {",...Object.entries(e).map(([r,s])=>` ${Og(r)}: '${s}',`),"} as const satisfies Record<string, string>;","","/** Tables with a keyset-safe seek key. */","export type SeekableTable = keyof typeof SEEK_KEYS;"].join(`
|
|
19
|
+
`)}var ai=j(()=>{});function Ng(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function ou(t,e,n){let r=await n(t,{headers:{Accept:"application/json",Authorization:`Bearer ${e}`}});if(!r.ok)throw new Error(`types-gen: GET ${t} failed (${r.status} ${r.statusText})`);return r.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 n=Ng(t.baseUrl),r=await ou(n.records,t.token,e);if(!r||!Array.isArray(r.records))throw new Error("types-gen: /v1/catalog/records did not return a { records: [...] } envelope");let s=cs(r),o=[jg,"// ----- Record shapes (from /v1/catalog/records) -----",s,"// ----- Keyset seek keys (derived from column nullability) -----",ii(r)];if(!t.recordsOnly){let i=await ou(n.openapi,t.token,e),a=await ls(i,t.openApi);o.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return o.join(`
|
|
20
20
|
|
|
21
21
|
`)+`
|
|
22
|
-
`}var
|
|
23
|
-
`)});var
|
|
24
|
-
`,{mode:384})}async function ad(t){let e=We(t.baseUrl),r=await Yr(),n=new Date().toISOString();return r.tenants[e]={token:t.token,updatedAt:n},r.active=e,await ai(r),{baseUrl:e,token:t.token,updatedAt:n}}async function ht(t){let e=await Yr();if(t){let o=We(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 ls(t){let e=We(t),r=await Yr(),n=r.tenants[e];return n?(r.active=e,await ai(r),{baseUrl:e,token:n.token,updatedAt:n.updatedAt}):null}async function li(t){let e=await Yr(),r=t?We(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 ai(e),r}async function Ct(){let t=await Yr();return Object.entries(t.tenants).map(([e,r])=>({baseUrl:e,token:r.token,updatedAt:r.updatedAt}))}var cs=j(()=>{});function ld(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 cd(t){return t.replace(/\/+$/,"")}function ci(t=process.env){let e=(t[gr]??"").trim(),r=(t[ds]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function di(t){let e;try{e=new URL(t)}catch{return`${gr} 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:`${gr} 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 ie,H,gr,ds,Qr,yr=j(()=>{ie=class extends Error{constructor(r,n,s){super(r);this.status=n;this.body=s;this.name="ApiError"}status;body};H=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=cd(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 c=ld(a);throw new ie(`${e} ${r} \u2192 ${o.status}${c?`: ${c}`:""}`,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)}`)}releaseFiles(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/files`)}releasePush(e,r){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/push`,{files:r.files,target:r.target,...r.approvedBy?{approvedBy:r.approvedBy}:{}})}releaseStatus(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/status`)}releaseRollback(e){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/rollback`)}},gr="TURBOBASE_REGISTRY_URL",ds="TURBOBASE_REGISTRY_TOKEN";Qr=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=cd(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 c=ld(a);throw new ie(`${e} ${r} \u2192 ${o.status}${c?`: ${c}`:""}`,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 Pg(t){if(Eg.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function Ig(){return{name:"extension-self-contained-fence",setup(t){t.onResolve({filter:/.*/},e=>e.kind==="entry-point"?null:Pg(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:")||Og(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:Ag,loader:"js"}))}}}function Og(t){let e=t.startsWith("node:")?t.slice(5):t;return Cg.has(e.split("/")[0])}function dd(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 Ng(){try{return(await import("esbuild")).build}catch(t){throw dd("esbuild",t)}}async function jg(){try{return(await import("isolated-vm")).default}catch(t){throw dd("isolated-vm",t)}}async function us(t){let e=await Ng(),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:[Ig()]})}catch(n){let o=n.errors?.map(i=>i.text).filter(Boolean).join("; ");throw new ui(o||`extension bundle failed: ${String(n)}`)}return r.outputFiles?.[0]?.text??""}async function Xr(t,e,r={}){let n=r.timeoutMs??200,s=r.memoryLimitMb??16,o=r.member??"run",i={patches:[],logs:[]},a=await jg(),c=new a.Isolate({memoryLimit:s});try{let d=await c.createContext(),u=d.global,h=new a.Callback(I=>{let L=JSON.parse(String(I));i.rejection||(i.rejection=L)}),S=new a.Callback(I=>{i.patches.push(JSON.parse(String(I)))}),b=new a.Callback(I=>{let L=JSON.parse(String(I));i.logs.push(L)}),w=new a.Callback(I=>{i.result=JSON.parse(String(I))});await u.set("__tb_reject",h),await u.set("__tb_patch",S),await u.set("__tb_log",b),await u.set("__tb_result",w),await u.set("__tb_ctx_json",JSON.stringify(zg(e)));let k=Lg(t,o),E=await(await c.compileScript(k)).run(d,{timeout:n,promise:!0});return o==="when"?{effects:i,whenResult:!!E}:{effects:i}}finally{c.isDisposed||c.dispose()}}function zg(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 Lg(t,e){return`
|
|
22
|
+
`}var jg,iu=j(()=>{ni();ai();ai();ni();jg=["/**"," * 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(`
|
|
23
|
+
`)});var li=j(()=>{ss();Zc();Xc();nu();iu()});import{homedir as Lg}from"node:os";import{join as au}from"node:path";import{promises as ci}from"node:fs";function We(t){return t.trim().replace(/\/+$/,"")}function cu(){let t=process.env.TURBOBASE_HOME??au(Lg(),".turbobase");return{dir:t,file:au(t,"credentials")}}function lu(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function er(){let{file:t}=cu(),e;try{let o=await ci.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 n=e;if(n.tenants&&typeof n.tenants=="object"){let o={};for(let[a,c]of Object.entries(n.tenants))lu(c)&&(o[a]={token:c.token,updatedAt:c.updatedAt});return{active:typeof n.active=="string"&&o[n.active]?n.active:void 0,tenants:o}}let r={};for(let[o,i]of Object.entries(n))lu(i)&&(r[o]={token:i.token,updatedAt:i.updatedAt});return{active:zg(r),tenants:r}}function zg(t){let e,n="";for(let[r,s]of Object.entries(t))(!e||String(s.updatedAt)>n)&&(e=r,n=String(s.updatedAt));return e}async function ui(t){let{dir:e,file:n}=cu();await ci.mkdir(e,{recursive:!0,mode:448}),await ci.writeFile(n,JSON.stringify(t,null,2)+`
|
|
24
|
+
`,{mode:384})}async function uu(t){let e=We(t.baseUrl),n=await er(),r=new Date().toISOString();return n.tenants[e]={token:t.token,updatedAt:r},n.active=e,await ui(n),{baseUrl:e,token:t.token,updatedAt:r}}async function gt(t){let e=await er();if(t){let o=We(t),i=e.tenants[o];return i?{baseUrl:o,token:i.token,updatedAt:i.updatedAt}:null}let n=Object.keys(e.tenants),r=e.active&&e.tenants[e.active]?e.active:n.length===1?n[0]:void 0;if(!r)return null;let s=e.tenants[r];return{baseUrl:r,token:s.token,updatedAt:s.updatedAt}}async function us(t){let e=We(t),n=await er(),r=n.tenants[e];return r?(n.active=e,await ui(n),{baseUrl:e,token:r.token,updatedAt:r.updatedAt}):null}async function di(t){let e=await er(),n=t?We(t):e.active&&e.tenants[e.active]?e.active:Object.keys(e.tenants).length===1?Object.keys(e.tenants)[0]:void 0;if(!n||!e.tenants[n])return null;if(delete e.tenants[n],e.active===n){let r=Object.keys(e.tenants);e.active=r.length===1?r[0]:void 0}return await ui(e),n}async function Ct(){let t=await er();return Object.entries(t.tenants).map(([e,n])=>({baseUrl:e,token:n.token,updatedAt:n.updatedAt}))}var ds=j(()=>{});function du(t){if(typeof t=="string")return t.trim().slice(0,200);if(!t||typeof t!="object")return"";let e=t,n=typeof e.message=="string"&&e.message?e.message:e.error;return typeof n=="string"?n.trim().slice(0,200):""}function pu(t){return t.replace(/\/+$/,"")}function pi(t=process.env){let e=(t[bn]??"").trim(),n=(t[ps]??"").trim();return!e||!n?null:{registryUrl:e,token:n}}function fi(t){let e;try{e=new URL(t)}catch{return`${bn} is not a valid URL: ${t}`}if(e.protocol==="https:")return null;let n=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]";return e.protocol==="http:"&&n?null:`${bn} 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 se,B,bn,ps,tr,Qt=j(()=>{se=class extends Error{constructor(n,r,s){super(n);this.status=r;this.body=s;this.name="ApiError"}status;body};B=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=pu(e.baseUrl),this.token=e.token;let n=e.fetchImpl??fetch;if(typeof n!="function")throw new Error("ExtensionsApi: no fetch implementation available");this.fetchImpl=n}async request(e,n,r,s){let o=await this.fetchImpl(`${this.baseUrl}${n}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/json",...r!==void 0?{"Content-Type":"application/json"}:{},...s??{}},...r!==void 0?{body:JSON.stringify(r)}:{}}),i=await o.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!o.ok){let c=du(a);throw new se(`${e} ${n} \u2192 ${o.status}${c?`: ${c}`:""}`,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 n=e?`?kind=${encodeURIComponent(e)}`:"";return(await this.request("GET",`/v1/extensions${n}`)).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,n){let r=n&&n>0?`?limit=${Math.floor(n)}`:"";return(await this.request("GET",`/v1/extensions/${encodeURIComponent(e)}/logs${r}`)).logs??[]}async catalogRecords(){return(await this.request("GET","/v1/catalog/records")).records??[]}async conduitEvents(e,n={}){let r=new URLSearchParams;n.since&&r.set("since",n.since),n.limit&&n.limit>0&&r.set("limit",String(Math.floor(n.limit)));let s=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/conduits/${encodeURIComponent(e)}/events${s}`)).events??[]}async bindings(e={}){let n=new URLSearchParams;e.status&&n.set("status",e.status),e.limit&&e.limit>0&&n.set("limit",String(Math.floor(e.limit)));let r=n.toString()?`?${n.toString()}`:"";return(await this.request("GET",`/v1/bindings${r}`)).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,n,r={}){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/push`,{files:n,...r.note?{note:r.note}:{},...r.meta?{meta:r.meta}:{}},r.proposalId?{"x-proposal-id":r.proposalId}:void 0)}learningsPending(e={}){let n=new URLSearchParams;e.app&&n.set("app",e.app),e.section&&n.set("section",e.section),e.limit!==void 0&&n.set("limit",String(e.limit)),e.group===!1&&n.set("group","false");let r=n.toString();return this.request("GET",`/v1/learnings/pending${r?`?${r}`:""}`)}rulesPending(e={}){let n=new URLSearchParams;e.app&&n.set("app",e.app),e.limit!==void 0&&n.set("limit",String(e.limit));let r=n.toString();return this.request("GET",`/v1/learnings/rules-pending${r?`?${r}`:""}`)}rulesPush(e,n={}){return this.request("POST","/v1/learnings/push-rules",{planToken:e,...n.app?{app:n.app}:{},...n.limit!==void 0?{limit:n.limit}:{},...n.group===!1?{group:!1}:{}})}skillsList(e={}){let n=new URLSearchParams;e.status&&n.set("status",e.status);let r=n.toString();return this.request("GET",`/v1/skills${r?`?${r}`:""}`)}skillsPublish(e){return this.request("POST","/v1/skills/publish",{slugs:[...e]})}skillsUnpublish(e){return this.request("POST","/v1/skills/unpublish",{slugs:[...e]})}skillsRollback(e){return this.request("POST","/v1/skills/rollback",{versionNo:e})}skillsReleases(){return this.request("GET","/v1/skills/releases")}skillsDelete(e){return this.request("DELETE",`/v1/skills/${encodeURIComponent(e)}`)}learningsPushKb(e,n={}){return this.request("POST","/v1/learnings/push-kb",{planToken:e,...n.app?{app:n.app}:{},...n.section?{section:n.section}:{},...n.limit!==void 0?{limit:n.limit}:{},...n.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,n){return this.request("DELETE",`/v1/tables/${encodeURIComponent(e)}?confirm=${encodeURIComponent(n)}`)}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,n){return(await this.request("PATCH",`/v1/guardrails/${encodeURIComponent(e)}`,n)).guardrail}guardrailDelete(e){return this.request("DELETE",`/v1/guardrails/${encodeURIComponent(e)}`)}guardrailTest(e){return this.request("POST","/v1/guardrails/test",e)}releaseDeploy(e){return this.request("POST","/v1/releases/deploy",{...e.solutionId?{solutionId:e.solutionId}:{},target:e.target,...e.approvedBy?{approvedBy:e.approvedBy}:{},...e.files?{files:e.files}:{},...e.gitRepo?{gitRepo:e.gitRepo}:{},...e.gitRef?{gitRef:e.gitRef}:{},...e.gitSha?{gitSha:e.gitSha}:{},...e.prUrl?{prUrl:e.prUrl}:{}})}async releaseList(){return(await this.request("GET","/v1/releases")).releases??[]}releaseGet(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}`)}releaseFiles(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/files`)}releasePush(e,n){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/push`,{files:n.files,target:n.target,...n.approvedBy?{approvedBy:n.approvedBy}:{}})}releaseStatus(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/status`)}releaseRollback(e){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/rollback`)}},bn="TURBOBASE_REGISTRY_URL",ps="TURBOBASE_REGISTRY_TOKEN";tr=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=pu(e.registryUrl),this.token=e.token;let n=e.fetchImpl??fetch;if(typeof n!="function")throw new Error("RegistryApi: no fetch implementation available");this.fetchImpl=n}async request(e,n,r){let s={Authorization:`Bearer ${this.token}`,Accept:"application/json"};r!==void 0&&(s["Content-Type"]="application/json");let o=await this.fetchImpl(`${this.registryUrl}${n}`,{method:e,headers:s,...r!==void 0?{body:JSON.stringify(r)}:{}}),i=await o.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!o.ok){let c=du(a);throw new se(`${e} ${n} \u2192 ${o.status}${c?`: ${c}`:""}`,o.status,a)}return a}async list(){return(await this.request("GET","/extensions")).extensions??[]}fetchBundle(e,n){let r=n?`?version=${encodeURIComponent(n)}`:"";return this.request("GET",`/extensions/${encodeURIComponent(e)}${r}`)}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 Dg(t){if(Ug.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function Mg(){return{name:"extension-self-contained-fence",setup(t){t.onResolve({filter:/.*/},e=>e.kind==="entry-point"?null:Dg(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:")||Fg(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:qg,loader:"js"}))}}}function Fg(t){let e=t.startsWith("node:")?t.slice(5):t;return Bg.has(e.split("/")[0])}function fu(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 Hg(){try{return(await import("esbuild")).build}catch(t){throw fu("esbuild",t)}}async function Kg(){try{return(await import("isolated-vm")).default}catch(t){throw fu("isolated-vm",t)}}async function fs(t){let e=await Hg(),n;try{n=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:[Mg()]})}catch(r){let o=r.errors?.map(i=>i.text).filter(Boolean).join("; ");throw new hi(o||`extension bundle failed: ${String(r)}`)}return n.outputFiles?.[0]?.text??""}async function nr(t,e,n={}){let r=n.timeoutMs??200,s=n.memoryLimitMb??16,o=n.member??"run",i={patches:[],logs:[]},a=await Kg(),c=new a.Isolate({memoryLimit:s});try{let u=await c.createContext(),p=u.global,h=new a.Callback(I=>{let z=JSON.parse(String(I));i.rejection||(i.rejection=z)}),k=new a.Callback(I=>{i.patches.push(JSON.parse(String(I)))}),b=new a.Callback(I=>{let z=JSON.parse(String(I));i.logs.push(z)}),v=new a.Callback(I=>{i.result=JSON.parse(String(I))});await p.set("__tb_reject",h),await p.set("__tb_patch",k),await p.set("__tb_log",b),await p.set("__tb_result",v),await p.set("__tb_ctx_json",JSON.stringify(Vg(e)));let T=Gg(t,o),E=await(await c.compileScript(T)).run(u,{timeout:r,promise:!0});return o==="when"?{effects:i,whenResult:!!E}:{effects:i}}finally{c.isDisposed||c.dispose()}}function Vg(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 Gg(t,e){return`
|
|
25
25
|
"use strict";
|
|
26
26
|
(async () => {
|
|
27
27
|
const __tb_ctx = JSON.parse(__tb_ctx_json);
|
|
@@ -90,37 +90,37 @@ ${s.join(`
|
|
|
90
90
|
${e==="transform"?"__tb_result(JSON.stringify(out == null ? null : out));":""}
|
|
91
91
|
return ${e==="when"?"out":"undefined"};
|
|
92
92
|
})()
|
|
93
|
-
`}var
|
|
93
|
+
`}var Ug,qg,hi,Bg,mi=j(()=>{Ug=new Set(["@/sync/hooks","@/sync/hooks/index.js","@/sync/conduits","@/sync/conduits/index.js","@turbobase/extensions","@turbobase/extensions/hook","@turbobase/extensions/conduit"]);qg=`
|
|
94
94
|
export const defineHook = (def) => def;
|
|
95
95
|
export const defineConduit = (def) => def;
|
|
96
96
|
export default defineHook;
|
|
97
|
-
`,
|
|
98
|
-
source: ${JSON.stringify(s)},`:"",i,a;if(
|
|
97
|
+
`,hi=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};Bg=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 gi}from"node:fs";import{join as Wg}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,n){let r=e.name??n,s=e.expect??"pass";try{let{effects:o}=await nr(t,Jg(e.context)),i=o.rejection?"reject":"pass";return{name:r,expected:s,observed:i,pass:i===s,rejection:o.rejection,patchCount:o.patches.length}}catch(o){return{name:r,expected:s,observed:"pass",pass:!1,patchCount:0,error:o instanceof Error?o.message:String(o)}}}async function hs(t,e){let n=await fs(t),r=[];for(let s=0;s<e.length;s+=1)r.push(await Zg(n,e[s],`sample[${s}]`));return r}async function rr(t){let e;try{e=await gi.readdir(t)}catch(r){if(r.code==="ENOENT")return[];throw r}let n=[];for(let r of e.sort()){if(!r.endsWith(".json"))continue;let s=await gi.readFile(Wg(t,r),"utf8"),o=JSON.parse(s),i=Array.isArray(o)?o:[o];for(let a=0;a<i.length;a+=1){let c=i[a];n.push({file:r,fixture:{...c,name:c.name??`${r}${i.length>1?`#${a}`:""}`}})}}return n}function sr(t){return gi.readFile(t,"utf8")}var yi=j(()=>{mi()});function jt(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function Ry(t){let e=t.recordType;if(!e)throw new Qe("record type is required (e.g. --record=salesOrder)");let n=t.event??"before_save",r=t.template??"require-field",s=t.source,o=s?`
|
|
98
|
+
source: ${JSON.stringify(s)},`:"",i,a;if(r==="blank")i=`
|
|
99
99
|
run: (ctx) => {
|
|
100
100
|
// Validate or mutate ctx.payload here. Reject with ctx.reject({...}); mutate
|
|
101
101
|
// with ctx.patch({...}); observe with ctx.log('info', '...').
|
|
102
|
-
},`,a="custom";else if(
|
|
102
|
+
},`,a="custom";else if(r==="require-field"){let k=t.field;if(!k)throw new Qe("require-field template needs --field=<name>");i=`
|
|
103
103
|
run: (ctx) => {
|
|
104
|
-
const v = ctx.payload[${JSON.stringify(
|
|
104
|
+
const v = ctx.payload[${JSON.stringify(k)}];
|
|
105
105
|
if (v === undefined || v === null || v === '') {
|
|
106
106
|
ctx.reject({
|
|
107
107
|
code: 'MANDATORY_FIELD_MISSING',
|
|
108
|
-
field: ${JSON.stringify(
|
|
109
|
-
message: ${JSON.stringify(`${
|
|
108
|
+
field: ${JSON.stringify(k)},
|
|
109
|
+
message: ${JSON.stringify(`${k} is required`)},
|
|
110
110
|
});
|
|
111
111
|
}
|
|
112
|
-
},`,a=`require-field-${
|
|
112
|
+
},`,a=`require-field-${k}`}else if(r==="enforce-format"){let k=t.field;if(!k)throw new Qe("enforce-format template needs --field=<name>");if(!t.regex)throw new Qe("enforce-format template needs --regex=<pattern>");i=`
|
|
113
113
|
run: (ctx) => {
|
|
114
|
-
const v = ctx.payload[${JSON.stringify(
|
|
114
|
+
const v = ctx.payload[${JSON.stringify(k)}];
|
|
115
115
|
if (typeof v === 'string' && v && !/${t.regex}/.test(v)) {
|
|
116
116
|
ctx.reject({
|
|
117
117
|
code: 'INVALID_FORMAT',
|
|
118
|
-
field: ${JSON.stringify(
|
|
119
|
-
message: ${JSON.stringify(`${
|
|
118
|
+
field: ${JSON.stringify(k)},
|
|
119
|
+
message: ${JSON.stringify(`${k} does not match expected format`)},
|
|
120
120
|
});
|
|
121
121
|
}
|
|
122
|
-
},`,a=`enforce-format-${
|
|
123
|
-
* ${t.description??`${a} on ${e}.${
|
|
122
|
+
},`,a=`enforce-format-${k}`}else throw new Qe(`unsupported template: ${r}. Supported: require-field | enforce-format | blank.`);let c=t.id??`custom:${e}:${a}${t.regex?`-${jt(t.regex).slice(0,24)}`:""}`,p=`/**
|
|
123
|
+
* ${t.description??`${a} on ${e}.${n}`}
|
|
124
124
|
*
|
|
125
125
|
* Scaffolded by \`turbobase ext new hook\`. Edit freely, then \`turbobase ext test\` and
|
|
126
126
|
* \`turbobase ext deploy\`.
|
|
@@ -130,10 +130,10 @@ import { defineHook } from '@turbobase/extensions';
|
|
|
130
130
|
export default defineHook<Record<string, unknown>>({
|
|
131
131
|
id: ${JSON.stringify(c)},
|
|
132
132
|
recordType: ${JSON.stringify(e)},
|
|
133
|
-
event: ${JSON.stringify(
|
|
133
|
+
event: ${JSON.stringify(n)},${o}${i}
|
|
134
134
|
});
|
|
135
|
-
`;return{relativePath:`hooks/${e}/${
|
|
136
|
-
* ${t.description??`Bridge ${
|
|
135
|
+
`;return{relativePath:`hooks/${e}/${n}.${a}.ts`,content:p}}function Ey(t){let e=t.recordType;if(!e)throw new Qe("record type is required (e.g. --record=order)");let n=t.source;if(!n)throw new Qe("--source is required (the origin source, e.g. --source=shopify)");let r=t.to;if(!r)throw new Qe("--to is required (the target source, e.g. --to=netsuite)");if(n===r)throw new Qe(`a conduit must bridge two DIFFERENT sources (got --source=${n} --to=${r}); 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(n)}2${jt(r)}:${jt(e)}`,c=`/**
|
|
136
|
+
* ${t.description??`Bridge ${n} ${e} \u2192 ${r} ${s} (${o}).`}
|
|
137
137
|
*
|
|
138
138
|
* Scaffolded by \`turbobase ext new conduit\`. A conduit is a PURE canonical\u2192canonical
|
|
139
139
|
* transform: read ctx, RETURN a { patch, createdFrom } \u2014 never call a source API
|
|
@@ -149,12 +149,12 @@ export default defineConduit<Record<string, unknown>>({
|
|
|
149
149
|
id: ${JSON.stringify(i)},
|
|
150
150
|
on: ${JSON.stringify(o)},
|
|
151
151
|
from: {
|
|
152
|
-
source: ${JSON.stringify(
|
|
152
|
+
source: ${JSON.stringify(n)},
|
|
153
153
|
recordType: ${JSON.stringify(e)},
|
|
154
154
|
// when: (ctx) => true, // optional gate on the inbound payload
|
|
155
155
|
},
|
|
156
156
|
to: {
|
|
157
|
-
source: ${JSON.stringify(
|
|
157
|
+
source: ${JSON.stringify(r)},
|
|
158
158
|
recordType: ${JSON.stringify(s)},
|
|
159
159
|
},
|
|
160
160
|
mode: 'dual-bind',
|
|
@@ -167,7 +167,7 @@ export default defineConduit<Record<string, unknown>>({
|
|
|
167
167
|
// ...mapped canonical fields...
|
|
168
168
|
},
|
|
169
169
|
createdFrom: {
|
|
170
|
-
source: ${JSON.stringify(
|
|
170
|
+
source: ${JSON.stringify(n)},
|
|
171
171
|
recordType: ${JSON.stringify(e)},
|
|
172
172
|
externalId: ctx.externalId,
|
|
173
173
|
},
|
|
@@ -175,19 +175,19 @@ export default defineConduit<Record<string, unknown>>({
|
|
|
175
175
|
},
|
|
176
176
|
idempotencyKey: (ctx) => ${JSON.stringify(`${i}:`)} + ctx.externalId,
|
|
177
177
|
});
|
|
178
|
-
`;return{relativePath:`conduits/${jt(
|
|
178
|
+
`;return{relativePath:`conduits/${jt(n)}-${jt(e)}-to-${jt(r)}-${jt(s)}.ts`,content:c}}function kn(t,e){let n=Py[t];if(!n)throw new Qe(`unknown extension kind '${t}'. Scaffoldable kinds: ${Uu.join(", ")}.`);return n(e)}var Uu,Qe,Py,$i=j(()=>{Uu=["hook","conduit"];Qe=class extends Error{};Py={hook:Ry,conduit:Ey}});function Zb(t){let e=2166136261;for(let n=0;n<t.length;n+=1)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e>>>0}function Yb(t){return _d[Zb(t)%_d.length]}function Qb(t){let e=t.trim().split(/[\s\-_.]+/).filter(n=>/[a-z0-9]/i.test(n));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 $d(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function xd(t,e){let[n,r]=Yb(t),s=$d(Qb(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${$d(e)}">
|
|
179
179
|
<defs>
|
|
180
180
|
<linearGradient id="tile" x1="0" y1="0" x2="1" y2="1">
|
|
181
|
-
<stop offset="0" stop-color="${
|
|
182
|
-
<stop offset="1" stop-color="${
|
|
181
|
+
<stop offset="0" stop-color="${n}"/>
|
|
182
|
+
<stop offset="1" stop-color="${r}"/>
|
|
183
183
|
</linearGradient>
|
|
184
184
|
</defs>
|
|
185
185
|
<rect width="64" height="64" rx="14" fill="url(#tile)"/>
|
|
186
186
|
<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>
|
|
187
187
|
</svg>
|
|
188
|
-
`}var
|
|
189
|
-
`}function
|
|
190
|
-
`}function
|
|
188
|
+
`}var _d,Td=j(()=>{_d=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var Rd,Ed=j(()=>{Rd=Object.freeze({instance:!0,platform:!0,share:"inherit"})});var Ld={};Kc(Ld,{MAIN_TSX:()=>Nd,STYLES_CSS:()=>jd,TSCONFIG:()=>Cd,TURBOBASE_CLIENT:()=>Pd,indexHtml:()=>Od,instanceOriginFromEnv:()=>sw,packageJson:()=>Ad,scaffoldAppFiles:()=>iw,starterApp:()=>aw,viteConfig:()=>Id});function ew(t){let e={name:t.title},n=(t.description??"").trim().slice(0,Xb);return n&&(e.description=n),e.icon="favicon.svg",e.learnings={...Rd},JSON.stringify(e,null,2)+`
|
|
189
|
+
`}function Ad(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)}
|
|
190
|
+
`}function rw(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 sw(t=process.env){let e=(t.TENANT_SLUG??"").trim(),n=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!n))return`https://${e}.${n}`}function Id(t,e={}){let n=rw(e.instanceOrigin);return`import { defineConfig } from 'vite';
|
|
191
191
|
import react from '@vitejs/plugin-react';
|
|
192
192
|
|
|
193
193
|
// A same-origin static SPA served at /a/${t}. \`base\` MUST match that mount
|
|
@@ -201,8 +201,8 @@ import react from '@vitejs/plugin-react';
|
|
|
201
201
|
// you sign in, and the cookies land on localhost:3000. Override the targets
|
|
202
202
|
// with SUPABASE_URL / TURBOBASE_API_URL without editing this file (Vite reads
|
|
203
203
|
// them at boot; restart the dev server after changing one).
|
|
204
|
-
const TENANT = process.env.SUPABASE_URL || '${
|
|
205
|
-
const API = process.env.TURBOBASE_API_URL || '${
|
|
204
|
+
const TENANT = process.env.SUPABASE_URL || '${n??tw}'; // /rest + the Realtime WS
|
|
205
|
+
const API = process.env.TURBOBASE_API_URL || '${n??nw}'; // /v1, /auth, /login, /_app
|
|
206
206
|
|
|
207
207
|
// Where this bundle's assets are requested from. \`turbobase apps deploy\` sets
|
|
208
208
|
// this to /_tb/app-assets/<build-id>/ so the asset URLs name the BUILD, not the
|
|
@@ -234,7 +234,7 @@ export default defineConfig({
|
|
|
234
234
|
},
|
|
235
235
|
build: { outDir: 'dist' },
|
|
236
236
|
});
|
|
237
|
-
`}function
|
|
237
|
+
`}function Od(t){return`<!doctype html>
|
|
238
238
|
<html lang="en">
|
|
239
239
|
<head>
|
|
240
240
|
<meta charset="UTF-8" />
|
|
@@ -247,7 +247,7 @@ export default defineConfig({
|
|
|
247
247
|
<script type="module" src="/src/main.tsx"></script>
|
|
248
248
|
</body>
|
|
249
249
|
</html>
|
|
250
|
-
`}function
|
|
250
|
+
`}function iw(t){return{"package.json":Ad(t.slug),"vite.config.ts":Id(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":ow,"tsconfig.json":Cd,"index.html":Od(t.title),"public/turbobase.json":ew(t),"public/favicon.svg":xd(t.slug,t.title),"src/main.tsx":Nd,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":Pd,"src/styles.css":jd,"README.md":`# ${t.title}
|
|
251
251
|
|
|
252
252
|
\`\`\`sh
|
|
253
253
|
npm install
|
|
@@ -268,7 +268,7 @@ every read comes back "permission denied", which looks like an RLS problem.
|
|
|
268
268
|
|
|
269
269
|
\`CLAUDE.md\` + \`.mcp.json\` wire Claude Code to this instance. \`.mcp.json\` holds a
|
|
270
270
|
live access token and is gitignored \u2014 keep it that way.
|
|
271
|
-
`}}function
|
|
271
|
+
`}}function aw(t){return`import React from 'react';
|
|
272
272
|
import { select } from './lib/turbobase';
|
|
273
273
|
|
|
274
274
|
/** Swap for any record type \u2014 GET /v1/catalog/records lists what this instance has. */
|
|
@@ -294,7 +294,7 @@ export default function App() {
|
|
|
294
294
|
</main>
|
|
295
295
|
);
|
|
296
296
|
}
|
|
297
|
-
`}var
|
|
297
|
+
`}var Xb,Pd,tw,nw,ow,Cd,Nd,jd,zd=j(()=>{Td();Ed();Xb=200;Pd=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
|
|
298
298
|
// Reads go through PostgREST (RLS-scoped); writes go through POST /v1/data/<recordType>.
|
|
299
299
|
// A cold first paint that fans out many reads should use batch() \u2014 ONE request
|
|
300
300
|
// that multiplexes them, sidestepping the per-request rate limiter.
|
|
@@ -904,7 +904,7 @@ export async function selectPage<T = unknown>(
|
|
|
904
904
|
}
|
|
905
905
|
return { rows, nextCursor };
|
|
906
906
|
}
|
|
907
|
-
`;
|
|
907
|
+
`;tw="http://localhost:54331",nw="http://localhost:4100";ow=`node_modules/
|
|
908
908
|
dist/
|
|
909
909
|
build/
|
|
910
910
|
|
|
@@ -916,8 +916,8 @@ build/
|
|
|
916
916
|
!.env.example
|
|
917
917
|
|
|
918
918
|
.DS_Store
|
|
919
|
-
`,
|
|
920
|
-
|
|
919
|
+
`,Cd=`${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)}
|
|
920
|
+
`;Nd=`import React from 'react';
|
|
921
921
|
import { createRoot } from 'react-dom/client';
|
|
922
922
|
import App from './App';
|
|
923
923
|
import './styles.css';
|
|
@@ -927,53 +927,53 @@ createRoot(document.getElementById('root')!).render(
|
|
|
927
927
|
<App />
|
|
928
928
|
</React.StrictMode>,
|
|
929
929
|
);
|
|
930
|
-
`,
|
|
930
|
+
`,jd=`:root { color-scheme: light; font-family: ui-sans-serif, system-ui, sans-serif; }
|
|
931
931
|
* { box-sizing: border-box; }
|
|
932
932
|
body { margin: 0; background: #f8fafc; color: #0f172a; }
|
|
933
|
-
`});import*as
|
|
934
|
-
`);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function Pu(t){return t.description}function Au(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 kr(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 dn=j(()=>{});import*as l from"zod/v4";function Gu(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Wu(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Ui,Iu,Ut,ks,ke,Cu,Ou,jE,Yb,Qb,Di,Ke,un,Nu,xe,Xe,et,Te,$s,ju,qi,zu,Lu,Mi,pn,M,Bi,Uu,Du,zE,xs,Xb,Ts,ew,fn,$r,qu,tw,rw,nw,sw,ow,iw,Fi,aw,lw,Hi,Rs,cw,dw,Es,uw,hn,mn,pw,gn,xr,fw,yn,Ps,As,Is,LE,Cs,Os,Ns,Mu,Bu,Fu,Ki,Hu,bn,Tr,Ku,hw,js,mw,zs,gw,Vi,yw,Ls,bw,ww,vw,Sw,_w,kw,$w,xw,Tw,Rw,Us,Ew,Pw,Ds,Gi,Wi,Ji,Aw,Iw,Cw,Zi,Ow,Nw,jw,zw,Lw,Vu,qs,Uw,Ms,UE,Dw,Rr,qw,DE,wn,Mw,Yi,Bw,Fw,Hw,Kw,Vw,Gw,Ww,_s,Jw,Zw,Yw,vn,Qi,Qw,Xw,ev,tv,rv,nv,sv,ov,iv,av,lv,cv,dv,uv,pv,fv,hv,mv,Er,gv,yv,bv,Bs,wv,vv,Sv,Xi,_v,qE,ME,BE,FE,HE,KE,U,Li,Pr=j(()=>{Ui="2025-11-25",Iu=[Ui,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ut="io.modelcontextprotocol/related-task",ks="2.0",ke=l.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Cu=l.union([l.string(),l.number().int()]),Ou=l.string(),jE=l.looseObject({ttl:l.number().optional(),pollInterval:l.number().optional()}),Yb=l.object({ttl:l.number().optional()}),Qb=l.object({taskId:l.string()}),Di=l.looseObject({progressToken:Cu.optional(),[Ut]:Qb.optional()}),Ke=l.object({_meta:Di.optional()}),un=Ke.extend({task:Yb.optional()}),Nu=t=>un.safeParse(t).success,xe=l.object({method:l.string(),params:Ke.loose().optional()}),Xe=l.object({_meta:Di.optional()}),et=l.object({method:l.string(),params:Xe.loose().optional()}),Te=l.looseObject({_meta:Di.optional()}),$s=l.union([l.string(),l.number().int()]),ju=l.object({jsonrpc:l.literal(ks),id:$s,...xe.shape}).strict(),qi=t=>ju.safeParse(t).success,zu=l.object({jsonrpc:l.literal(ks),...et.shape}).strict(),Lu=t=>zu.safeParse(t).success,Mi=l.object({jsonrpc:l.literal(ks),id:$s,result:Te}).strict(),pn=t=>Mi.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={}));Bi=l.object({jsonrpc:l.literal(ks),id:$s.optional(),error:l.object({code:l.number().int(),message:l.string(),data:l.unknown().optional()})}).strict(),Uu=t=>Bi.safeParse(t).success,Du=l.union([ju,zu,Mi,Bi]),zE=l.union([Mi,Bi]),xs=Te.strict(),Xb=Xe.extend({requestId:$s.optional(),reason:l.string().optional()}),Ts=et.extend({method:l.literal("notifications/cancelled"),params:Xb}),ew=l.object({src:l.string(),mimeType:l.string().optional(),sizes:l.array(l.string()).optional(),theme:l.enum(["light","dark"]).optional()}),fn=l.object({icons:l.array(ew).optional()}),$r=l.object({name:l.string(),title:l.string().optional()}),qu=$r.extend({...$r.shape,...fn.shape,version:l.string(),websiteUrl:l.string().optional(),description:l.string().optional()}),tw=l.intersection(l.object({applyDefaults:l.boolean().optional()}),l.record(l.string(),l.unknown())),rw=l.preprocess(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,l.intersection(l.object({form:tw.optional(),url:ke.optional()}),l.record(l.string(),l.unknown()).optional())),nw=l.looseObject({list:ke.optional(),cancel:ke.optional(),requests:l.looseObject({sampling:l.looseObject({createMessage:ke.optional()}).optional(),elicitation:l.looseObject({create:ke.optional()}).optional()}).optional()}),sw=l.looseObject({list:ke.optional(),cancel:ke.optional(),requests:l.looseObject({tools:l.looseObject({call:ke.optional()}).optional()}).optional()}),ow=l.object({experimental:l.record(l.string(),ke).optional(),sampling:l.object({context:ke.optional(),tools:ke.optional()}).optional(),elicitation:rw.optional(),roots:l.object({listChanged:l.boolean().optional()}).optional(),tasks:nw.optional(),extensions:l.record(l.string(),ke).optional()}),iw=Ke.extend({protocolVersion:l.string(),capabilities:ow,clientInfo:qu}),Fi=xe.extend({method:l.literal("initialize"),params:iw}),aw=l.object({experimental:l.record(l.string(),ke).optional(),logging:ke.optional(),completions:ke.optional(),prompts:l.object({listChanged:l.boolean().optional()}).optional(),resources:l.object({subscribe:l.boolean().optional(),listChanged:l.boolean().optional()}).optional(),tools:l.object({listChanged:l.boolean().optional()}).optional(),tasks:sw.optional(),extensions:l.record(l.string(),ke).optional()}),lw=Te.extend({protocolVersion:l.string(),capabilities:aw,serverInfo:qu,instructions:l.string().optional()}),Hi=et.extend({method:l.literal("notifications/initialized"),params:Xe.optional()}),Rs=xe.extend({method:l.literal("ping"),params:Ke.optional()}),cw=l.object({progress:l.number(),total:l.optional(l.number()),message:l.optional(l.string())}),dw=l.object({...Xe.shape,...cw.shape,progressToken:Cu}),Es=et.extend({method:l.literal("notifications/progress"),params:dw}),uw=Ke.extend({cursor:Ou.optional()}),hn=xe.extend({params:uw.optional()}),mn=Te.extend({nextCursor:Ou.optional()}),pw=l.enum(["working","input_required","completed","failed","cancelled"]),gn=l.object({taskId:l.string(),status:pw,ttl:l.union([l.number(),l.null()]),createdAt:l.string(),lastUpdatedAt:l.string(),pollInterval:l.optional(l.number()),statusMessage:l.optional(l.string())}),xr=Te.extend({task:gn}),fw=Xe.merge(gn),yn=et.extend({method:l.literal("notifications/tasks/status"),params:fw}),Ps=xe.extend({method:l.literal("tasks/get"),params:Ke.extend({taskId:l.string()})}),As=Te.merge(gn),Is=xe.extend({method:l.literal("tasks/result"),params:Ke.extend({taskId:l.string()})}),LE=Te.loose(),Cs=hn.extend({method:l.literal("tasks/list")}),Os=mn.extend({tasks:l.array(gn)}),Ns=xe.extend({method:l.literal("tasks/cancel"),params:Ke.extend({taskId:l.string()})}),Mu=Te.merge(gn),Bu=l.object({uri:l.string(),mimeType:l.optional(l.string()),_meta:l.record(l.string(),l.unknown()).optional()}),Fu=Bu.extend({text:l.string()}),Ki=l.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Hu=Bu.extend({blob:Ki}),bn=l.enum(["user","assistant"]),Tr=l.object({audience:l.array(bn).optional(),priority:l.number().min(0).max(1).optional(),lastModified:l.iso.datetime({offset:!0}).optional()}),Ku=l.object({...$r.shape,...fn.shape,uri:l.string(),description:l.optional(l.string()),mimeType:l.optional(l.string()),size:l.optional(l.number()),annotations:Tr.optional(),_meta:l.optional(l.looseObject({}))}),hw=l.object({...$r.shape,...fn.shape,uriTemplate:l.string(),description:l.optional(l.string()),mimeType:l.optional(l.string()),annotations:Tr.optional(),_meta:l.optional(l.looseObject({}))}),js=hn.extend({method:l.literal("resources/list")}),mw=mn.extend({resources:l.array(Ku)}),zs=hn.extend({method:l.literal("resources/templates/list")}),gw=mn.extend({resourceTemplates:l.array(hw)}),Vi=Ke.extend({uri:l.string()}),yw=Vi,Ls=xe.extend({method:l.literal("resources/read"),params:yw}),bw=Te.extend({contents:l.array(l.union([Fu,Hu]))}),ww=et.extend({method:l.literal("notifications/resources/list_changed"),params:Xe.optional()}),vw=Vi,Sw=xe.extend({method:l.literal("resources/subscribe"),params:vw}),_w=Vi,kw=xe.extend({method:l.literal("resources/unsubscribe"),params:_w}),$w=Xe.extend({uri:l.string()}),xw=et.extend({method:l.literal("notifications/resources/updated"),params:$w}),Tw=l.object({name:l.string(),description:l.optional(l.string()),required:l.optional(l.boolean())}),Rw=l.object({...$r.shape,...fn.shape,description:l.optional(l.string()),arguments:l.optional(l.array(Tw)),_meta:l.optional(l.looseObject({}))}),Us=hn.extend({method:l.literal("prompts/list")}),Ew=mn.extend({prompts:l.array(Rw)}),Pw=Ke.extend({name:l.string(),arguments:l.record(l.string(),l.string()).optional()}),Ds=xe.extend({method:l.literal("prompts/get"),params:Pw}),Gi=l.object({type:l.literal("text"),text:l.string(),annotations:Tr.optional(),_meta:l.record(l.string(),l.unknown()).optional()}),Wi=l.object({type:l.literal("image"),data:Ki,mimeType:l.string(),annotations:Tr.optional(),_meta:l.record(l.string(),l.unknown()).optional()}),Ji=l.object({type:l.literal("audio"),data:Ki,mimeType:l.string(),annotations:Tr.optional(),_meta:l.record(l.string(),l.unknown()).optional()}),Aw=l.object({type:l.literal("tool_use"),name:l.string(),id:l.string(),input:l.record(l.string(),l.unknown()),_meta:l.record(l.string(),l.unknown()).optional()}),Iw=l.object({type:l.literal("resource"),resource:l.union([Fu,Hu]),annotations:Tr.optional(),_meta:l.record(l.string(),l.unknown()).optional()}),Cw=Ku.extend({type:l.literal("resource_link")}),Zi=l.union([Gi,Wi,Ji,Cw,Iw]),Ow=l.object({role:bn,content:Zi}),Nw=Te.extend({description:l.string().optional(),messages:l.array(Ow)}),jw=et.extend({method:l.literal("notifications/prompts/list_changed"),params:Xe.optional()}),zw=l.object({title:l.string().optional(),readOnlyHint:l.boolean().optional(),destructiveHint:l.boolean().optional(),idempotentHint:l.boolean().optional(),openWorldHint:l.boolean().optional()}),Lw=l.object({taskSupport:l.enum(["required","optional","forbidden"]).optional()}),Vu=l.object({...$r.shape,...fn.shape,description:l.string().optional(),inputSchema:l.object({type:l.literal("object"),properties:l.record(l.string(),ke).optional(),required:l.array(l.string()).optional()}).catchall(l.unknown()),outputSchema:l.object({type:l.literal("object"),properties:l.record(l.string(),ke).optional(),required:l.array(l.string()).optional()}).catchall(l.unknown()).optional(),annotations:zw.optional(),execution:Lw.optional(),_meta:l.record(l.string(),l.unknown()).optional()}),qs=hn.extend({method:l.literal("tools/list")}),Uw=mn.extend({tools:l.array(Vu)}),Ms=Te.extend({content:l.array(Zi).default([]),structuredContent:l.record(l.string(),l.unknown()).optional(),isError:l.boolean().optional()}),UE=Ms.or(Te.extend({toolResult:l.unknown()})),Dw=un.extend({name:l.string(),arguments:l.record(l.string(),l.unknown()).optional()}),Rr=xe.extend({method:l.literal("tools/call"),params:Dw}),qw=et.extend({method:l.literal("notifications/tools/list_changed"),params:Xe.optional()}),DE=l.object({autoRefresh:l.boolean().default(!0),debounceMs:l.number().int().nonnegative().default(300)}),wn=l.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),Mw=Ke.extend({level:wn}),Yi=xe.extend({method:l.literal("logging/setLevel"),params:Mw}),Bw=Xe.extend({level:wn,logger:l.string().optional(),data:l.unknown()}),Fw=et.extend({method:l.literal("notifications/message"),params:Bw}),Hw=l.object({name:l.string().optional()}),Kw=l.object({hints:l.array(Hw).optional(),costPriority:l.number().min(0).max(1).optional(),speedPriority:l.number().min(0).max(1).optional(),intelligencePriority:l.number().min(0).max(1).optional()}),Vw=l.object({mode:l.enum(["auto","required","none"]).optional()}),Gw=l.object({type:l.literal("tool_result"),toolUseId:l.string().describe("The unique identifier for the corresponding tool call."),content:l.array(Zi).default([]),structuredContent:l.object({}).loose().optional(),isError:l.boolean().optional(),_meta:l.record(l.string(),l.unknown()).optional()}),Ww=l.discriminatedUnion("type",[Gi,Wi,Ji]),_s=l.discriminatedUnion("type",[Gi,Wi,Ji,Aw,Gw]),Jw=l.object({role:bn,content:l.union([_s,l.array(_s)]),_meta:l.record(l.string(),l.unknown()).optional()}),Zw=un.extend({messages:l.array(Jw),modelPreferences:Kw.optional(),systemPrompt:l.string().optional(),includeContext:l.enum(["none","thisServer","allServers"]).optional(),temperature:l.number().optional(),maxTokens:l.number().int(),stopSequences:l.array(l.string()).optional(),metadata:ke.optional(),tools:l.array(Vu).optional(),toolChoice:Vw.optional()}),Yw=xe.extend({method:l.literal("sampling/createMessage"),params:Zw}),vn=Te.extend({model:l.string(),stopReason:l.optional(l.enum(["endTurn","stopSequence","maxTokens"]).or(l.string())),role:bn,content:Ww}),Qi=Te.extend({model:l.string(),stopReason:l.optional(l.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(l.string())),role:bn,content:l.union([_s,l.array(_s)])}),Qw=l.object({type:l.literal("boolean"),title:l.string().optional(),description:l.string().optional(),default:l.boolean().optional()}),Xw=l.object({type:l.literal("string"),title:l.string().optional(),description:l.string().optional(),minLength:l.number().optional(),maxLength:l.number().optional(),format:l.enum(["email","uri","date","date-time"]).optional(),default:l.string().optional()}),ev=l.object({type:l.enum(["number","integer"]),title:l.string().optional(),description:l.string().optional(),minimum:l.number().optional(),maximum:l.number().optional(),default:l.number().optional()}),tv=l.object({type:l.literal("string"),title:l.string().optional(),description:l.string().optional(),enum:l.array(l.string()),default:l.string().optional()}),rv=l.object({type:l.literal("string"),title:l.string().optional(),description:l.string().optional(),oneOf:l.array(l.object({const:l.string(),title:l.string()})),default:l.string().optional()}),nv=l.object({type:l.literal("string"),title:l.string().optional(),description:l.string().optional(),enum:l.array(l.string()),enumNames:l.array(l.string()).optional(),default:l.string().optional()}),sv=l.union([tv,rv]),ov=l.object({type:l.literal("array"),title:l.string().optional(),description:l.string().optional(),minItems:l.number().optional(),maxItems:l.number().optional(),items:l.object({type:l.literal("string"),enum:l.array(l.string())}),default:l.array(l.string()).optional()}),iv=l.object({type:l.literal("array"),title:l.string().optional(),description:l.string().optional(),minItems:l.number().optional(),maxItems:l.number().optional(),items:l.object({anyOf:l.array(l.object({const:l.string(),title:l.string()}))}),default:l.array(l.string()).optional()}),av=l.union([ov,iv]),lv=l.union([nv,sv,av]),cv=l.union([lv,Qw,Xw,ev]),dv=un.extend({mode:l.literal("form").optional(),message:l.string(),requestedSchema:l.object({type:l.literal("object"),properties:l.record(l.string(),cv),required:l.array(l.string()).optional()})}),uv=un.extend({mode:l.literal("url"),message:l.string(),elicitationId:l.string(),url:l.string().url()}),pv=l.union([dv,uv]),fv=xe.extend({method:l.literal("elicitation/create"),params:pv}),hv=Xe.extend({elicitationId:l.string()}),mv=et.extend({method:l.literal("notifications/elicitation/complete"),params:hv}),Er=Te.extend({action:l.enum(["accept","decline","cancel"]),content:l.preprocess(t=>t===null?void 0:t,l.record(l.string(),l.union([l.string(),l.number(),l.boolean(),l.array(l.string())])).optional())}),gv=l.object({type:l.literal("ref/resource"),uri:l.string()}),yv=l.object({type:l.literal("ref/prompt"),name:l.string()}),bv=Ke.extend({ref:l.union([yv,gv]),argument:l.object({name:l.string(),value:l.string()}),context:l.object({arguments:l.record(l.string(),l.string()).optional()}).optional()}),Bs=xe.extend({method:l.literal("completion/complete"),params:bv});wv=Te.extend({completion:l.looseObject({values:l.array(l.string()).max(100),total:l.optional(l.number().int()),hasMore:l.optional(l.boolean())})}),vv=l.object({uri:l.string().startsWith("file://"),name:l.string().optional(),_meta:l.record(l.string(),l.unknown()).optional()}),Sv=xe.extend({method:l.literal("roots/list"),params:Ke.optional()}),Xi=Te.extend({roots:l.array(vv)}),_v=et.extend({method:l.literal("notifications/roots/list_changed"),params:Xe.optional()}),qE=l.union([Rs,Fi,Bs,Yi,Ds,Us,js,zs,Ls,Sw,kw,Rr,qs,Ps,Is,Cs,Ns]),ME=l.union([Ts,Es,Hi,_v,yn]),BE=l.union([xs,vn,Qi,Er,Xi,As,Os,xr]),FE=l.union([Rs,Yw,fv,Sv,Ps,Is,Cs,Ns]),HE=l.union([Ts,Es,Fw,xw,ww,qw,jw,yn,mv]),KE=l.union([xs,lw,wv,Nw,Ew,mw,gw,bw,Ms,Uw,As,Os,xr]),U=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 Li(s.elicitations,r)}return new t(e,r,n)}},Li=class extends U{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(M.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Dt(t){return t==="completed"||t==="failed"||t==="cancelled"}var Ju=j(()=>{});var Yu,Zu,Qu,Fs=j(()=>{Yu=Symbol("Let zodToJsonSchema decide on which parser to use"),Zu={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"},Qu=t=>typeof t=="string"?{...Zu,name:t}:{...Zu,...t}});var Xu,ea=j(()=>{Fs();Xu=t=>{let e=Qu(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 ta(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function se(t,e,r,n,s){t[e]=r,ta(t,e,n,s)}var qt=j(()=>{});var Hs,Ks=j(()=>{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 tt=j(()=>{Ks()});import{ZodFirstPartyTypeKind as kv}from"zod/v3";function ep(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==kv.ZodAny&&(r.items=B(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&se(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&se(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(se(r,"minItems",t.exactLength.value,t.exactLength.message,e),se(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var ra=j(()=>{qt();_e()});function tp(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?se(r,"minimum",n.value,n.message,e):se(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),se(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?se(r,"maximum",n.value,n.message,e):se(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),se(r,"maximum",n.value,n.message,e));break;case"multipleOf":se(r,"multipleOf",n.value,n.message,e);break}return r}var na=j(()=>{qt()});function rp(){return{type:"boolean"}}var sa=j(()=>{});function Vs(t,e){return B(t.type._def,e)}var Gs=j(()=>{_e()});var np,oa=j(()=>{_e();np=(t,e)=>B(t.innerType._def,e)});function ia(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>ia(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 $v(t,e)}}var $v,aa=j(()=>{qt();$v=(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":se(r,"minimum",n.value,n.message,e);break;case"max":se(r,"maximum",n.value,n.message,e);break}return r}});function sp(t,e){return{...B(t.innerType._def,e),default:t.defaultValue()}}var la=j(()=>{_e()});function op(t,e){return e.effectStrategy==="input"?B(t.schema._def,e):be(e)}var ca=j(()=>{_e();tt()});function ip(t){return{type:"string",enum:Array.from(t.values)}}var da=j(()=>{});function ap(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(xv(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,...c}=o;i=c}else n=void 0;s.push(i)}}),s.length?{allOf:s,...n}:void 0}var xv,ua=j(()=>{_e();xv=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function lp(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 pa=j(()=>{});function Ws(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":se(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":se(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(`^${ha(n.value,e)}`),n.message,e);break;case"endsWith":je(r,RegExp(`${ha(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":se(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),se(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{je(r,RegExp(ha(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":{se(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 ha(t,e){return e.patternStrategy==="escape"?Rv(t):t}function Rv(t){let e="";for(let r=0;r<t.length;r++)Tv.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}}})):se(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:cp(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):se(t,"pattern",cp(e,n),r,n)}function cp(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 c=0;c<n.length;c++){if(o){s+=n[c],o=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(s+=n[c],s+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(s+=n[c],a=!0):s+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){s+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){s+=`(^|(?<=[\r
|
|
935
|
-
]))`;continue}else if(
|
|
936
|
-
]))`;continue}}if(
|
|
937
|
-
`:`[${
|
|
938
|
-
]`;continue}s+=n[c],n[c]==="\\"?o=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(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 fa,it,Tv,Js=j(()=>{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:()=>(fa===void 0&&(fa=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),fa),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-_]*$/};Tv=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});import{ZodFirstPartyTypeKind as Sn}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===Sn.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===Sn.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===Sn.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===Sn.ZodBranded&&t.keyType._def.type._def.typeName===Sn.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=j(()=>{_e();Js();Gs();tt()});function dp(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 ma=j(()=>{_e();Ys();tt()});function up(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 ga=j(()=>{});function pp(t){return t.target==="openAi"?void 0:{not:be({...t,currentPath:[...t.currentPath,"not"]})}}var ya=j(()=>{tt()});function fp(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ba=j(()=>{});function mp(t,e){if(e.target==="openApi3")return hp(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 hp(t,e)}var _n,hp,Qs=j(()=>{_e();_n={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};hp=(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 gp(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=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 wa=j(()=>{_e();Qs()});function yp(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",ta(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?se(r,"minimum",n.value,n.message,e):se(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),se(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?se(r,"maximum",n.value,n.message,e):se(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),se(r,"maximum",n.value,n.message,e));break;case"multipleOf":se(r,"multipleOf",n.value,n.message,e);break}return r}var va=j(()=>{qt()});function bp(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},s=[],o=t.shape();for(let a in o){let c=o[a];if(c===void 0||c._def===void 0)continue;let d=Pv(c);d&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),d=!1);let u=B(c._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=Ev(t,e);return i!==void 0&&(n.additionalProperties=i),n}function Ev(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 Pv(t){try{return t.isOptional()}catch{return!0}}var Sa=j(()=>{_e()});var wp,_a=j(()=>{_e();tt();wp=(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 vp,ka=j(()=>{_e();vp=(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 Sp(t,e){return B(t.type._def,e)}var $a=j(()=>{_e()});function _p(t,e){let n={type:"array",uniqueItems:!0,items:B(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&se(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&se(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var xa=j(()=>{qt();_e()});function kp(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 Ta=j(()=>{_e()});function $p(t){return{not:be(t)}}var Ra=j(()=>{tt()});function xp(t){return be(t)}var Ea=j(()=>{tt()});var Tp,Pa=j(()=>{_e();Tp=(t,e)=>B(t.innerType._def,e)});import{ZodFirstPartyTypeKind as re}from"zod/v3";var Rp,Aa=j(()=>{tt();ra();na();sa();Gs();oa();aa();la();ca();da();ua();pa();ma();ga();ya();ba();wa();va();Sa();_a();ka();$a();Ys();xa();Js();Ta();Ra();Qs();Ea();Pa();Rp=(t,e,r)=>{switch(e){case re.ZodString:return Ws(t,r);case re.ZodNumber:return yp(t,r);case re.ZodObject:return bp(t,r);case re.ZodBigInt:return tp(t,r);case re.ZodBoolean:return rp();case re.ZodDate:return ia(t,r);case re.ZodUndefined:return $p(r);case re.ZodNull:return fp(r);case re.ZodArray:return ep(t,r);case re.ZodUnion:case re.ZodDiscriminatedUnion:return mp(t,r);case re.ZodIntersection:return ap(t,r);case re.ZodTuple:return kp(t,r);case re.ZodRecord:return Zs(t,r);case re.ZodLiteral:return lp(t,r);case re.ZodEnum:return ip(t);case re.ZodNativeEnum:return up(t);case re.ZodNullable:return gp(t,r);case re.ZodOptional:return wp(t,r);case re.ZodMap:return dp(t,r);case re.ZodSet:return _p(t,r);case re.ZodLazy:return()=>t.getter()._def;case re.ZodPromise:return Sp(t,r);case re.ZodNaN:case re.ZodNever:return pp(r);case re.ZodEffects:return op(t,r);case re.ZodAny:return be(r);case re.ZodUnknown:return xp(r);case re.ZodDefault:return sp(t,r);case re.ZodBranded:return Vs(t,r);case re.ZodReadonly:return Tp(t,r);case re.ZodCatch:return np(t,r);case re.ZodPipeline:return vp(t,r);case re.ZodFunction:case re.ZodVoid:case re.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!==Yu)return a}if(n&&!r){let a=Av(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=Rp(t,t.typeName,e),i=typeof o=="function"?B(o(),e):o;if(i&&Iv(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return s.jsonSchema=i,a}return s.jsonSchema=i,i}var Av,Iv,_e=j(()=>{Fs();Aa();Ks();tt();Av=(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}},Iv=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var Ep=j(()=>{});var Ia,Ca=j(()=>{_e();ea();tt();Ia=(t,e)=>{let r=Xu(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[d,u])=>({...c,[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 Pp=j(()=>{Fs();ea();qt();Ks();_e();Ep();tt();ra();na();sa();Gs();oa();aa();la();ca();da();ua();pa();ma();ga();ya();ba();wa();va();Sa();_a();ka();$a();Pa();Ys();xa();Js();Ta();Ra();Qs();Ea();Aa();Ca();Ca()});import*as Ap from"zod/v4-mini";function Cv(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Oa(t,e){return mt(t)?Ap.toJSONSchema(t,{target:Cv(e?.target),io:e?.pipeStrategy??"input"}):Ia(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Na(t){let r=Lt(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=kr(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function ja(t,e){let r=zt(t,e);if(!r.success)throw r.error;return r.data}var za=j(()=>{dn();Pp()});function Ip(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Cp(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];Ip(i)&&Ip(o)?r[s]={...i,...o}:r[s]=o}return r}var Ov,Xs,Op=j(()=>{dn();Pr();Ju();za();Ov=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 U(M.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 c=a.message,d=c.id,u=this._requestResolvers.get(d);if(u)if(this._requestResolvers.delete(d),a.type==="response")u(c);else{let h=c,S=new U(h.error.code,h.error.message,h.error.data);u(S)}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 U(M.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 U(M.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 U(M.InvalidParams,`Task not found: ${r.params.taskId}`);if(Dt(s.status))throw new U(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 U(M.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof U?s:new U(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),U.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),pn(o)||Uu(o)?this._onresponse(o):qi(o)?this._onrequest(o,i):Lu(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=U.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?.[Ut]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:M.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=Nu(e.params)?e.params.task:void 0,c=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,S)=>{if(i.signal.aborted)throw new U(M.ConnectionClosed,"Request was cancelled");let b={...S,relatedRequestId:e.id};o&&!b.relatedTask&&(b.relatedTask={taskId:o});let w=b.relatedTask?.taskId??o;return w&&c&&await c.updateTaskStatus(w,"input_required"),await this.request(u,h,b)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:o,taskStore:c,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:M.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(c){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),i(c);return}o(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),pn(e))n(e);else{let i=new U(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(pn(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),pn(e))s(e);else{let i=U.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 U?i:new U(M.InternalError,String(i))}}return}let o;try{let i=await this.request(e,xr,n);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new U(M.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 U(M.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new U(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 c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(d=>setTimeout(d,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof U?i:new U(M.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((d,u)=>{let h=I=>{u(I)};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(I){h(I);return}n?.signal?.throwIfAborted();let S=this._requestMessageId++,b={...e,jsonrpc:"2.0",id:S};n?.onprogress&&(this._progressHandlers.set(S,n.onprogress),b.params={...e.params,_meta:{...e.params?._meta||{},progressToken:S}}),a&&(b.params={...b.params,task:a}),c&&(b.params={...b.params,_meta:{...b.params?._meta||{},[Ut]:c}});let w=I=>{this._responseHandlers.delete(S),this._progressHandlers.delete(S),this._cleanupTimeout(S),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:S,reason:String(I)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(ne=>this._onerror(new Error(`Failed to send cancellation: ${ne}`)));let L=I instanceof U?I:new U(M.RequestTimeout,String(I));u(L)};this._responseHandlers.set(S,I=>{if(!n?.signal?.aborted){if(I instanceof Error)return u(I);try{let L=zt(r,I.result);L.success?d(L.data):u(L.error)}catch(L){u(L)}}}),n?.signal?.addEventListener("abort",()=>{w(n?.signal?.reason)});let k=n?.timeout??Ov,R=()=>w(U.fromError(M.RequestTimeout,"Request timed out",{timeout:k}));this._setupTimeout(S,k,n?.maxTotalTimeout,R,n?.resetTimeoutOnProgress??!1);let E=c?.taskId;if(E){let I=L=>{let ne=this._responseHandlers.get(S);ne?ne(L):this._onerror(new Error(`Response handler missing for side-channeled request ${S}`))};this._requestResolvers.set(S,I),this._enqueueTaskMessage(E,{type:"request",message:b,timestamp:Date.now()}).catch(L=>{this._cleanupTimeout(S),u(L)})}else this._transport.send(b,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(I=>{this._cleanupTimeout(S),u(I)})})}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},Mu,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(c=>this._onerror(c))});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=Na(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{let i=ja(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=Na(e);this._notificationHandlers.set(n,s=>{let o=ja(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"&&qi(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new U(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 U(M.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(i),o(new U(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 U(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 c=yn.parse({method:"notifications/tasks/status",params:a});await this.notification(c),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 U(M.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(Dt(a.status))throw new U(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 c=await n.getTask(s,r);if(c){let d=yn.parse({method:"notifications/tasks/status",params:c});await this.notification(d),Dt(c.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}}});var xn=z(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.regexpCode=de.getEsmExportName=de.getProperty=de.safeStringify=de.stringify=de.strConcat=de.addCodeArg=de.str=de._=de.nil=de._Code=de.Name=de.IDENTIFIER=de._CodeOrName=void 0;var kn=class{};de._CodeOrName=kn;de.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var rr=class extends kn{constructor(e){if(super(),!de.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}}};de.Name=rr;var rt=class extends kn{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),{})}};de._Code=rt;de.nil=new rt("");function Np(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Ua(r,e[n]),r.push(t[++n]);return new rt(r)}de._=Np;var La=new rt("+");function jp(t,...e){let r=[$n(t[0])],n=0;for(;n<e.length;)r.push(La),Ua(r,e[n]),r.push(La,$n(t[++n]));return Nv(r),new rt(r)}de.str=jp;function Ua(t,e){e instanceof rt?t.push(...e._items):e instanceof rr?t.push(e):t.push(Lv(e))}de.addCodeArg=Ua;function Nv(t){let e=1;for(;e<t.length-1;){if(t[e]===La){let r=jv(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function jv(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 zv(t,e){return e.emptyStr()?t:t.emptyStr()?e:jp`${t}${e}`}de.strConcat=zv;function Lv(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:$n(Array.isArray(t)?t.join(","):t)}function Uv(t){return new rt($n(t))}de.stringify=Uv;function $n(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}de.safeStringify=$n;function Dv(t){return typeof t=="string"&&de.IDENTIFIER.test(t)?new rt(`.${t}`):Np`[${t}]`}de.getProperty=Dv;function qv(t){if(typeof t=="string"&&de.IDENTIFIER.test(t))return new rt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}de.getEsmExportName=qv;function Mv(t){return new rt(t.toString())}de.regexpCode=Mv});var Ma=z(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.ValueScope=Be.ValueScopeName=Be.Scope=Be.varKinds=Be.UsedValueState=void 0;var Me=xn(),Da=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 Bv=(0,Me._)`\n`,qa=class extends to{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Bv: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 c=this._scope[o]||(this._scope[o]=[]),d=c.length;return c[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 c=n[i]=n[i]||new Map;a.forEach(d=>{if(c.has(d))return;c.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 Da(d);c.set(d,eo.Completed)})}return o}};Be.ValueScope=qa});var Z=z(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.or=Y.and=Y.not=Y.CodeGen=Y.operators=Y.varKinds=Y.ValueScopeName=Y.ValueScope=Y.Scope=Y.Name=Y.regexpCode=Y.stringify=Y.getProperty=Y.nil=Y.strConcat=Y.str=Y._=void 0;var oe=xn(),lt=Ma(),Mt=xn();Object.defineProperty(Y,"_",{enumerable:!0,get:function(){return Mt._}});Object.defineProperty(Y,"str",{enumerable:!0,get:function(){return Mt.str}});Object.defineProperty(Y,"strConcat",{enumerable:!0,get:function(){return Mt.strConcat}});Object.defineProperty(Y,"nil",{enumerable:!0,get:function(){return Mt.nil}});Object.defineProperty(Y,"getProperty",{enumerable:!0,get:function(){return Mt.getProperty}});Object.defineProperty(Y,"stringify",{enumerable:!0,get:function(){return Mt.stringify}});Object.defineProperty(Y,"regexpCode",{enumerable:!0,get:function(){return Mt.regexpCode}});Object.defineProperty(Y,"Name",{enumerable:!0,get:function(){return Mt.Name}});var io=Ma();Object.defineProperty(Y,"Scope",{enumerable:!0,get:function(){return io.Scope}});Object.defineProperty(Y,"ValueScope",{enumerable:!0,get:function(){return io.ValueScope}});Object.defineProperty(Y,"ValueScopeName",{enumerable:!0,get:function(){return io.ValueScopeName}});Object.defineProperty(Y,"varKinds",{enumerable:!0,get:function(){return io.varKinds}});Y.operators={GT:new oe._Code(">"),GTE:new oe._Code(">="),LT:new oe._Code("<"),LTE:new oe._Code("<="),EQ:new oe._Code("==="),NEQ:new oe._Code("!=="),NOT:new oe._Code("!"),OR:new oe._Code("||"),AND:new oe._Code("&&"),ADD:new oe._Code("+")};var Tt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Ba=class extends Tt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?lt.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=Ir(this.rhs,e,r)),this}get names(){return this.rhs instanceof oe._CodeOrName?this.rhs.names:{}}},no=class extends Tt{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 oe.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Ir(this.rhs,e,r),this}get names(){let e=this.lhs instanceof oe.Name?{}:{...this.lhs.names};return oo(e,this.rhs)}},Fa=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}},Ha=class extends Tt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Ka=class extends Tt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Va=class extends Tt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Ga=class extends Tt{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=Ir(this.code,e,r),this}get names(){return this.code instanceof oe._CodeOrName?this.code.names:{}}},Tn=class extends Tt{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)||(Fv(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),{})}},Rt=class extends Tn{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Wa=class extends Tn{},Ar=class extends Rt{};Ar.kind="else";var nr=class t extends Rt{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 Ar(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(zp(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=Ir(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 Rt{};sr.kind="for";var Ja=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=Ir(this.iteration,e,r),this}get names(){return or(super.names,this.iteration.names)}},Za=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?lt.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=Ir(this.iterable,e,r),this}get names(){return or(super.names,this.iterable.names)}},Rn=class extends Rt{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)}};Rn.kind="func";var En=class extends Tn{render(e){return"return "+super.render(e)}};En.kind="return";var Ya=class extends Rt{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}},Pn=class extends Rt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Pn.kind="catch";var An=class extends Rt{render(e){return"finally"+super.render(e)}};An.kind="finally";var Qa=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
939
|
-
`:""},this._extScope=e,this._scope=new lt.Scope({parent:e}),this._nodes=[new Wa]}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 Ba(e,o,n)),o}const(e,r,n){return this._def(lt.varKinds.const,e,r,n)}let(e,r,n){return this._def(lt.varKinds.let,e,r,n)}var(e,r,n){return this._def(lt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new no(e,r,n))}add(e,r){return this._leafNode(new Fa(e,Y.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==oe.nil&&this._leafNode(new Ga(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,oe.addCodeArg)(r,s));return r.push("}"),new oe._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 Ar)}endIf(){return this._endBlockNode(nr,Ar)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Ja(e),r)}forRange(e,r,n,s,o=this.opts.es5?lt.varKinds.var:lt.varKinds.let){let i=this._scope.toName(e);return this._for(new Za(o,i,r,n),()=>s(i))}forOf(e,r,n,s=lt.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=r instanceof oe.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,oe._)`${i}.length`,a=>{this.var(o,(0,oe._)`${i}[${a}]`),n(o)})}return this._for(new so("of",s,o,r),()=>n(o))}forIn(e,r,n,s=this.opts.es5?lt.varKinds.var:lt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,oe._)`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 Ha(e))}break(e){return this._leafNode(new Ka(e))}return(e){let r=new En;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(En)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new Ya;if(this._blockNode(s),this.code(e),r){let o=this.name("e");this._currNode=s.catch=new Pn(o),r(o)}return n&&(this._currNode=s.finally=new An,this.code(n)),this._endBlockNode(Pn,An)}throw(e){return this._leafNode(new Va(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=oe.nil,n,s){return this._blockNode(new Rn(e,r,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(Rn)}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}};Y.CodeGen=Qa;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 oe._CodeOrName?or(t,e.names):t}function Ir(t,e,r){if(t instanceof oe.Name)return n(t);if(!s(t))return t;return new oe._Code(t._items.reduce((o,i)=>(i instanceof oe.Name&&(i=n(i)),i instanceof oe._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 oe._Code&&o._items.some(i=>i instanceof oe.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function Fv(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function zp(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,oe._)`!${Xa(t)}`}Y.not=zp;var Hv=Lp(Y.operators.AND);function Kv(...t){return t.reduce(Hv)}Y.and=Kv;var Vv=Lp(Y.operators.OR);function Gv(...t){return t.reduce(Vv)}Y.or=Gv;function Lp(t){return(e,r)=>e===oe.nil?r:r===oe.nil?e:(0,oe._)`${Xa(e)} ${t} ${Xa(r)}`}function Xa(t){return t instanceof oe.Name?t:(0,oe._)`(${t})`}});var ae=z(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.checkStrictMode=X.getErrorPath=X.Type=X.useFunc=X.setEvaluated=X.evaluatedPropsToName=X.mergeEvaluated=X.eachItem=X.unescapeJsonPointer=X.escapeJsonPointer=X.escapeFragment=X.unescapeFragment=X.schemaRefOrVal=X.schemaHasRulesButRef=X.schemaHasRules=X.checkUnknownRules=X.alwaysValidSchema=X.toHash=void 0;var me=Z(),Wv=xn();function Jv(t){let e={};for(let r of t)e[r]=!0;return e}X.toHash=Jv;function Zv(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(qp(t,e),!Mp(e,t.self.RULES.all))}X.alwaysValidSchema=Zv;function qp(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]||Hp(t,`unknown keyword: "${o}"`)}X.checkUnknownRules=qp;function Mp(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}X.schemaHasRules=Mp;function Yv(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}X.schemaHasRulesButRef=Yv;function Qv({topSchemaRef:t,schemaPath:e},r,n,s){if(!s){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,me._)`${r}`}return(0,me._)`${t}${e}${(0,me.getProperty)(n)}`}X.schemaRefOrVal=Qv;function Xv(t){return Bp(decodeURIComponent(t))}X.unescapeFragment=Xv;function eS(t){return encodeURIComponent(tl(t))}X.escapeFragment=eS;function tl(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}X.escapeJsonPointer=tl;function Bp(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}X.unescapeJsonPointer=Bp;function tS(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}X.eachItem=tS;function Up({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(s,o,i,a)=>{let c=i===void 0?o:i instanceof me.Name?(o instanceof me.Name?t(s,o,i):e(s,o,i),i):o instanceof me.Name?(e(s,i,o),o):r(o,i);return a===me.Name&&!(c instanceof me.Name)?n(s,c):c}}X.mergeEvaluated={props:Up({mergeNames:(t,e,r)=>t.if((0,me._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,me._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,me._)`${r} || {}`).code((0,me._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,me._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,me._)`${r} || {}`),rl(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Fp}),items:Up({mergeNames:(t,e,r)=>t.if((0,me._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,me._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,me._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,me._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Fp(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,me._)`{}`);return e!==void 0&&rl(t,r,e),r}X.evaluatedPropsToName=Fp;function rl(t,e,r){Object.keys(r).forEach(n=>t.assign((0,me._)`${e}${(0,me.getProperty)(n)}`,!0))}X.setEvaluated=rl;var Dp={};function rS(t,e){return t.scopeValue("func",{ref:e,code:Dp[e.code]||(Dp[e.code]=new Wv._Code(e.code))})}X.useFunc=rS;var el;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(el||(X.Type=el={}));function nS(t,e,r){if(t instanceof me.Name){let n=e===el.Num;return r?n?(0,me._)`"[" + ${t} + "]"`:(0,me._)`"['" + ${t} + "']"`:n?(0,me._)`"/" + ${t}`:(0,me._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,me.getProperty)(t).toString():"/"+tl(t)}X.getErrorPath=nS;function Hp(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}X.checkStrictMode=Hp});var Et=z(nl=>{"use strict";Object.defineProperty(nl,"__esModule",{value:!0});var Pe=Z(),sS={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")};nl.default=sS});var In=z(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 le=Z(),ao=ae(),ze=Et();Ae.keywordError={message:({keyword:t})=>(0,le.str)`must pass "${t}" keyword validation`};Ae.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,le.str)`"${t}" keyword must be ${e} ($data)`:(0,le.str)`"${t}" keyword is invalid ($data)`};function oS(t,e=Ae.keywordError,r,n){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,c=Gp(t,e,r);n??(i||a)?Kp(o,c):Vp(s,(0,le._)`[${c}]`)}Ae.reportError=oS;function iS(t,e=Ae.keywordError,r){let{it:n}=t,{gen:s,compositeRule:o,allErrors:i}=n,a=Gp(t,e,r);Kp(s,a),o||i||Vp(n,ze.default.vErrors)}Ae.reportExtraError=iS;function aS(t,e){t.assign(ze.default.errors,e),t.if((0,le._)`${ze.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,le._)`${ze.default.vErrors}.length`,e),()=>t.assign(ze.default.vErrors,null)))}Ae.resetErrorsCount=aS;function lS({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,le._)`${ze.default.vErrors}[${a}]`),t.if((0,le._)`${i}.instancePath === undefined`,()=>t.assign((0,le._)`${i}.instancePath`,(0,le.strConcat)(ze.default.instancePath,o.errorPath))),t.assign((0,le._)`${i}.schemaPath`,(0,le.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,le._)`${i}.schema`,r),t.assign((0,le._)`${i}.data`,n))})}Ae.extendErrors=lS;function Kp(t,e){let r=t.const("err",e);t.if((0,le._)`${ze.default.vErrors} === null`,()=>t.assign(ze.default.vErrors,(0,le._)`[${r}]`),(0,le._)`${ze.default.vErrors}.push(${r})`),t.code((0,le._)`${ze.default.errors}++`)}function Vp(t,e){let{gen:r,validateName:n,schemaEnv:s}=t;s.$async?r.throw((0,le._)`new ${t.ValidationError}(${e})`):(r.assign((0,le._)`${n}.errors`,e),r.return(!1))}var ir={keyword:new le.Name("keyword"),schemaPath:new le.Name("schemaPath"),params:new le.Name("params"),propertyName:new le.Name("propertyName"),message:new le.Name("message"),schema:new le.Name("schema"),parentSchema:new le.Name("parentSchema")};function Gp(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,le._)`{}`:cS(t,e,r)}function cS(t,e,r={}){let{gen:n,it:s}=t,o=[dS(s,r),uS(t,r)];return pS(t,e,o),n.object(...o)}function dS({errorPath:t},{instancePath:e}){let r=e?(0,le.str)`${t}${(0,ao.getErrorPath)(e,ao.Type.Str)}`:t;return[ze.default.instancePath,(0,le.strConcat)(ze.default.instancePath,r)]}function uS({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let s=n?e:(0,le.str)`${e}/${t}`;return r&&(s=(0,le.str)`${s}${(0,ao.getErrorPath)(r,ao.Type.Str)}`),[ir.schemaPath,s]}function pS(t,{params:e,message:r},n){let{keyword:s,data:o,schemaValue:i,it:a}=t,{opts:c,propertyName:d,topSchemaRef:u,schemaPath:h}=a;n.push([ir.keyword,s],[ir.params,typeof e=="function"?e(t):e||(0,le._)`{}`]),c.messages&&n.push([ir.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([ir.schema,i],[ir.parentSchema,(0,le._)`${u}${h}`],[ze.default.data,o]),d&&n.push([ir.propertyName,d])}});var Jp=z(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.boolOrEmptySchema=Cr.topBoolOrEmptySchema=void 0;var fS=In(),hS=Z(),mS=Et(),gS={message:"boolean schema is false"};function yS(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Wp(t,!1):typeof r=="object"&&r.$async===!0?e.return(mS.default.data):(e.assign((0,hS._)`${n}.errors`,null),e.return(!0))}Cr.topBoolOrEmptySchema=yS;function bS(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Wp(t)):r.var(e,!0)}Cr.boolOrEmptySchema=bS;function Wp(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,fS.reportError)(s,gS,void 0,e)}});var sl=z(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.getRules=Or.isJSONType=void 0;var wS=["string","number","integer","boolean","null","object","array"],vS=new Set(wS);function SS(t){return typeof t=="string"&&vS.has(t)}Or.isJSONType=SS;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:{}}}Or.getRules=_S});var ol=z(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.shouldUseRule=Bt.shouldUseGroup=Bt.schemaHasRulesForType=void 0;function kS({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Zp(t,n)}Bt.schemaHasRulesForType=kS;function Zp(t,e){return e.rules.some(r=>Yp(t,r))}Bt.shouldUseGroup=Zp;function Yp(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=Yp});var Cn=z(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 $S=sl(),xS=ol(),TS=In(),J=Z(),Qp=ae(),Nr;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Nr||(Ie.DataType=Nr={}));function RS(t){let e=Xp(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=RS;function Xp(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every($S.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ie.getJSONTypes=Xp;function ES(t,e){let{gen:r,data:n,opts:s}=t,o=PS(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,xS.schemaHasRulesForType)(t,e[0]));if(i){let a=al(e,n,s.strictNumbers,Nr.Wrong);r.if(a,()=>{o.length?AS(t,e,o):ll(t)})}return i}Ie.coerceAndCheckDataType=ES;var ef=new Set(["string","number","integer","boolean","null"]);function PS(t,e){return e?t.filter(r=>ef.has(r)||e==="array"&&r==="array"):[]}function AS(t,e,r){let{gen:n,data:s,opts:o}=t,i=n.let("dataType",(0,J._)`typeof ${s}`),a=n.let("coerced",(0,J._)`undefined`);o.coerceTypes==="array"&&n.if((0,J._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,(0,J._)`${s}[0]`).assign(i,(0,J._)`typeof ${s}`).if(al(e,s,o.strictNumbers),()=>n.assign(a,s))),n.if((0,J._)`${a} !== undefined`);for(let d of r)(ef.has(d)||d==="array"&&o.coerceTypes==="array")&&c(d);n.else(),ll(t),n.endIf(),n.if((0,J._)`${a} !== undefined`,()=>{n.assign(s,a),IS(t,a)});function c(d){switch(d){case"string":n.elseIf((0,J._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,J._)`"" + ${s}`).elseIf((0,J._)`${s} === null`).assign(a,(0,J._)`""`);return;case"number":n.elseIf((0,J._)`${i} == "boolean" || ${s} === null
|
|
940
|
-
|| (${i} == "string" && ${s} && ${s} == +${s})`).assign(a,(0,J._)`+${s}`);return;case"integer":
|
|
941
|
-
|| (${i} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(a,(0,J._)`+${s}`);return;case"boolean":
|
|
942
|
-
|| ${i} === "boolean" || ${s} === null`).assign(a,(0,J._)`[${s}]`)}}}function IS({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,J._)`${e} !== undefined`,()=>t.assign((0,J._)`${e}[${r}]`,n))}function il(t,e,r,n=Nr.Correct){let s=n===Nr.Correct?J.operators.EQ:J.operators.NEQ,o;switch(t){case"null":return(0,J._)`${e} ${s} null`;case"array":o=(0,J._)`Array.isArray(${e})`;break;case"object":o=(0,J._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,J._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,J._)`typeof ${e} ${s} ${t}`}return n===Nr.Correct?o:(0,J.not)(o);function i(a=J.nil){return(0,J.and)((0,J._)`typeof ${e} == "number"`,a,r?(0,J._)`isFinite(${e})`:J.nil)}}Ie.checkDataType=il;function al(t,e,r,n){if(t.length===1)return il(t[0],e,r,n);let s,o=(0,Qp.toHash)(t);if(o.array&&o.object){let i=(0,J._)`typeof ${e} != "object"`;s=o.null?i:(0,J._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=J.nil;o.number&&delete o.integer;for(let i in o)s=(0,J.and)(s,il(i,e,r,n));return s}Ie.checkDataTypes=al;var CS={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,J._)`{type: ${t}}`:(0,J._)`{type: ${e}}`};function ll(t){let e=OS(t);(0,TS.reportError)(e,CS)}Ie.reportTypeError=ll;function OS(t){let{gen:e,data:r,schema:n}=t,s=(0,Qp.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var rf=z(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});lo.assignDefaults=void 0;var jr=Z(),NS=ae();function jS(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)tf(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,o)=>tf(t,o,s.default))}lo.assignDefaults=jS;function tf(t,e,r){let{gen:n,compositeRule:s,data:o,opts:i}=t;if(r===void 0)return;let a=(0,jr._)`${o}${(0,jr.getProperty)(e)}`;if(s){(0,NS.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,jr._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,jr._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,jr._)`${a} = ${(0,jr.stringify)(r)}`)}});var nt=z(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 ge=Z(),cl=ae(),Ft=Et(),zS=ae();function LS(t,e){let{gen:r,data:n,it:s}=t;r.if(ul(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ge._)`${e}`},!0),t.error()})}fe.checkReportMissingProp=LS;function US({gen:t,data:e,it:{opts:r}},n,s){return(0,ge.or)(...n.map(o=>(0,ge.and)(ul(t,e,o,r.ownProperties),(0,ge._)`${s} = ${o}`)))}fe.checkMissingProp=US;function DS(t,e){t.setParams({missingProperty:e},!0),t.error()}fe.reportMissingProp=DS;function nf(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ge._)`Object.prototype.hasOwnProperty`})}fe.hasPropFunc=nf;function dl(t,e,r){return(0,ge._)`${nf(t)}.call(${e}, ${r})`}fe.isOwnProperty=dl;function qS(t,e,r,n){let s=(0,ge._)`${e}${(0,ge.getProperty)(r)} !== undefined`;return n?(0,ge._)`${s} && ${dl(t,e,r)}`:s}fe.propertyInData=qS;function ul(t,e,r,n){let s=(0,ge._)`${e}${(0,ge.getProperty)(r)} === undefined`;return n?(0,ge.or)(s,(0,ge.not)(dl(t,e,r))):s}fe.noPropertyInData=ul;function sf(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}fe.allSchemaProperties=sf;function MS(t,e){return sf(e).filter(r=>!(0,cl.alwaysValidSchema)(t,e[r]))}fe.schemaProperties=MS;function BS({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:o},it:i},a,c,d){let u=d?(0,ge._)`${t}, ${e}, ${n}${s}`:e,h=[[Ft.default.instancePath,(0,ge.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 S=(0,ge._)`${u}, ${r.object(...h)}`;return c!==ge.nil?(0,ge._)`${a}.call(${c}, ${S})`:(0,ge._)`${a}(${S})`}fe.callValidateCode=BS;var FS=(0,ge._)`new RegExp`;function HS({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,ge._)`${s.code==="new RegExp"?FS:(0,zS.useFunc)(t,s)}(${r}, ${n})`})}fe.usePattern=HS;function KS(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 c=e.const("len",(0,ge._)`${r}.length`);e.forRange("i",0,c,d=>{t.subschema({keyword:n,dataProp:d,dataPropType:cl.Type.Num},o),e.if((0,ge.not)(o),a)})}}fe.validateArray=KS;function VS(t){let{gen:e,schema:r,keyword:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,cl.alwaysValidSchema)(s,c))&&!s.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,d)=>{let u=t.subschema({keyword:n,schemaProp:d,compositeRule:!0},a);e.assign(i,(0,ge._)`${i} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,ge.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}fe.validateUnion=VS});var lf=z(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.validateKeywordUsage=gt.validSchemaType=gt.funcKeywordCode=gt.macroKeywordCode=void 0;var Le=Z(),ar=Et(),GS=nt(),WS=In();function JS(t,e){let{gen:r,keyword:n,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),c=af(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:c,compositeRule:!0},d),t.pass(d,()=>t.error(!0))}gt.macroKeywordCode=JS;function ZS(t,e){var r;let{gen:n,keyword:s,schema:o,parentSchema:i,$data:a,it:c}=t;QS(c,e);let d=!a&&e.compile?e.compile.call(c.self,o,i,c):e.validate,u=af(n,s,d),h=n.let("valid");t.block$data(h,S),t.ok((r=e.valid)!==null&&r!==void 0?r:h);function S(){if(e.errors===!1)k(),e.modifying&&of(t),R(()=>t.error());else{let E=e.async?b():w();e.modifying&&of(t),R(()=>YS(t,E))}}function b(){let E=n.let("ruleErrs",null);return n.try(()=>k((0,Le._)`await `),I=>n.assign(h,!1).if((0,Le._)`${I} instanceof ${c.ValidationError}`,()=>n.assign(E,(0,Le._)`${I}.errors`),()=>n.throw(I))),E}function w(){let E=(0,Le._)`${u}.errors`;return n.assign(E,null),k(Le.nil),E}function k(E=e.async?(0,Le._)`await `:Le.nil){let I=c.opts.passContext?ar.default.this:ar.default.self,L=!("compile"in e&&!a||e.schema===!1);n.assign(h,(0,Le._)`${E}${(0,GS.callValidateCode)(t,u,I,L)}`,e.modifying)}function R(E){var I;n.if((0,Le.not)((I=e.valid)!==null&&I!==void 0?I:h),E)}}gt.funcKeywordCode=ZS;function of(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Le._)`${n.parentData}[${n.parentDataProperty}]`))}function YS(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,WS.extendErrors)(t)},()=>t.error())}function QS({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function af(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 XS(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=XS;function e_({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 c=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}gt.validateKeywordUsage=e_});var df=z(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.extendSubschemaMode=Ht.extendSubschemaData=Ht.getSubschema=void 0;var yt=Z(),cf=ae();function t_(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,cf.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=t_;function r_(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,S=a.let("data",(0,yt._)`${e.data}${(0,yt.getProperty)(r)}`,!0);c(S),t.errorPath=(0,yt.str)`${d}${(0,cf.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);c(d),i!==void 0&&(t.propertyName=i)}o&&(t.dataTypes=o);function c(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=r_;function n_(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=n_});var pl=z((aC,uf)=>{"use strict";uf.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 ff=z((lC,pf)=>{"use strict";var Kt=pf.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(){};co(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 co(t,e,r,n,s,o,i,a,c,d){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,s,o,i,a,c,d);for(var u in n){var h=n[u];if(Array.isArray(h)){if(u in Kt.arrayKeywords)for(var S=0;S<h.length;S++)co(t,e,r,h[S],s+"/"+u+"/"+S,o,s,u,n,S)}else if(u in Kt.propsKeywords){if(h&&typeof h=="object")for(var b in h)co(t,e,r,h[b],s+"/"+u+"/"+s_(b),o,s,u,n,b)}else(u in Kt.keywords||t.allKeys&&!(u in Kt.skipKeywords))&&co(t,e,r,h,s+"/"+u,o,s,u,n)}r(n,s,o,i,a,c,d)}}function s_(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var On=z(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.getSchemaRefs=Fe.resolveUrl=Fe.normalizeId=Fe._getFullPath=Fe.getFullPath=Fe.inlineRef=void 0;var o_=ae(),i_=pl(),a_=ff(),l_=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function c_(t,e=!0){return typeof t=="boolean"?!0:e===!0?!fl(t):e?hf(t)<=e:!1}Fe.inlineRef=c_;var d_=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function fl(t){for(let e in t){if(d_.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(fl)||typeof r=="object"&&fl(r))return!0}return!1}function hf(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!l_.has(r)&&(typeof t[r]=="object"&&(0,o_.eachItem)(t[r],n=>e+=hf(n)),e===1/0))return 1/0}return e}function mf(t,e="",r){r!==!1&&(e=zr(e));let n=t.parse(e);return gf(t,n)}Fe.getFullPath=mf;function gf(t,e){return t.serialize(e).split("#")[0]+"#"}Fe._getFullPath=gf;var u_=/#\/?$/;function zr(t){return t?t.replace(u_,""):""}Fe.normalizeId=zr;function p_(t,e,r){return r=zr(r),t.resolve(e,r)}Fe.resolveUrl=p_;var f_=/^[a-z_][-a-z0-9._]*$/i;function h_(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=zr(t[r]||e),o={"":s},i=mf(n,s,!1),a={},c=new Set;return a_(t,{allKeys:!0},(h,S,b,w)=>{if(w===void 0)return;let k=i+S,R=o[w];typeof h[r]=="string"&&(R=E.call(this,h[r])),I.call(this,h.$anchor),I.call(this,h.$dynamicAnchor),o[S]=R;function E(L){let ne=this.opts.uriResolver.resolve;if(L=zr(R?ne(R,L):L),c.has(L))throw u(L);c.add(L);let F=this.refs[L];return typeof F=="string"&&(F=this.refs[F]),typeof F=="object"?d(h,F.schema,L):L!==zr(k)&&(L[0]==="#"?(d(h,a[L],L),a[L]=h):this.refs[L]=k),L}function I(L){if(typeof L=="string"){if(!f_.test(L))throw new Error(`invalid anchor "${L}"`);E.call(this,`#${L}`)}}}),a;function d(h,S,b){if(S!==void 0&&!i_(h,S))throw u(b)}function u(h){return new Error(`reference "${h}" resolves to more than one schema`)}}Fe.getSchemaRefs=h_});var zn=z(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.getData=Vt.KeywordCxt=Vt.validateFunctionCode=void 0;var Sf=Jp(),yf=Cn(),ml=ol(),uo=Cn(),m_=rf(),jn=lf(),hl=df(),D=Z(),K=Et(),g_=On(),Pt=ae(),Nn=In();function y_(t){if($f(t)&&(xf(t),kf(t))){v_(t);return}_f(t,()=>(0,Sf.topBoolOrEmptySchema)(t))}Vt.validateFunctionCode=y_;function _f({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},o){s.code.es5?t.func(e,(0,D._)`${K.default.data}, ${K.default.valCxt}`,n.$async,()=>{t.code((0,D._)`"use strict"; ${bf(r,s)}`),w_(t,s),t.code(o)}):t.func(e,(0,D._)`${K.default.data}, ${b_(s)}`,n.$async,()=>t.code(bf(r,s)).code(o))}function b_(t){return(0,D._)`{${K.default.instancePath}="", ${K.default.parentData}, ${K.default.parentDataProperty}, ${K.default.rootData}=${K.default.data}${t.dynamicRef?(0,D._)`, ${K.default.dynamicAnchors}={}`:D.nil}}={}`}function w_(t,e){t.if(K.default.valCxt,()=>{t.var(K.default.instancePath,(0,D._)`${K.default.valCxt}.${K.default.instancePath}`),t.var(K.default.parentData,(0,D._)`${K.default.valCxt}.${K.default.parentData}`),t.var(K.default.parentDataProperty,(0,D._)`${K.default.valCxt}.${K.default.parentDataProperty}`),t.var(K.default.rootData,(0,D._)`${K.default.valCxt}.${K.default.rootData}`),e.dynamicRef&&t.var(K.default.dynamicAnchors,(0,D._)`${K.default.valCxt}.${K.default.dynamicAnchors}`)},()=>{t.var(K.default.instancePath,(0,D._)`""`),t.var(K.default.parentData,(0,D._)`undefined`),t.var(K.default.parentDataProperty,(0,D._)`undefined`),t.var(K.default.rootData,K.default.data),e.dynamicRef&&t.var(K.default.dynamicAnchors,(0,D._)`{}`)})}function v_(t){let{schema:e,opts:r,gen:n}=t;_f(t,()=>{r.$comment&&e.$comment&&Rf(t),x_(t),n.let(K.default.vErrors,null),n.let(K.default.errors,0),r.unevaluated&&S_(t),Tf(t),E_(t)})}function S_(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,D._)`${r}.evaluated`),e.if((0,D._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,D._)`${t.evaluated}.props`,(0,D._)`undefined`)),e.if((0,D._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,D._)`${t.evaluated}.items`,(0,D._)`undefined`))}function bf(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,D._)`/*# sourceURL=${r} */`:D.nil}function __(t,e){if($f(t)&&(xf(t),kf(t))){k_(t,e);return}(0,Sf.boolOrEmptySchema)(t,e)}function kf({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 $f(t){return typeof t.schema!="boolean"}function k_(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&Rf(t),T_(t),R_(t);let o=n.const("_errs",K.default.errors);Tf(t,o),n.var(e,(0,D._)`${o} === ${K.default.errors}`)}function xf(t){(0,Pt.checkUnknownRules)(t),$_(t)}function Tf(t,e){if(t.opts.jtd)return wf(t,[],!1,e);let r=(0,yf.getSchemaTypes)(t.schema),n=(0,yf.coerceAndCheckDataType)(t,r);wf(t,r,!n,e)}function $_(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Pt.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function x_(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Pt.checkStrictMode)(t,"default is ignored in the schema root")}function T_(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,g_.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function R_(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Rf({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){let o=r.$comment;if(s.$comment===!0)t.code((0,D._)`${K.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,D.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,D._)`${K.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function E_(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:o}=t;r.$async?e.if((0,D._)`${K.default.errors} === 0`,()=>e.return(K.default.data),()=>e.throw((0,D._)`new ${s}(${K.default.vErrors})`)):(e.assign((0,D._)`${n}.errors`,K.default.vErrors),o.unevaluated&&P_(t),e.return((0,D._)`${K.default.errors} === 0`))}function P_({gen:t,evaluated:e,props:r,items:n}){r instanceof D.Name&&t.assign((0,D._)`${e}.props`,r),n instanceof D.Name&&t.assign((0,D._)`${e}.items`,n)}function wf(t,e,r,n){let{gen:s,schema:o,data:i,allErrors:a,opts:c,self:d}=t,{RULES:u}=d;if(o.$ref&&(c.ignoreKeywordsWithRef||!(0,Pt.schemaHasRulesButRef)(o,u))){s.block(()=>Pf(t,"$ref",u.all.$ref.definition));return}c.jtd||A_(t,e),s.block(()=>{for(let S of u.rules)h(S);h(u.post)});function h(S){(0,ml.shouldUseGroup)(o,S)&&(S.type?(s.if((0,uo.checkDataType)(S.type,i,c.strictNumbers)),vf(t,S),e.length===1&&e[0]===S.type&&r&&(s.else(),(0,uo.reportTypeError)(t)),s.endIf()):vf(t,S),a||s.if((0,D._)`${K.default.errors} === ${n||0}`))}}function vf(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,m_.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,ml.shouldUseRule)(n,o)&&Pf(t,o.keyword,o.definition,e.type)})}function A_(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(I_(t,e),t.opts.allowUnionTypes||C_(t,e),O_(t,t.dataTypes))}function I_(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Ef(t.dataTypes,r)||gl(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),j_(t,e)}}function C_(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&gl(t,"use allowUnionTypes to allow union type keyword")}function O_(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,ml.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>N_(e,i))&&gl(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function N_(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Ef(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function j_(t,e){let r=[];for(let n of t.dataTypes)Ef(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function gl(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Pt.checkStrictMode)(t,e,t.opts.strictTypes)}var po=class{constructor(e,r,n){if((0,jn.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,Pt.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",Af(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,jn.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",K.default.errors))}result(e,r,n){this.failResult((0,D.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,D.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,D._)`${r} !== undefined && (${(0,D.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?Nn.reportExtraError:Nn.reportError)(this,this.def.error,r)}$dataError(){(0,Nn.reportError)(this,this.def.$dataError||Nn.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Nn.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=D.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=D.nil,r=D.nil){if(!this.$data)return;let{gen:n,schemaCode:s,schemaType:o,def:i}=this;n.if((0,D.or)((0,D._)`${s} === undefined`,r)),e!==D.nil&&n.assign(e,!0),(o.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==D.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:s,it:o}=this;return(0,D.or)(i(),a());function i(){if(n.length){if(!(r instanceof D.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,D._)`${(0,uo.checkDataTypes)(c,r,o.opts.strictNumbers,uo.DataType.Wrong)}`}return D.nil}function a(){if(s.validateSchema){let c=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,D._)`!${c}(${r})`}return D.nil}}subschema(e,r){let n=(0,hl.getSubschema)(this.it,e);(0,hl.extendSubschemaData)(n,this.it,e),(0,hl.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return __(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Pt.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Pt.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,D.Name)),!0}};Vt.KeywordCxt=po;function Pf(t,e,r,n){let s=new po(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,jn.funcKeywordCode)(s,r):"macro"in r?(0,jn.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,jn.funcKeywordCode)(s,r)}var z_=/^\/(?:[^~]|~0|~1)*$/,L_=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Af(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,o;if(t==="")return K.default.rootData;if(t[0]==="/"){if(!z_.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=K.default.rootData}else{let d=L_.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(c("property/index",u));return n[e-u]}if(u>e)throw new Error(c("data",u));if(o=r[e-u],!s)return o}let i=o,a=s.split("/");for(let d of a)d&&(o=(0,D._)`${o}${(0,D.getProperty)((0,Pt.unescapeJsonPointer)(d))}`,i=(0,D._)`${i} && ${o}`);return i;function c(d,u){return`Cannot access ${d} ${u} levels up, current level is ${e}`}}Vt.getData=Af});var fo=z(bl=>{"use strict";Object.defineProperty(bl,"__esModule",{value:!0});var yl=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};bl.default=yl});var Ln=z(Sl=>{"use strict";Object.defineProperty(Sl,"__esModule",{value:!0});var wl=On(),vl=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,wl.resolveUrl)(e,r,n),this.missingSchema=(0,wl.normalizeId)((0,wl.getFullPath)(e,this.missingRef))}};Sl.default=vl});var mo=z(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.resolveSchema=st.getCompilingSchema=st.resolveRef=st.compileSchema=st.SchemaEnv=void 0;var ct=Z(),U_=fo(),lr=Et(),dt=On(),If=ae(),D_=zn(),Lr=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={}}};st.SchemaEnv=Lr;function kl(t){let e=Cf.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 ct.CodeGen(this.scope,{es5:n,lines:s,ownProperties:o}),a;t.$async&&(a=i.scopeValue("Error",{ref:U_.default,code:(0,ct._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let d={gen:i,allErrors:this.opts.allErrors,data:lr.default.data,parentData:lr.default.parentData,parentDataProperty:lr.default.parentDataProperty,dataNames:[lr.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:c,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},u;try{this._compilations.add(t),(0,D_.validateFunctionCode)(d),i.optimize(this.opts.code.optimize);let h=i.toString();u=`${i.scopeRefs(lr.default.scope)}return ${h}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let b=new Function(`${lr.default.self}`,`${lr.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:b}),b.errors=null,b.schema=t.schema,b.schemaEnv=t,t.$async&&(b.$async=!0),this.opts.code.source===!0&&(b.source={validateName:c,validateCode:h,scopeValues:i._values}),this.opts.unevaluated){let{props:w,items:k}=d;b.evaluated={props:w instanceof ct.Name?void 0:w,items:k instanceof ct.Name?void 0:k,dynamicProps:w instanceof ct.Name,dynamicItems:k instanceof ct.Name},b.source&&(b.source.evaluated=(0,ct.stringify)(b.evaluated))}return t.validate=b,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)}}st.compileSchema=kl;function q_(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=F_.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 Lr({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=M_.call(this,o)}st.resolveRef=q_;function M_(t){return(0,dt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:kl.call(this,t)}function Cf(t){for(let e of this._compilations)if(B_(e,t))return e}st.getCompilingSchema=Cf;function B_(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function F_(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 _l.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:_l.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||kl.call(this,i),o===(0,dt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,d=a[c];return d&&(s=(0,dt.resolveUrl)(this.opts.uriResolver,s,d)),new Lr({schema:a,schemaId:c,root:t,baseId:s})}return _l.call(this,r,i)}}st.resolveSchema=ho;var H_=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function _l(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 c=r[(0,If.unescapeFragment)(a)];if(c===void 0)return;r=c;let d=typeof r=="object"&&r[this.opts.schemaId];!H_.has(a)&&d&&(e=(0,dt.resolveUrl)(this.opts.uriResolver,e,d))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,If.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 Lr({schema:r,schemaId:i,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var Of=z((hC,K_)=>{K_.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 Tl=z((mC,Df)=>{"use strict";var V_=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),jf=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),$l=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),zf=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),G_=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function xl(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 W_=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Nf(t){return t.length=0,!0}function J_(t,e,r){if(t.length){let n=xl(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function Z_(t){let e=0,r={error:!1,address:"",zone:""},n=[],s=[],o=!1,i=!1,a=J_;for(let c=0;c<t.length;c++){let d=t[c];if(!(d==="["||d==="]"))if(d===":"){if(o===!0&&(i=!0),!a(s,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(o=!0),n.push(":");continue}else if(d==="%"){if(!a(s,n,r))break;a=Nf}else{s.push(d);continue}}return s.length&&(a===Nf?r.zone=s.join(""):i?n.push(s.join("")):n.push(xl(s))),r.address=n.join(""),r}function Lf(t){if(Y_(t,":")<2)return{host:t,isIPV6:!1};let e=Z_(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 Y_(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function Q_(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 X_={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},ek=/[@/?#:]/g,tk=/[@/?#]/g;function Uf(t,e){let r=e?tk:ek;return r.lastIndex=0,t.replace(r,n=>X_[n])}function rk(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($l(s)){let o=s.toUpperCase(),i=String.fromCharCode(parseInt(o,16));e&&zf(i)?r+=i:r+="%"+o,n+=2;continue}}r+=t[n]}return r}function nk(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($l(n)){let s=n.toUpperCase(),o=String.fromCharCode(parseInt(s,16));o!=="."&&zf(o)?e+=o:e+="%"+s,r+=2;continue}}G_(t[r])?e+=t[r]:e+=escape(t[r])}return e}function sk(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($l(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function ok(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!jf(r)){let n=Lf(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Uf(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}Df.exports={nonSimpleDomain:W_,recomposeAuthority:ok,reescapeHostDelimiters:Uf,normalizePercentEncoding:rk,normalizePathEncoding:nk,escapePreservingEscapes:sk,removeDotSegments:Q_,isIPv4:jf,isUUID:V_,normalizeIPv6:Lf,stringArrayToHexStripped:xl}});var Hf=z((gC,Ff)=>{"use strict";var{isUUID:ik}=Tl(),ak=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,lk=["http","https","ws","wss","urn","urn:uuid"];function ck(t){return lk.indexOf(t)!==-1}function Rl(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 qf(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Mf(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 dk(t){return t.secure=Rl(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function uk(t){if((t.port===(Rl(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 pk(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(ak);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=El(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function fk(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=El(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 hk(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!ik(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function mk(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Bf={scheme:"http",domainHost:!0,parse:qf,serialize:Mf},gk={scheme:"https",domainHost:Bf.domainHost,parse:qf,serialize:Mf},go={scheme:"ws",domainHost:!0,parse:dk,serialize:uk},yk={scheme:"wss",domainHost:go.domainHost,parse:go.parse,serialize:go.serialize},bk={scheme:"urn",parse:pk,serialize:fk,skipNormalize:!0},wk={scheme:"urn:uuid",parse:hk,serialize:mk,skipNormalize:!0},yo={http:Bf,https:gk,ws:go,wss:yk,urn:bk,"urn:uuid":wk};Object.setPrototypeOf(yo,null);function El(t){return t&&(yo[t]||yo[t.toLowerCase()])||void 0}Ff.exports={wsIsSecure:Rl,SCHEMES:yo,isValidSchemeName:ck,getSchemeHandler:El}});var Jf=z((yC,vo)=>{"use strict";var{normalizeIPv6:vk,removeDotSegments:Un,recomposeAuthority:Sk,normalizePercentEncoding:_k,normalizePathEncoding:kk,escapePreservingEscapes:$k,reescapeHostDelimiters:xk,isIPv4:Tk,nonSimpleDomain:Rk}=Tl(),{SCHEMES:Ek,getSchemeHandler:Vf}=Hf();function Pk(t,e){return typeof t=="string"?t=zk(t,e):typeof t=="object"&&(t=wo(cr(t,e),e)),t}function Ak(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 c=Gf(s,i,n,!0);return n.skipEscape=!0,cr(c,n)}function Gf(t,e,r,n){let s={};return n||(t=wo(cr(t,r),r),e=wo(cr(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=Un(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=Un(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=Un(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=Un(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 Ik(t,e,r){let n=Kf(t,r),s=Kf(e,r);return n!==void 0&&s!==void 0&&n.toLowerCase()===s.toLowerCase()}function cr(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=Vf(n.scheme||r.scheme);o&&o.serialize&&o.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=_k(r.path):(r.path=$k(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&s.push(r.scheme,":");let i=Sk(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=Un(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 Ck=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,Ok=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,Nk=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function jk(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(Ok);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",s=!0);let a=t.match(Nk);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 c=t.match(Ck);if(c){n.scheme=c[1],n.userinfo=c[3],n.host=c[4],n.port=parseInt(c[5],10),n.path=c[6]||"",n.query=c[7],n.fragment=c[8],isNaN(n.port)&&(n.port=c[5]);let d=jk(n,c);if(d!==void 0&&(n.error=n.error||d,s=!0),n.host)if(Tk(n.host)===!1){let S=vk(n.host);n.host=S.host.toLowerCase(),o=S.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=Vf(r.scheme||n.scheme);if(!r.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(r.domainHost||u&&u.domainHost)&&o===!1&&Rk(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=xk(unescape(n.host),o))),n.path&&(n.path=kk(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 zk(t,e){return Wf(t,e).normalized}function Wf(t,e){let{parsed:r,malformedAuthorityOrPort:n}=bo(t,e);return{normalized:n?t:cr(r,e),malformedAuthorityOrPort:n}}function Kf(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Wf(t,e);return n?void 0:r}if(typeof t=="object")return cr(t,e)}var Pl={SCHEMES:Ek,normalize:Pk,resolve:Ak,resolveComponent:Gf,equal:Ik,serialize:cr,parse:wo};vo.exports=Pl;vo.exports.default=Pl;vo.exports.fastUri=Pl});var Yf=z(Al=>{"use strict";Object.defineProperty(Al,"__esModule",{value:!0});var Zf=Jf();Zf.code='require("ajv/dist/runtime/uri").default';Al.default=Zf});var oh=z(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 Lk=zn();Object.defineProperty(Re,"KeywordCxt",{enumerable:!0,get:function(){return Lk.KeywordCxt}});var Ur=Z();Object.defineProperty(Re,"_",{enumerable:!0,get:function(){return Ur._}});Object.defineProperty(Re,"str",{enumerable:!0,get:function(){return Ur.str}});Object.defineProperty(Re,"stringify",{enumerable:!0,get:function(){return Ur.stringify}});Object.defineProperty(Re,"nil",{enumerable:!0,get:function(){return Ur.nil}});Object.defineProperty(Re,"Name",{enumerable:!0,get:function(){return Ur.Name}});Object.defineProperty(Re,"CodeGen",{enumerable:!0,get:function(){return Ur.CodeGen}});var Uk=fo(),rh=Ln(),Dk=sl(),Dn=mo(),qk=Z(),qn=On(),So=Cn(),Cl=ae(),Qf=Of(),Mk=Yf(),nh=(t,e)=>new RegExp(t,e);nh.code="new RegExp";var Bk=["removeAdditional","useDefaults","coerceTypes"],Fk=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Hk={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."},Kk={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Xf=200;function Vk(t){var e,r,n,s,o,i,a,c,d,u,h,S,b,w,k,R,E,I,L,ne,F,Ce,Ue,Jr,ft;let Zt=t.strict,St=(e=t.code)===null||e===void 0?void 0:e.optimize,fr=St===!0||St===void 0?1:St||0,hr=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:nh,es=(s=t.uriResolver)!==null&&s!==void 0?s:Mk.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:Zt)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Zt)!==null&&c!==void 0?c:!0,strictTypes:(u=(d=t.strictTypes)!==null&&d!==void 0?d:Zt)!==null&&u!==void 0?u:"log",strictTuples:(S=(h=t.strictTuples)!==null&&h!==void 0?h:Zt)!==null&&S!==void 0?S:"log",strictRequired:(w=(b=t.strictRequired)!==null&&b!==void 0?b:Zt)!==null&&w!==void 0?w:!1,code:t.code?{...t.code,optimize:fr,regExp:hr}:{optimize:fr,regExp:hr},loopRequired:(k=t.loopRequired)!==null&&k!==void 0?k:Xf,loopEnum:(R=t.loopEnum)!==null&&R!==void 0?R:Xf,meta:(E=t.meta)!==null&&E!==void 0?E:!0,messages:(I=t.messages)!==null&&I!==void 0?I:!0,inlineRefs:(L=t.inlineRefs)!==null&&L!==void 0?L:!0,schemaId:(ne=t.schemaId)!==null&&ne!==void 0?ne:"$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:(Jr=t.unicodeRegExp)!==null&&Jr!==void 0?Jr:!0,int32range:(ft=t.int32range)!==null&&ft!==void 0?ft:!0,uriResolver:es}}var Mn=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,...Vk(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new qk.ValueScope({scope:{},prefixes:Fk,es5:r,lines:n}),this.logger=Qk(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Dk.getRules)(),eh.call(this,Hk,e,"NOT SUPPORTED"),eh.call(this,Kk,e,"DEPRECATED","warn"),this._metaOpts=Zk.call(this),e.formats&&Wk.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&Jk.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Gk.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=Qf;n==="id"&&(s={...Qf},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 S=this._addSchema(u,h);return S.validate||i.call(this,S)}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 rh.default))throw h;return a.call(this,h),await c.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 c(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,qn.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=th.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=th.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,qn.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(e$.call(this,n,r),!r)return(0,Cl.eachItem)(n,o=>Il.call(this,o)),this;r$.call(this,r);let s={...r,type:(0,So.getJSONTypes)(r.type),schemaType:(0,So.getJSONTypes)(r.schemaType)};return(0,Cl.eachItem)(n,s.type.length===0?o=>Il.call(this,o,s):o=>s.type.forEach(i=>Il.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 c=n[a];if(typeof c!="object")continue;let{$data:d}=c.definition,u=i[a];d&&u&&(i[a]=sh(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 c=this._cache.get(e);if(c!==void 0)return c;n=(0,qn.normalizeId)(i||n);let d=qn.getSchemaRefs.call(this,e,n);return c=new Dn.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:d}),this._cache.set(c.schema,c),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),s&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):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}}};Mn.ValidationError=Uk.default;Mn.MissingRefError=rh.default;Re.default=Mn;function eh(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 th(t){return t=(0,qn.normalizeId)(t),this.schemas[t]||this.refs[t]}function Gk(){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 Wk(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function Jk(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 Zk(){let t={...this.opts};for(let e of Bk)delete t[e];return t}var Yk={log(){},warn(){},error(){}};function Qk(t){if(t===!1)return Yk;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 Xk=/^[a-z_$][a-z0-9_$:-]*$/i;function e$(t,e){let{RULES:r}=this;if((0,Cl.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!Xk.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 Il(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:c})=>c===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?t$.call(this,i,a,e.before):i.rules.push(a),o.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function t$(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 r$(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=sh(e)),t.validateSchema=this.compile(e,!0))}var n$={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function sh(t){return{anyOf:[t,n$]}}});var ih=z(Ol=>{"use strict";Object.defineProperty(Ol,"__esModule",{value:!0});var s$={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ol.default=s$});var dh=z(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.callRef=dr.getValidate=void 0;var o$=Ln(),ah=nt(),He=Z(),Dr=Et(),lh=mo(),_o=ae(),i$={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:s,schemaEnv:o,validateName:i,opts:a,self:c}=n,{root:d}=o;if((r==="#"||r==="#/")&&s===d.baseId)return h();let u=lh.resolveRef.call(c,d,s,r);if(u===void 0)throw new o$.default(n.opts.uriResolver,s,r);if(u instanceof lh.SchemaEnv)return S(u);return b(u);function h(){if(o===d)return ko(t,i,o,o.$async);let w=e.scopeValue("root",{ref:d});return ko(t,(0,He._)`${w}.validate`,d,d.$async)}function S(w){let k=ch(t,w);ko(t,k,w,w.$async)}function b(w){let k=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:k,errSchemaPath:r},R);t.mergeEvaluated(E),t.ok(R)}}};function ch(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=ch;function ko(t,e,r,n){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:c}=o,d=c.passContext?Dr.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,ah.callValidateCode)(t,e,d)}`),b(e),i||s.assign(w,!0)},k=>{s.if((0,He._)`!(${k} instanceof ${o.ValidationError})`,()=>s.throw(k)),S(k),i||s.assign(w,!1)}),t.ok(w)}function h(){t.result((0,ah.callValidateCode)(t,e,d),()=>b(e),()=>S(e))}function S(w){let k=(0,He._)`${w}.errors`;s.assign(Dr.default.vErrors,(0,He._)`${Dr.default.vErrors} === null ? ${k} : ${Dr.default.vErrors}.concat(${k})`),s.assign(Dr.default.errors,(0,He._)`${Dr.default.vErrors}.length`)}function b(w){var k;if(!o.opts.unevaluated)return;let R=(k=r?.validate)===null||k===void 0?void 0:k.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=ko;dr.default=i$});var uh=z(Nl=>{"use strict";Object.defineProperty(Nl,"__esModule",{value:!0});var a$=ih(),l$=dh(),c$=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",a$.default,l$.default];Nl.default=c$});var ph=z(jl=>{"use strict";Object.defineProperty(jl,"__esModule",{value:!0});var $o=Z(),Gt=$o.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}},d$={message:({keyword:t,schemaCode:e})=>(0,$o.str)`must be ${xo[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,$o._)`{comparison: ${xo[t].okStr}, limit: ${e}}`},u$={keyword:Object.keys(xo),type:"number",schemaType:"number",$data:!0,error:d$,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,$o._)`${r} ${xo[e].fail} ${n} || isNaN(${r})`)}};jl.default=u$});var fh=z(zl=>{"use strict";Object.defineProperty(zl,"__esModule",{value:!0});var Bn=Z(),p$={message:({schemaCode:t})=>(0,Bn.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Bn._)`{multipleOf: ${t}}`},f$={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:p$,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,Bn._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,Bn._)`${i} !== parseInt(${i})`;t.fail$data((0,Bn._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};zl.default=f$});var mh=z(Ll=>{"use strict";Object.defineProperty(Ll,"__esModule",{value:!0});function hh(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}Ll.default=hh;hh.code='require("ajv/dist/runtime/ucs2length").default'});var gh=z(Ul=>{"use strict";Object.defineProperty(Ul,"__esModule",{value:!0});var ur=Z(),h$=ae(),m$=mh(),g$={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}}`},y$={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:g$,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,h$.useFunc)(t.gen,m$.default)}(${r})`;t.fail$data((0,ur._)`${i} ${o} ${n}`)}};Ul.default=y$});var yh=z(Dl=>{"use strict";Object.defineProperty(Dl,"__esModule",{value:!0});var b$=nt(),w$=ae(),qr=Z(),v$={message:({schemaCode:t})=>(0,qr.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,qr._)`{pattern: ${t}}`},S$={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:v$,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:c}=i.opts.code,d=c.code==="new RegExp"?(0,qr._)`new RegExp`:(0,w$.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,qr._)`${d}(${o}, ${a}).test(${r})`),()=>e.assign(u,!1)),t.fail$data((0,qr._)`!${u}`)}else{let c=(0,b$.usePattern)(t,s);t.fail$data((0,qr._)`!${c}.test(${r})`)}}};Dl.default=S$});var bh=z(ql=>{"use strict";Object.defineProperty(ql,"__esModule",{value:!0});var Fn=Z(),_$={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Fn.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Fn._)`{limit: ${t}}`},k$={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:_$,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?Fn.operators.GT:Fn.operators.LT;t.fail$data((0,Fn._)`Object.keys(${r}).length ${s} ${n}`)}};ql.default=k$});var wh=z(Ml=>{"use strict";Object.defineProperty(Ml,"__esModule",{value:!0});var Hn=nt(),Kn=Z(),$$=ae(),x$={message:({params:{missingProperty:t}})=>(0,Kn.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Kn._)`{missingProperty: ${t}}`},T$={keyword:"required",type:"object",schemaType:"array",$data:!0,error:x$,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 c=r.length>=a.loopRequired;if(i.allErrors?d():u(),a.strictRequired){let b=t.parentSchema.properties,{definedProperties:w}=t.it;for(let k of r)if(b?.[k]===void 0&&!w.has(k)){let R=i.schemaEnv.baseId+i.errSchemaPath,E=`required property "${k}" is not defined at "${R}" (strictRequired)`;(0,$$.checkStrictMode)(i,E,i.opts.strictRequired)}}function d(){if(c||o)t.block$data(Kn.nil,h);else for(let b of r)(0,Hn.checkReportMissingProp)(t,b)}function u(){let b=e.let("missing");if(c||o){let w=e.let("valid",!0);t.block$data(w,()=>S(b,w)),t.ok(w)}else e.if((0,Hn.checkMissingProp)(t,r,b)),(0,Hn.reportMissingProp)(t,b),e.else()}function h(){e.forOf("prop",n,b=>{t.setParams({missingProperty:b}),e.if((0,Hn.noPropertyInData)(e,s,b,a.ownProperties),()=>t.error())})}function S(b,w){t.setParams({missingProperty:b}),e.forOf(b,n,()=>{e.assign(w,(0,Hn.propertyInData)(e,s,b,a.ownProperties)),e.if((0,Kn.not)(w),()=>{t.error(),e.break()})},Kn.nil)}}};Ml.default=T$});var vh=z(Bl=>{"use strict";Object.defineProperty(Bl,"__esModule",{value:!0});var Vn=Z(),R$={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Vn.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Vn._)`{limit: ${t}}`},E$={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:R$,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?Vn.operators.GT:Vn.operators.LT;t.fail$data((0,Vn._)`${r}.length ${s} ${n}`)}};Bl.default=E$});var To=z(Fl=>{"use strict";Object.defineProperty(Fl,"__esModule",{value:!0});var Sh=pl();Sh.code='require("ajv/dist/runtime/equal").default';Fl.default=Sh});var _h=z(Kl=>{"use strict";Object.defineProperty(Kl,"__esModule",{value:!0});var Hl=Cn(),Ee=Z(),P$=ae(),A$=To(),I$={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}}`},C$={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:I$,code(t){let{gen:e,data:r,$data:n,schema:s,parentSchema:o,schemaCode:i,it:a}=t;if(!n&&!s)return;let c=e.let("valid"),d=o.items?(0,Hl.getSchemaTypes)(o.items):[];t.block$data(c,u,(0,Ee._)`${i} === false`),t.ok(c);function u(){let w=e.let("i",(0,Ee._)`${r}.length`),k=e.let("j");t.setParams({i:w,j:k}),e.assign(c,!0),e.if((0,Ee._)`${w} > 1`,()=>(h()?S:b)(w,k))}function h(){return d.length>0&&!d.some(w=>w==="object"||w==="array")}function S(w,k){let R=e.name("item"),E=(0,Hl.checkDataTypes)(d,R,a.opts.strictNumbers,Hl.DataType.Wrong),I=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 ${I}[${R}] == "number"`,()=>{e.assign(k,(0,Ee._)`${I}[${R}]`),t.error(),e.assign(c,!1).break()}).code((0,Ee._)`${I}[${R}] = ${w}`)})}function b(w,k){let R=(0,P$.useFunc)(e,A$.default),E=e.name("outer");e.label(E).for((0,Ee._)`;${w}--;`,()=>e.for((0,Ee._)`${k} = ${w}; ${k}--;`,()=>e.if((0,Ee._)`${R}(${r}[${w}], ${r}[${k}])`,()=>{t.error(),e.assign(c,!1).break(E)})))}}};Kl.default=C$});var kh=z(Gl=>{"use strict";Object.defineProperty(Gl,"__esModule",{value:!0});var Vl=Z(),O$=ae(),N$=To(),j$={message:"must be equal to constant",params:({schemaCode:t})=>(0,Vl._)`{allowedValue: ${t}}`},z$={keyword:"const",$data:!0,error:j$,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,Vl._)`!${(0,O$.useFunc)(e,N$.default)}(${r}, ${s})`):t.fail((0,Vl._)`${o} !== ${r}`)}};Gl.default=z$});var $h=z(Wl=>{"use strict";Object.defineProperty(Wl,"__esModule",{value:!0});var Gn=Z(),L$=ae(),U$=To(),D$={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Gn._)`{allowedValues: ${t}}`},q$={keyword:"enum",schemaType:"array",$data:!0,error:D$,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,c,d=()=>c??(c=(0,L$.useFunc)(e,U$.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 b=e.const("vSchema",o);u=(0,Gn.or)(...s.map((w,k)=>S(b,k)))}t.pass(u);function h(){e.assign(u,!1),e.forOf("v",o,b=>e.if((0,Gn._)`${d()}(${r}, ${b})`,()=>e.assign(u,!0).break()))}function S(b,w){let k=s[w];return typeof k=="object"&&k!==null?(0,Gn._)`${d()}(${r}, ${b}[${w}])`:(0,Gn._)`${r} === ${k}`}}};Wl.default=q$});var xh=z(Jl=>{"use strict";Object.defineProperty(Jl,"__esModule",{value:!0});var M$=ph(),B$=fh(),F$=gh(),H$=yh(),K$=bh(),V$=wh(),G$=vh(),W$=_h(),J$=kh(),Z$=$h(),Y$=[M$.default,B$.default,F$.default,H$.default,K$.default,V$.default,G$.default,W$.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},J$.default,Z$.default];Jl.default=Y$});var Yl=z(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.validateAdditionalItems=void 0;var pr=Z(),Zl=ae(),Q$={message:({params:{len:t}})=>(0,pr.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,pr._)`{limit: ${t}}`},X$={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Q$,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Zl.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Th(t,n)}};function Th(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,Zl.alwaysValidSchema)(i,n)){let d=r.var("valid",(0,pr._)`${a} <= ${e.length}`);r.if((0,pr.not)(d),()=>c(d)),t.ok(d)}function c(d){r.forRange("i",e.length,a,u=>{t.subschema({keyword:o,dataProp:u,dataPropType:Zl.Type.Num},d),i.allErrors||r.if((0,pr.not)(d),()=>r.break())})}}Wn.validateAdditionalItems=Th;Wn.default=X$});var Ql=z(Jn=>{"use strict";Object.defineProperty(Jn,"__esModule",{value:!0});Jn.validateTuple=void 0;var Rh=Z(),Ro=ae(),ex=nt(),tx={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Eh(t,"additionalItems",e);r.items=!0,!(0,Ro.alwaysValidSchema)(r,e)&&t.ok((0,ex.validateArray)(t))}};function Eh(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 c=n.name("valid"),d=n.const("len",(0,Rh._)`${o}.length`);r.forEach((h,S)=>{(0,Ro.alwaysValidSchema)(a,h)||(n.if((0,Rh._)`${d} > ${S}`,()=>t.subschema({keyword:i,schemaProp:S,dataProp:S},c)),t.ok(c))});function u(h){let{opts:S,errSchemaPath:b}=a,w=r.length,k=w===h.minItems&&(w===h.maxItems||h[e]===!1);if(S.strictTuples&&!k){let R=`"${i}" is ${w}-tuple, but minItems or maxItems/${e} are not specified or different at path "${b}"`;(0,Ro.checkStrictMode)(a,R,S.strictTuples)}}}Jn.validateTuple=Eh;Jn.default=tx});var Ph=z(Xl=>{"use strict";Object.defineProperty(Xl,"__esModule",{value:!0});var rx=Ql(),nx={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,rx.validateTuple)(t,"items")};Xl.default=nx});var Ih=z(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});var Ah=Z(),sx=ae(),ox=nt(),ix=Yl(),ax={message:({params:{len:t}})=>(0,Ah.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Ah._)`{limit: ${t}}`},lx={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:ax,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,sx.alwaysValidSchema)(n,e)&&(s?(0,ix.validateAdditionalItems)(t,s):t.ok((0,ox.validateArray)(t)))}};ec.default=lx});var Ch=z(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});var ot=Z(),Eo=ae(),cx={message:({params:{min:t,max:e}})=>e===void 0?(0,ot.str)`must contain at least ${t} valid item(s)`:(0,ot.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,ot._)`{minContains: ${t}}`:(0,ot._)`{minContains: ${t}, maxContains: ${e}}`},dx={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:cx,code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t,i,a,{minContains:c,maxContains:d}=n;o.opts.next?(i=c===void 0?1:c,a=d):i=1;let u=e.const("len",(0,ot._)`${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 k=(0,ot._)`${u} >= ${i}`;a!==void 0&&(k=(0,ot._)`${k} && ${u} <= ${a}`),t.pass(k);return}o.items=!0;let h=e.name("valid");a===void 0&&i===1?b(h,()=>e.if(h,()=>e.break())):i===0?(e.let(h,!0),a!==void 0&&e.if((0,ot._)`${s}.length > 0`,S)):(e.let(h,!1),S()),t.result(h,()=>t.reset());function S(){let k=e.name("_valid"),R=e.let("count",0);b(k,()=>e.if(k,()=>w(R)))}function b(k,R){e.forRange("i",0,u,E=>{t.subschema({keyword:"contains",dataProp:E,dataPropType:Eo.Type.Num,compositeRule:!0},k),R()})}function w(k){e.code((0,ot._)`${k}++`),a===void 0?e.if((0,ot._)`${k} >= ${i}`,()=>e.assign(h,!0).break()):(e.if((0,ot._)`${k} > ${a}`,()=>e.assign(h,!1).break()),i===1?e.assign(h,!0):e.if((0,ot._)`${k} >= ${i}`,()=>e.assign(h,!0)))}}};tc.default=dx});var jh=z(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.validateSchemaDeps=bt.validatePropertyDeps=bt.error=void 0;var rc=Z(),ux=ae(),Zn=nt();bt.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,rc.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,rc._)`{property: ${t},
|
|
943
|
-
missingProperty: ${
|
|
933
|
+
`});import*as Ud from"zod/v3";import*as tn from"zod/v4-mini";function yt(t){return!!t._zod}function nn(t){let e=Object.values(t);if(e.length===0)return tn.object({});let n=e.every(yt),r=e.every(s=>!yt(s));if(n)return tn.object(t);if(r)return Ud.object(t);throw new Error("Mixed Zod versions detected in object shape.")}function Lt(t,e){return yt(t)?tn.safeParse(t,e):t.safeParse(e)}async function _s(t,e){return yt(t)?await tn.safeParseAsync(t,e):await t.safeParseAsync(e)}function zt(t){if(!t)return;let e;if(yt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function xn(t){if(t){if(typeof t=="object"){let e=t,n=t;if(!e._def&&!n._zod){let r=Object.values(t);if(r.length>0&&r.every(s=>typeof s=="object"&&s!==null&&(s._def!==void 0||s._zod!==void 0||typeof s.parse=="function")))return nn(t)}}if(yt(t)){let n=t._zod?.def;if(n&&(n.type==="object"||n.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function lw(t){return t.length===0?"object root":t.reduce((e,n,r)=>r===0?String(n):typeof n=="number"?`${e}[${n}]`:`${e}.${n}`,"")}function $s(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 ${lw(e.path)}`:e.message).join(`
|
|
934
|
+
`);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function Dd(t){return t.description}function qd(t){if(yt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Tn(t){if(yt(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 n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let r=t.value;if(r!==void 0)return r}var pr=j(()=>{});import*as l from"zod/v4";function rp(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function sp(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Mi,Md,Ut,Ts,_e,Bd,Fd,YE,cw,uw,Bi,Ke,fr,Hd,xe,Xe,et,Te,Rs,Kd,Fi,Vd,Gd,Hi,hr,M,Ki,Wd,Jd,QE,Es,dw,Ps,pw,mr,Rn,Zd,fw,hw,mw,gw,yw,bw,Vi,ww,vw,Gi,As,Sw,kw,Is,_w,gr,yr,$w,br,En,xw,wr,Cs,Os,Ns,XE,js,Ls,zs,Yd,Qd,Xd,Wi,ep,vr,Pn,tp,Tw,Us,Rw,Ds,Ew,Ji,Pw,qs,Aw,Iw,Cw,Ow,Nw,jw,Lw,zw,Uw,Dw,Ms,qw,Mw,Bs,Zi,Yi,Qi,Bw,Fw,Hw,Xi,Kw,Vw,Gw,Ww,Jw,np,Fs,Zw,Hs,eP,Yw,An,Qw,tP,Sr,Xw,ea,ev,tv,nv,rv,sv,ov,iv,xs,av,lv,cv,kr,ta,uv,dv,pv,fv,hv,mv,gv,yv,bv,wv,vv,Sv,kv,_v,$v,xv,Tv,Rv,In,Ev,Pv,Av,Ks,Iv,Cv,Ov,na,Nv,nP,rP,sP,oP,iP,aP,U,qi,Cn=j(()=>{Mi="2025-11-25",Md=[Mi,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ut="io.modelcontextprotocol/related-task",Ts="2.0",_e=l.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Bd=l.union([l.string(),l.number().int()]),Fd=l.string(),YE=l.looseObject({ttl:l.number().optional(),pollInterval:l.number().optional()}),cw=l.object({ttl:l.number().optional()}),uw=l.object({taskId:l.string()}),Bi=l.looseObject({progressToken:Bd.optional(),[Ut]:uw.optional()}),Ke=l.object({_meta:Bi.optional()}),fr=Ke.extend({task:cw.optional()}),Hd=t=>fr.safeParse(t).success,xe=l.object({method:l.string(),params:Ke.loose().optional()}),Xe=l.object({_meta:Bi.optional()}),et=l.object({method:l.string(),params:Xe.loose().optional()}),Te=l.looseObject({_meta:Bi.optional()}),Rs=l.union([l.string(),l.number().int()]),Kd=l.object({jsonrpc:l.literal(Ts),id:Rs,...xe.shape}).strict(),Fi=t=>Kd.safeParse(t).success,Vd=l.object({jsonrpc:l.literal(Ts),...et.shape}).strict(),Gd=t=>Vd.safeParse(t).success,Hi=l.object({jsonrpc:l.literal(Ts),id:Rs,result:Te}).strict(),hr=t=>Hi.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={}));Ki=l.object({jsonrpc:l.literal(Ts),id:Rs.optional(),error:l.object({code:l.number().int(),message:l.string(),data:l.unknown().optional()})}).strict(),Wd=t=>Ki.safeParse(t).success,Jd=l.union([Kd,Vd,Hi,Ki]),QE=l.union([Hi,Ki]),Es=Te.strict(),dw=Xe.extend({requestId:Rs.optional(),reason:l.string().optional()}),Ps=et.extend({method:l.literal("notifications/cancelled"),params:dw}),pw=l.object({src:l.string(),mimeType:l.string().optional(),sizes:l.array(l.string()).optional(),theme:l.enum(["light","dark"]).optional()}),mr=l.object({icons:l.array(pw).optional()}),Rn=l.object({name:l.string(),title:l.string().optional()}),Zd=Rn.extend({...Rn.shape,...mr.shape,version:l.string(),websiteUrl:l.string().optional(),description:l.string().optional()}),fw=l.intersection(l.object({applyDefaults:l.boolean().optional()}),l.record(l.string(),l.unknown())),hw=l.preprocess(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,l.intersection(l.object({form:fw.optional(),url:_e.optional()}),l.record(l.string(),l.unknown()).optional())),mw=l.looseObject({list:_e.optional(),cancel:_e.optional(),requests:l.looseObject({sampling:l.looseObject({createMessage:_e.optional()}).optional(),elicitation:l.looseObject({create:_e.optional()}).optional()}).optional()}),gw=l.looseObject({list:_e.optional(),cancel:_e.optional(),requests:l.looseObject({tools:l.looseObject({call:_e.optional()}).optional()}).optional()}),yw=l.object({experimental:l.record(l.string(),_e).optional(),sampling:l.object({context:_e.optional(),tools:_e.optional()}).optional(),elicitation:hw.optional(),roots:l.object({listChanged:l.boolean().optional()}).optional(),tasks:mw.optional(),extensions:l.record(l.string(),_e).optional()}),bw=Ke.extend({protocolVersion:l.string(),capabilities:yw,clientInfo:Zd}),Vi=xe.extend({method:l.literal("initialize"),params:bw}),ww=l.object({experimental:l.record(l.string(),_e).optional(),logging:_e.optional(),completions:_e.optional(),prompts:l.object({listChanged:l.boolean().optional()}).optional(),resources:l.object({subscribe:l.boolean().optional(),listChanged:l.boolean().optional()}).optional(),tools:l.object({listChanged:l.boolean().optional()}).optional(),tasks:gw.optional(),extensions:l.record(l.string(),_e).optional()}),vw=Te.extend({protocolVersion:l.string(),capabilities:ww,serverInfo:Zd,instructions:l.string().optional()}),Gi=et.extend({method:l.literal("notifications/initialized"),params:Xe.optional()}),As=xe.extend({method:l.literal("ping"),params:Ke.optional()}),Sw=l.object({progress:l.number(),total:l.optional(l.number()),message:l.optional(l.string())}),kw=l.object({...Xe.shape,...Sw.shape,progressToken:Bd}),Is=et.extend({method:l.literal("notifications/progress"),params:kw}),_w=Ke.extend({cursor:Fd.optional()}),gr=xe.extend({params:_w.optional()}),yr=Te.extend({nextCursor:Fd.optional()}),$w=l.enum(["working","input_required","completed","failed","cancelled"]),br=l.object({taskId:l.string(),status:$w,ttl:l.union([l.number(),l.null()]),createdAt:l.string(),lastUpdatedAt:l.string(),pollInterval:l.optional(l.number()),statusMessage:l.optional(l.string())}),En=Te.extend({task:br}),xw=Xe.merge(br),wr=et.extend({method:l.literal("notifications/tasks/status"),params:xw}),Cs=xe.extend({method:l.literal("tasks/get"),params:Ke.extend({taskId:l.string()})}),Os=Te.merge(br),Ns=xe.extend({method:l.literal("tasks/result"),params:Ke.extend({taskId:l.string()})}),XE=Te.loose(),js=gr.extend({method:l.literal("tasks/list")}),Ls=yr.extend({tasks:l.array(br)}),zs=xe.extend({method:l.literal("tasks/cancel"),params:Ke.extend({taskId:l.string()})}),Yd=Te.merge(br),Qd=l.object({uri:l.string(),mimeType:l.optional(l.string()),_meta:l.record(l.string(),l.unknown()).optional()}),Xd=Qd.extend({text:l.string()}),Wi=l.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),ep=Qd.extend({blob:Wi}),vr=l.enum(["user","assistant"]),Pn=l.object({audience:l.array(vr).optional(),priority:l.number().min(0).max(1).optional(),lastModified:l.iso.datetime({offset:!0}).optional()}),tp=l.object({...Rn.shape,...mr.shape,uri:l.string(),description:l.optional(l.string()),mimeType:l.optional(l.string()),size:l.optional(l.number()),annotations:Pn.optional(),_meta:l.optional(l.looseObject({}))}),Tw=l.object({...Rn.shape,...mr.shape,uriTemplate:l.string(),description:l.optional(l.string()),mimeType:l.optional(l.string()),annotations:Pn.optional(),_meta:l.optional(l.looseObject({}))}),Us=gr.extend({method:l.literal("resources/list")}),Rw=yr.extend({resources:l.array(tp)}),Ds=gr.extend({method:l.literal("resources/templates/list")}),Ew=yr.extend({resourceTemplates:l.array(Tw)}),Ji=Ke.extend({uri:l.string()}),Pw=Ji,qs=xe.extend({method:l.literal("resources/read"),params:Pw}),Aw=Te.extend({contents:l.array(l.union([Xd,ep]))}),Iw=et.extend({method:l.literal("notifications/resources/list_changed"),params:Xe.optional()}),Cw=Ji,Ow=xe.extend({method:l.literal("resources/subscribe"),params:Cw}),Nw=Ji,jw=xe.extend({method:l.literal("resources/unsubscribe"),params:Nw}),Lw=Xe.extend({uri:l.string()}),zw=et.extend({method:l.literal("notifications/resources/updated"),params:Lw}),Uw=l.object({name:l.string(),description:l.optional(l.string()),required:l.optional(l.boolean())}),Dw=l.object({...Rn.shape,...mr.shape,description:l.optional(l.string()),arguments:l.optional(l.array(Uw)),_meta:l.optional(l.looseObject({}))}),Ms=gr.extend({method:l.literal("prompts/list")}),qw=yr.extend({prompts:l.array(Dw)}),Mw=Ke.extend({name:l.string(),arguments:l.record(l.string(),l.string()).optional()}),Bs=xe.extend({method:l.literal("prompts/get"),params:Mw}),Zi=l.object({type:l.literal("text"),text:l.string(),annotations:Pn.optional(),_meta:l.record(l.string(),l.unknown()).optional()}),Yi=l.object({type:l.literal("image"),data:Wi,mimeType:l.string(),annotations:Pn.optional(),_meta:l.record(l.string(),l.unknown()).optional()}),Qi=l.object({type:l.literal("audio"),data:Wi,mimeType:l.string(),annotations:Pn.optional(),_meta:l.record(l.string(),l.unknown()).optional()}),Bw=l.object({type:l.literal("tool_use"),name:l.string(),id:l.string(),input:l.record(l.string(),l.unknown()),_meta:l.record(l.string(),l.unknown()).optional()}),Fw=l.object({type:l.literal("resource"),resource:l.union([Xd,ep]),annotations:Pn.optional(),_meta:l.record(l.string(),l.unknown()).optional()}),Hw=tp.extend({type:l.literal("resource_link")}),Xi=l.union([Zi,Yi,Qi,Hw,Fw]),Kw=l.object({role:vr,content:Xi}),Vw=Te.extend({description:l.string().optional(),messages:l.array(Kw)}),Gw=et.extend({method:l.literal("notifications/prompts/list_changed"),params:Xe.optional()}),Ww=l.object({title:l.string().optional(),readOnlyHint:l.boolean().optional(),destructiveHint:l.boolean().optional(),idempotentHint:l.boolean().optional(),openWorldHint:l.boolean().optional()}),Jw=l.object({taskSupport:l.enum(["required","optional","forbidden"]).optional()}),np=l.object({...Rn.shape,...mr.shape,description:l.string().optional(),inputSchema:l.object({type:l.literal("object"),properties:l.record(l.string(),_e).optional(),required:l.array(l.string()).optional()}).catchall(l.unknown()),outputSchema:l.object({type:l.literal("object"),properties:l.record(l.string(),_e).optional(),required:l.array(l.string()).optional()}).catchall(l.unknown()).optional(),annotations:Ww.optional(),execution:Jw.optional(),_meta:l.record(l.string(),l.unknown()).optional()}),Fs=gr.extend({method:l.literal("tools/list")}),Zw=yr.extend({tools:l.array(np)}),Hs=Te.extend({content:l.array(Xi).default([]),structuredContent:l.record(l.string(),l.unknown()).optional(),isError:l.boolean().optional()}),eP=Hs.or(Te.extend({toolResult:l.unknown()})),Yw=fr.extend({name:l.string(),arguments:l.record(l.string(),l.unknown()).optional()}),An=xe.extend({method:l.literal("tools/call"),params:Yw}),Qw=et.extend({method:l.literal("notifications/tools/list_changed"),params:Xe.optional()}),tP=l.object({autoRefresh:l.boolean().default(!0),debounceMs:l.number().int().nonnegative().default(300)}),Sr=l.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),Xw=Ke.extend({level:Sr}),ea=xe.extend({method:l.literal("logging/setLevel"),params:Xw}),ev=Xe.extend({level:Sr,logger:l.string().optional(),data:l.unknown()}),tv=et.extend({method:l.literal("notifications/message"),params:ev}),nv=l.object({name:l.string().optional()}),rv=l.object({hints:l.array(nv).optional(),costPriority:l.number().min(0).max(1).optional(),speedPriority:l.number().min(0).max(1).optional(),intelligencePriority:l.number().min(0).max(1).optional()}),sv=l.object({mode:l.enum(["auto","required","none"]).optional()}),ov=l.object({type:l.literal("tool_result"),toolUseId:l.string().describe("The unique identifier for the corresponding tool call."),content:l.array(Xi).default([]),structuredContent:l.object({}).loose().optional(),isError:l.boolean().optional(),_meta:l.record(l.string(),l.unknown()).optional()}),iv=l.discriminatedUnion("type",[Zi,Yi,Qi]),xs=l.discriminatedUnion("type",[Zi,Yi,Qi,Bw,ov]),av=l.object({role:vr,content:l.union([xs,l.array(xs)]),_meta:l.record(l.string(),l.unknown()).optional()}),lv=fr.extend({messages:l.array(av),modelPreferences:rv.optional(),systemPrompt:l.string().optional(),includeContext:l.enum(["none","thisServer","allServers"]).optional(),temperature:l.number().optional(),maxTokens:l.number().int(),stopSequences:l.array(l.string()).optional(),metadata:_e.optional(),tools:l.array(np).optional(),toolChoice:sv.optional()}),cv=xe.extend({method:l.literal("sampling/createMessage"),params:lv}),kr=Te.extend({model:l.string(),stopReason:l.optional(l.enum(["endTurn","stopSequence","maxTokens"]).or(l.string())),role:vr,content:iv}),ta=Te.extend({model:l.string(),stopReason:l.optional(l.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(l.string())),role:vr,content:l.union([xs,l.array(xs)])}),uv=l.object({type:l.literal("boolean"),title:l.string().optional(),description:l.string().optional(),default:l.boolean().optional()}),dv=l.object({type:l.literal("string"),title:l.string().optional(),description:l.string().optional(),minLength:l.number().optional(),maxLength:l.number().optional(),format:l.enum(["email","uri","date","date-time"]).optional(),default:l.string().optional()}),pv=l.object({type:l.enum(["number","integer"]),title:l.string().optional(),description:l.string().optional(),minimum:l.number().optional(),maximum:l.number().optional(),default:l.number().optional()}),fv=l.object({type:l.literal("string"),title:l.string().optional(),description:l.string().optional(),enum:l.array(l.string()),default:l.string().optional()}),hv=l.object({type:l.literal("string"),title:l.string().optional(),description:l.string().optional(),oneOf:l.array(l.object({const:l.string(),title:l.string()})),default:l.string().optional()}),mv=l.object({type:l.literal("string"),title:l.string().optional(),description:l.string().optional(),enum:l.array(l.string()),enumNames:l.array(l.string()).optional(),default:l.string().optional()}),gv=l.union([fv,hv]),yv=l.object({type:l.literal("array"),title:l.string().optional(),description:l.string().optional(),minItems:l.number().optional(),maxItems:l.number().optional(),items:l.object({type:l.literal("string"),enum:l.array(l.string())}),default:l.array(l.string()).optional()}),bv=l.object({type:l.literal("array"),title:l.string().optional(),description:l.string().optional(),minItems:l.number().optional(),maxItems:l.number().optional(),items:l.object({anyOf:l.array(l.object({const:l.string(),title:l.string()}))}),default:l.array(l.string()).optional()}),wv=l.union([yv,bv]),vv=l.union([mv,gv,wv]),Sv=l.union([vv,uv,dv,pv]),kv=fr.extend({mode:l.literal("form").optional(),message:l.string(),requestedSchema:l.object({type:l.literal("object"),properties:l.record(l.string(),Sv),required:l.array(l.string()).optional()})}),_v=fr.extend({mode:l.literal("url"),message:l.string(),elicitationId:l.string(),url:l.string().url()}),$v=l.union([kv,_v]),xv=xe.extend({method:l.literal("elicitation/create"),params:$v}),Tv=Xe.extend({elicitationId:l.string()}),Rv=et.extend({method:l.literal("notifications/elicitation/complete"),params:Tv}),In=Te.extend({action:l.enum(["accept","decline","cancel"]),content:l.preprocess(t=>t===null?void 0:t,l.record(l.string(),l.union([l.string(),l.number(),l.boolean(),l.array(l.string())])).optional())}),Ev=l.object({type:l.literal("ref/resource"),uri:l.string()}),Pv=l.object({type:l.literal("ref/prompt"),name:l.string()}),Av=Ke.extend({ref:l.union([Pv,Ev]),argument:l.object({name:l.string(),value:l.string()}),context:l.object({arguments:l.record(l.string(),l.string()).optional()}).optional()}),Ks=xe.extend({method:l.literal("completion/complete"),params:Av});Iv=Te.extend({completion:l.looseObject({values:l.array(l.string()).max(100),total:l.optional(l.number().int()),hasMore:l.optional(l.boolean())})}),Cv=l.object({uri:l.string().startsWith("file://"),name:l.string().optional(),_meta:l.record(l.string(),l.unknown()).optional()}),Ov=xe.extend({method:l.literal("roots/list"),params:Ke.optional()}),na=Te.extend({roots:l.array(Cv)}),Nv=et.extend({method:l.literal("notifications/roots/list_changed"),params:Xe.optional()}),nP=l.union([As,Vi,Ks,ea,Bs,Ms,Us,Ds,qs,Ow,jw,An,Fs,Cs,Ns,js,zs]),rP=l.union([Ps,Is,Gi,Nv,wr]),sP=l.union([Es,kr,ta,In,na,Os,Ls,En]),oP=l.union([As,cv,xv,Ov,Cs,Ns,js,zs]),iP=l.union([Ps,Is,tv,zw,Iw,Qw,Gw,wr,Rv]),aP=l.union([Es,vw,Iv,Vw,qw,Rw,Ew,Aw,Hs,Zw,Os,Ls,En]),U=class t extends Error{constructor(e,n,r){super(`MCP error ${e}: ${n}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,n,r){if(e===M.UrlElicitationRequired&&r){let s=r;if(s.elicitations)return new qi(s.elicitations,n)}return new t(e,n,r)}},qi=class extends U{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(M.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Dt(t){return t==="completed"||t==="failed"||t==="cancelled"}var op=j(()=>{});var ap,ip,lp,Vs=j(()=>{ap=Symbol("Let zodToJsonSchema decide on which parser to use"),ip={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"},lp=t=>typeof t=="string"?{...ip,name:t}:{...ip,...t}});var cp,ra=j(()=>{Vs();cp=t=>{let e=lp(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}}});function sa(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function ae(t,e,n,r,s){t[e]=n,sa(t,e,r,s)}var qt=j(()=>{});var Gs,Ws=j(()=>{Gs=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].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"?Gs(e,t.currentPath):e.join("/")}}var tt=j(()=>{Ws()});import{ZodFirstPartyTypeKind as jv}from"zod/v3";function up(t,e){let n={type:"array"};return t.type?._def&&t.type?._def?.typeName!==jv.ZodAny&&(n.items=F(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ae(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ae(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ae(n,"minItems",t.exactLength.value,t.exactLength.message,e),ae(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}var oa=j(()=>{qt();ke()});function dp(t,e){let n={type:"integer",format:"int64"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?ae(n,"minimum",r.value,r.message,e):ae(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),ae(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ae(n,"maximum",r.value,r.message,e):ae(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),ae(n,"maximum",r.value,r.message,e));break;case"multipleOf":ae(n,"multipleOf",r.value,r.message,e);break}return n}var ia=j(()=>{qt()});function pp(){return{type:"boolean"}}var aa=j(()=>{});function Js(t,e){return F(t.type._def,e)}var Zs=j(()=>{ke()});var fp,la=j(()=>{ke();fp=(t,e)=>F(t.innerType._def,e)});function ca(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,o)=>ca(t,e,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Lv(t,e)}}var Lv,ua=j(()=>{qt();Lv=(t,e)=>{let n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(let r of t.checks)switch(r.kind){case"min":ae(n,"minimum",r.value,r.message,e);break;case"max":ae(n,"maximum",r.value,r.message,e);break}return n}});function hp(t,e){return{...F(t.innerType._def,e),default:t.defaultValue()}}var da=j(()=>{ke()});function mp(t,e){return e.effectStrategy==="input"?F(t.schema._def,e):be(e)}var pa=j(()=>{ke();tt()});function gp(t){return{type:"string",enum:Array.from(t.values)}}var fa=j(()=>{});function yp(t,e){let n=[F(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),F(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return n.forEach(o=>{if(zv(o))s.push(...o.allOf),o.unevaluatedProperties===void 0&&(r=void 0);else{let i=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:a,...c}=o;i=c}else r=void 0;s.push(i)}}),s.length?{allOf:s,...r}:void 0}var zv,ha=j(()=>{ke();zv=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function bp(t,e){let n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}var ma=j(()=>{});function Ys(t,e){let n={type:"string"};if(t.checks)for(let r of t.checks)switch(r.kind){case"min":ae(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":ae(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":ct(n,"email",r.message,e);break;case"format:idn-email":ct(n,"idn-email",r.message,e);break;case"pattern:zod":je(n,lt.email,r.message,e);break}break;case"url":ct(n,"uri",r.message,e);break;case"uuid":ct(n,"uuid",r.message,e);break;case"regex":je(n,r.regex,r.message,e);break;case"cuid":je(n,lt.cuid,r.message,e);break;case"cuid2":je(n,lt.cuid2,r.message,e);break;case"startsWith":je(n,RegExp(`^${ya(r.value,e)}`),r.message,e);break;case"endsWith":je(n,RegExp(`${ya(r.value,e)}$`),r.message,e);break;case"datetime":ct(n,"date-time",r.message,e);break;case"date":ct(n,"date",r.message,e);break;case"time":ct(n,"time",r.message,e);break;case"duration":ct(n,"duration",r.message,e);break;case"length":ae(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),ae(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{je(n,RegExp(ya(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&ct(n,"ipv4",r.message,e),r.version!=="v4"&&ct(n,"ipv6",r.message,e);break}case"base64url":je(n,lt.base64url,r.message,e);break;case"jwt":je(n,lt.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&je(n,lt.ipv4Cidr,r.message,e),r.version!=="v4"&&je(n,lt.ipv6Cidr,r.message,e);break}case"emoji":je(n,lt.emoji(),r.message,e);break;case"ulid":{je(n,lt.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{ct(n,"binary",r.message,e);break}case"contentEncoding:base64":{ae(n,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{je(n,lt.base64,r.message,e);break}}break}case"nanoid":je(n,lt.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function ya(t,e){return e.patternStrategy==="escape"?Dv(t):t}function Dv(t){let e="";for(let n=0;n<t.length;n++)Uv.has(t[n])||(e+="\\"),e+=t[n];return e}function ct(t,e,n,r){t.format||t.anyOf?.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.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,...n&&r.errorMessages&&{errorMessage:{format:n}}})):ae(t,"format",e,n,r)}function je(t,e,n,r){t.pattern||t.allOf?.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.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:wp(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):ae(t,"pattern",wp(e,r),n,r)}function wp(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},r=n.i?t.source.toLowerCase():t.source,s="",o=!1,i=!1,a=!1;for(let c=0;c<r.length;c++){if(o){s+=r[c],o=!1;continue}if(n.i){if(i){if(r[c].match(/[a-z]/)){a?(s+=r[c],s+=`${r[c-2]}-${r[c]}`.toUpperCase(),a=!1):r[c+1]==="-"&&r[c+2]?.match(/[a-z]/)?(s+=r[c],a=!0):s+=`${r[c]}${r[c].toUpperCase()}`;continue}}else if(r[c].match(/[a-z]/)){s+=`[${r[c]}${r[c].toUpperCase()}]`;continue}}if(n.m){if(r[c]==="^"){s+=`(^|(?<=[\r
|
|
935
|
+
]))`;continue}else if(r[c]==="$"){s+=`($|(?=[\r
|
|
936
|
+
]))`;continue}}if(n.s&&r[c]==="."){s+=i?`${r[c]}\r
|
|
937
|
+
`:`[${r[c]}\r
|
|
938
|
+
]`;continue}s+=r[c],r[c]==="\\"?o=!0:i&&r[c]==="]"?i=!1:!i&&r[c]==="["&&(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 ga,lt,Uv,Qs=j(()=>{qt();lt={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:()=>(ga===void 0&&(ga=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ga),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-_]*$/};Uv=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});import{ZodFirstPartyTypeKind as _r}from"zod/v3";function Xs(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===_r.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((r,s)=>({...r,[s]:F(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??be(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:F(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===_r.ZodString&&t.keyType._def.checks?.length){let{type:r,...s}=Ys(t.keyType._def,e);return{...n,propertyNames:s}}else{if(t.keyType?._def.typeName===_r.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===_r.ZodBranded&&t.keyType._def.type._def.typeName===_r.ZodString&&t.keyType._def.type._def.checks?.length){let{type:r,...s}=Js(t.keyType._def,e);return{...n,propertyNames:s}}}return n}var eo=j(()=>{ke();Qs();Zs();tt()});function vp(t,e){if(e.mapStrategy==="record")return Xs(t,e);let n=F(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||be(e),r=F(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||be(e);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}var ba=j(()=>{ke();eo();tt()});function Sp(t){let e=t.values,r=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(r.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}var wa=j(()=>{});function kp(t){return t.target==="openAi"?void 0:{not:be({...t,currentPath:[...t.currentPath,"not"]})}}var va=j(()=>{tt()});function _p(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Sa=j(()=>{});function xp(t,e){if(e.target==="openApi3")return $p(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in $r&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((s,o)=>{let i=$r[o._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=n.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(r.length===n.length){let s=r.filter((o,i,a)=>a.indexOf(o)===i);return{type:s.length>1?s:s[0],enum:n.reduce((o,i)=>o.includes(i._def.value)?o:[...o,i._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,s)=>[...r,...s._def.values.filter(o=>!r.includes(o))],[])};return $p(t,e)}var $r,$p,to=j(()=>{ke();$r={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};$p=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,s)=>F(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0}});function Tp(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:$r[t.innerType._def.typeName],nullable:!0}:{type:[$r[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=F(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=F(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}var ka=j(()=>{ke();to()});function Rp(t,e){let n={type:"number"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"int":n.type="integer",sa(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?ae(n,"minimum",r.value,r.message,e):ae(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),ae(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ae(n,"maximum",r.value,r.message,e):ae(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),ae(n,"maximum",r.value,r.message,e));break;case"multipleOf":ae(n,"multipleOf",r.value,r.message,e);break}return n}var _a=j(()=>{qt()});function Ep(t,e){let n=e.target==="openAi",r={type:"object",properties:{}},s=[],o=t.shape();for(let a in o){let c=o[a];if(c===void 0||c._def===void 0)continue;let u=Mv(c);u&&n&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let p=F(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});p!==void 0&&(r.properties[a]=p,u||s.push(a))}s.length&&(r.required=s);let i=qv(t,e);return i!==void 0&&(r.additionalProperties=i),r}function qv(t,e){if(t.catchall._def.typeName!=="ZodNever")return F(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 Mv(t){try{return t.isOptional()}catch{return!0}}var $a=j(()=>{ke()});var Pp,xa=j(()=>{ke();tt();Pp=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return F(t.innerType._def,e);let n=F(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:be(e)},n]}:be(e)}});var Ap,Ta=j(()=>{ke();Ap=(t,e)=>{if(e.pipeStrategy==="input")return F(t.in._def,e);if(e.pipeStrategy==="output")return F(t.out._def,e);let n=F(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=F(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(s=>s!==void 0)}}});function Ip(t,e){return F(t.type._def,e)}var Ra=j(()=>{ke()});function Cp(t,e){let r={type:"array",uniqueItems:!0,items:F(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ae(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ae(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}var Ea=j(()=>{qt();ke()});function Op(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>F(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:F(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>F(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}var Pa=j(()=>{ke()});function Np(t){return{not:be(t)}}var Aa=j(()=>{tt()});function jp(t){return be(t)}var Ia=j(()=>{tt()});var Lp,Ca=j(()=>{ke();Lp=(t,e)=>F(t.innerType._def,e)});import{ZodFirstPartyTypeKind as oe}from"zod/v3";var zp,Oa=j(()=>{tt();oa();ia();aa();Zs();la();ua();da();pa();fa();ha();ma();ba();wa();va();Sa();ka();_a();$a();xa();Ta();Ra();eo();Ea();Qs();Pa();Aa();to();Ia();Ca();zp=(t,e,n)=>{switch(e){case oe.ZodString:return Ys(t,n);case oe.ZodNumber:return Rp(t,n);case oe.ZodObject:return Ep(t,n);case oe.ZodBigInt:return dp(t,n);case oe.ZodBoolean:return pp();case oe.ZodDate:return ca(t,n);case oe.ZodUndefined:return Np(n);case oe.ZodNull:return _p(n);case oe.ZodArray:return up(t,n);case oe.ZodUnion:case oe.ZodDiscriminatedUnion:return xp(t,n);case oe.ZodIntersection:return yp(t,n);case oe.ZodTuple:return Op(t,n);case oe.ZodRecord:return Xs(t,n);case oe.ZodLiteral:return bp(t,n);case oe.ZodEnum:return gp(t);case oe.ZodNativeEnum:return Sp(t);case oe.ZodNullable:return Tp(t,n);case oe.ZodOptional:return Pp(t,n);case oe.ZodMap:return vp(t,n);case oe.ZodSet:return Cp(t,n);case oe.ZodLazy:return()=>t.getter()._def;case oe.ZodPromise:return Ip(t,n);case oe.ZodNaN:case oe.ZodNever:return kp(n);case oe.ZodEffects:return mp(t,n);case oe.ZodAny:return be(n);case oe.ZodUnknown:return jp(n);case oe.ZodDefault:return hp(t,n);case oe.ZodBranded:return Js(t,n);case oe.ZodReadonly:return Lp(t,n);case oe.ZodCatch:return fp(t,n);case oe.ZodPipeline:return Ap(t,n);case oe.ZodFunction:case oe.ZodVoid:case oe.ZodSymbol:return;default:return(r=>{})(e)}}});function F(t,e,n=!1){let r=e.seen.get(t);if(e.override){let a=e.override?.(t,e,r,n);if(a!==ap)return a}if(r&&!n){let a=Bv(r,e);if(a!==void 0)return a}let s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);let o=zp(t,t.typeName,e),i=typeof o=="function"?F(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 Bv,Fv,ke=j(()=>{Vs();Oa();Ws();tt();Bv=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Gs(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,r)=>e.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),be(e)):e.$refStrategy==="seen"?be(e):void 0}},Fv=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n)});var Up=j(()=>{});var Na,ja=j(()=>{ke();ra();tt();Na=(t,e)=>{let n=cp(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,p])=>({...c,[u]:F(p._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0)??be(n)}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=F(t._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1)??be(n),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(o.title=i),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));let a=s===void 0?r?{...o,[n.definitionPath]:r}:o:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...r,[s]:o}};return n.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),n.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 Dp=j(()=>{Vs();ra();qt();Ws();ke();Up();tt();oa();ia();aa();Zs();la();ua();da();pa();fa();ha();ma();ba();wa();va();Sa();ka();_a();$a();xa();Ta();Ra();Ca();eo();Ea();Qs();Pa();Aa();to();Ia();Oa();ja();ja()});import*as qp 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 La(t,e){return yt(t)?qp.toJSONSchema(t,{target:Hv(e?.target),io:e?.pipeStrategy??"input"}):Na(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function za(t){let n=zt(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=Tn(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function Ua(t,e){let n=Lt(t,e);if(!n.success)throw n.error;return n.data}var Da=j(()=>{pr();Dp()});function Mp(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Bp(t,e){let n={...t};for(let r in e){let s=r,o=e[s];if(o===void 0)continue;let i=n[s];Mp(i)&&Mp(o)?n[s]={...i,...o}:n[s]=o}return n}var Kv,no,Fp=j(()=>{pr();Cn();op();Da();Kv=6e4,no=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(Ps,n=>{this._oncancel(n)}),this.setNotificationHandler(Is,n=>{this._onprogress(n)}),this.setRequestHandler(As,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Cs,async(n,r)=>{let s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new U(M.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(Ns,async(n,r)=>{let s=async()=>{let o=n.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(o,r.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,p=this._requestResolvers.get(u);if(p)if(this._requestResolvers.delete(u),a.type==="response")p(c);else{let h=c,k=new U(h.error.code,h.error.message,h.error.data);p(k)}else{let h=a.type==="response"?"Response":"Error";this._onerror(new Error(`${h} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:r.requestId})}}let i=await this._taskStore.getTask(o,r.sessionId);if(!i)throw new U(M.InvalidParams,`Task not found: ${o}`);if(!Dt(i.status))return await this._waitForTaskUpdate(o,r.signal),await s();if(Dt(i.status)){let a=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[Ut]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(js,async(n,r)=>{try{let{tasks:s,nextCursor:o}=await this._taskStore.listTasks(n.params?.cursor,r.sessionId);return{tasks:s,nextCursor:o,_meta:{}}}catch(s){throw new U(M.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(zs,async(n,r)=>{try{let s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new U(M.InvalidParams,`Task not found: ${n.params.taskId}`);if(Dt(s.status))throw new U(M.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(n.params.taskId);let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new U(M.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof U?s:new U(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,n,r,s,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,n),startTime:Date.now(),timeout:n,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:s})}_resetTimeout(e){let n=this._timeoutInfo.get(e);if(!n)return!1;let r=Date.now()-n.startTime;if(n.maxTotalTimeout&&r>=n.maxTotalTimeout)throw this._timeoutInfo.delete(e),U.fromError(M.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:r});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(e){let n=this._timeoutInfo.get(e);n&&(clearTimeout(n.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 n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let r=this.transport?.onerror;this._transport.onerror=o=>{r?.(o),this._onerror(o)};let s=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{s?.(o,i),hr(o)||Wd(o)?this._onresponse(o):Fi(o)?this._onrequest(o,i):Gd(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 r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(let r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();let n=U.fromError(M.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let r of e.values())r(n)}_onerror(e){this.onerror?.(e)}_onnotification(e){let n=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,n){let r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,s=this._transport,o=e.params?._meta?.[Ut]?.taskId;if(r===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(h=>this._onerror(new Error(`Failed to enqueue error response: ${h}`))):s?.send(p).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=Hd(e.params)?e.params.task:void 0,c=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 h={relatedRequestId:e.id};o&&(h.relatedTask={taskId:o}),await this.notification(p,h)},sendRequest:async(p,h,k)=>{if(i.signal.aborted)throw new U(M.ConnectionClosed,"Request was cancelled");let b={...k,relatedRequestId:e.id};o&&!b.relatedTask&&(b.relatedTask={taskId:o});let v=b.relatedTask?.taskId??o;return v&&c&&await c.updateTaskStatus(v,"input_required"),await this.request(p,h,b)},authInfo:n?.authInfo,requestId:e.id,requestInfo:n?.requestInfo,taskId:o,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,u)).then(async p=>{if(i.signal.aborted)return;let h={result:p,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 p=>{if(i.signal.aborted)return;let h={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:h,timestamp:Date.now()},s?.sessionId):await s?.send(h)}).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:n,...r}=e.params,s=Number(n),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(c){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),i(c);return}o(r)}_onresponse(e){let n=Number(e.id),r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),hr(e))r(e);else{let i=new U(e.error.code,e.error.message,e.error.data);r(i)}return}let s=this._responseHandlers.get(n);if(s===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let o=!1;if(hr(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,n))}}if(o||this._progressHandlers.delete(n),hr(e))s(e);else{let i=U.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,n,r){let{task:s}=r??{};if(!s){try{yield{type:"result",result:await this.request(e,n,r)}}catch(i){yield{type:"error",error:i instanceof U?i:new U(M.InternalError,String(i))}}return}let o;try{let i=await this.request(e,En,r);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new U(M.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:a},Dt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},n,r)}:a.status==="failed"?yield{type:"error",error:new U(M.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new U(M.InternalError,`Task ${o} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},n,r)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof U?i:new U(M.InternalError,String(i))}}}request(e,n,r){let{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i,task:a,relatedTask:c}=r??{};return new Promise((u,p)=>{let h=I=>{p(I)};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(I){h(I);return}r?.signal?.throwIfAborted();let k=this._requestMessageId++,b={...e,jsonrpc:"2.0",id:k};r?.onprogress&&(this._progressHandlers.set(k,r.onprogress),b.params={...e.params,_meta:{...e.params?._meta||{},progressToken:k}}),a&&(b.params={...b.params,task:a}),c&&(b.params={...b.params,_meta:{...b.params?._meta||{},[Ut]:c}});let v=I=>{this._responseHandlers.delete(k),this._progressHandlers.delete(k),this._cleanupTimeout(k),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:k,reason:String(I)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(ie=>this._onerror(new Error(`Failed to send cancellation: ${ie}`)));let z=I instanceof U?I:new U(M.RequestTimeout,String(I));p(z)};this._responseHandlers.set(k,I=>{if(!r?.signal?.aborted){if(I instanceof Error)return p(I);try{let z=Lt(n,I.result);z.success?u(z.data):p(z.error)}catch(z){p(z)}}}),r?.signal?.addEventListener("abort",()=>{v(r?.signal?.reason)});let T=r?.timeout??Kv,R=()=>v(U.fromError(M.RequestTimeout,"Request timed out",{timeout:T}));this._setupTimeout(k,T,r?.maxTotalTimeout,R,r?.resetTimeoutOnProgress??!1);let E=c?.taskId;if(E){let I=z=>{let ie=this._responseHandlers.get(k);ie?ie(z):this._onerror(new Error(`Response handler missing for side-channeled request ${k}`))};this._requestResolvers.set(k,I),this._enqueueTaskMessage(E,{type:"request",message:b,timestamp:Date.now()}).catch(z=>{this._cleanupTimeout(k),p(z)})}else this._transport.send(b,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(I=>{this._cleanupTimeout(k),p(I)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},Os,n)}async getTaskResult(e,n,r){return this.request({method:"tasks/result",params:e},n,r)}async listTasks(e,n){return this.request({method:"tasks/list",params:e},Ls,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},Yd,n)}async notification(e,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let r=n?.relatedTask?.taskId;if(r){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Ut]:n.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!n?.relatedRequestId&&!n?.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"};n?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Ut]:n.relatedTask}}}),this._transport?.send(a,n).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};n?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Ut]:n.relatedTask}}}),await this._transport.send(i,n)}setRequestHandler(e,n){let r=za(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(s,o)=>{let i=Ua(e,s);return Promise.resolve(n(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,n){let r=za(e);this._notificationHandlers.set(r,s=>{let o=Ua(e,s);return Promise.resolve(n(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let n=this._taskProgressTokens.get(e);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,n,r){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,n,r,s)}async _clearTaskQueue(e,n){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,n);for(let s of r)if(s.type==="request"&&Fi(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new U(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,n){let r=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e);s?.pollInterval&&(r=s.pollInterval)}catch{}return new Promise((s,o)=>{if(n.aborted){o(new U(M.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,r);n.addEventListener("abort",()=>{clearTimeout(i),o(new U(M.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,n){let r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await r.createTask(s,e.id,{method:e.method,params:e.params},n)},getTask:async s=>{let o=await r.getTask(s,n);if(!o)throw new U(M.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(s,o,i)=>{await r.storeTaskResult(s,o,i,n);let a=await r.getTask(s,n);if(a){let c=wr.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Dt(a.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>r.getTaskResult(s,n),updateTaskStatus:async(s,o,i)=>{let a=await r.getTask(s,n);if(!a)throw new U(M.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(Dt(a.status))throw new U(M.InvalidParams,`Cannot update task "${s}" from terminal status "${a.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(s,o,i,n);let c=await r.getTask(s,n);if(c){let u=wr.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Dt(c.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>r.listTasks(s,n)}}}});var Rr=L(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.regexpCode=fe.getEsmExportName=fe.getProperty=fe.safeStringify=fe.stringify=fe.strConcat=fe.addCodeArg=fe.str=fe._=fe.nil=fe._Code=fe.Name=fe.IDENTIFIER=fe._CodeOrName=void 0;var xr=class{};fe._CodeOrName=xr;fe.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var rn=class extends xr{constructor(e){if(super(),!fe.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}}};fe.Name=rn;var nt=class extends xr{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((n,r)=>`${n}${r}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((n,r)=>(r instanceof rn&&(n[r.str]=(n[r.str]||0)+1),n),{})}};fe._Code=nt;fe.nil=new nt("");function Hp(t,...e){let n=[t[0]],r=0;for(;r<e.length;)Ma(n,e[r]),n.push(t[++r]);return new nt(n)}fe._=Hp;var qa=new nt("+");function Kp(t,...e){let n=[Tr(t[0])],r=0;for(;r<e.length;)n.push(qa),Ma(n,e[r]),n.push(qa,Tr(t[++r]));return Vv(n),new nt(n)}fe.str=Kp;function Ma(t,e){e instanceof nt?t.push(...e._items):e instanceof rn?t.push(e):t.push(Jv(e))}fe.addCodeArg=Ma;function Vv(t){let e=1;for(;e<t.length-1;){if(t[e]===qa){let n=Gv(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function Gv(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof rn||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 rn))return`"${t}${e.slice(1)}`}function Wv(t,e){return e.emptyStr()?t:t.emptyStr()?e:Kp`${t}${e}`}fe.strConcat=Wv;function Jv(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Tr(Array.isArray(t)?t.join(","):t)}function Zv(t){return new nt(Tr(t))}fe.stringify=Zv;function Tr(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}fe.safeStringify=Tr;function Yv(t){return typeof t=="string"&&fe.IDENTIFIER.test(t)?new nt(`.${t}`):Hp`[${t}]`}fe.getProperty=Yv;function Qv(t){if(typeof t=="string"&&fe.IDENTIFIER.test(t))return new nt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}fe.getEsmExportName=Qv;function Xv(t){return new nt(t.toString())}fe.regexpCode=Xv});var Ha=L(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.ValueScope=Be.ValueScopeName=Be.Scope=Be.varKinds=Be.UsedValueState=void 0;var Me=Rr(),Ba=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},ro;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(ro||(Be.UsedValueState=ro={}));Be.varKinds={const:new Me.Name("const"),let:new Me.Name("let"),var:new Me.Name("var")};var so=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof Me.Name?e:this.name(e)}name(e){return new Me.Name(this._newName(e))}_newName(e){let n=this._names[e]||this._nameGroup(e);return`${e}${n.index++}`}_nameGroup(e){var n,r;if(!((r=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||r===void 0)&&r.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=so;var oo=class extends Me.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,Me._)`.${new Me.Name(n)}[${r}]`}};Be.ValueScopeName=oo;var eS=(0,Me._)`\n`,Fa=class extends so{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?eS:Me.nil}}get(){return this._scope}name(e){return new oo(e,this._newName(e))}value(e,n){var r;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let s=this.toName(e),{prefix:o}=s,i=(r=n.key)!==null&&r!==void 0?r:n.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 c=this._scope[o]||(this._scope[o]=[]),u=c.length;return c[u]=n.ref,s.setValue(n,{property:o,itemIndex:u}),s}getValue(e,n){let r=this._values[e];if(r)return r.get(n)}scopeRefs(e,n=this._values){return this._reduceValues(n,r=>{if(r.scopePath===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return(0,Me._)`${e}${r.scopePath}`})}scopeCode(e=this._values,n,r){return this._reduceValues(e,s=>{if(s.value===void 0)throw new Error(`CodeGen: name "${s}" has no value`);return s.value.code},n,r)}_reduceValues(e,n,r={},s){let o=Me.nil;for(let i in e){let a=e[i];if(!a)continue;let c=r[i]=r[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,ro.Started);let p=n(u);if(p){let h=this.opts.es5?Be.varKinds.var:Be.varKinds.const;o=(0,Me._)`${o}${h} ${u} = ${p};${this.opts._n}`}else if(p=s?.(u))o=(0,Me._)`${o}${p}${this.opts._n}`;else throw new Ba(u);c.set(u,ro.Completed)})}return o}};Be.ValueScope=Fa});var Y=L(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.or=Q.and=Q.not=Q.CodeGen=Q.operators=Q.varKinds=Q.ValueScopeName=Q.ValueScope=Q.Scope=Q.Name=Q.regexpCode=Q.stringify=Q.getProperty=Q.nil=Q.strConcat=Q.str=Q._=void 0;var le=Rr(),ut=Ha(),Mt=Rr();Object.defineProperty(Q,"_",{enumerable:!0,get:function(){return Mt._}});Object.defineProperty(Q,"str",{enumerable:!0,get:function(){return Mt.str}});Object.defineProperty(Q,"strConcat",{enumerable:!0,get:function(){return Mt.strConcat}});Object.defineProperty(Q,"nil",{enumerable:!0,get:function(){return Mt.nil}});Object.defineProperty(Q,"getProperty",{enumerable:!0,get:function(){return Mt.getProperty}});Object.defineProperty(Q,"stringify",{enumerable:!0,get:function(){return Mt.stringify}});Object.defineProperty(Q,"regexpCode",{enumerable:!0,get:function(){return Mt.regexpCode}});Object.defineProperty(Q,"Name",{enumerable:!0,get:function(){return Mt.Name}});var co=Ha();Object.defineProperty(Q,"Scope",{enumerable:!0,get:function(){return co.Scope}});Object.defineProperty(Q,"ValueScope",{enumerable:!0,get:function(){return co.ValueScope}});Object.defineProperty(Q,"ValueScopeName",{enumerable:!0,get:function(){return co.ValueScopeName}});Object.defineProperty(Q,"varKinds",{enumerable:!0,get:function(){return co.varKinds}});Q.operators={GT:new le._Code(">"),GTE:new le._Code(">="),LT:new le._Code("<"),LTE:new le._Code("<="),EQ:new le._Code("==="),NEQ:new le._Code("!=="),NOT:new le._Code("!"),OR:new le._Code("||"),AND:new le._Code("&&"),ADD:new le._Code("+")};var Tt=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},Ka=class extends Tt{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?ut.varKinds.var:this.varKind,s=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${s};`+n}optimizeNames(e,n){if(e[this.name.str])return this.rhs&&(this.rhs=Nn(this.rhs,e,n)),this}get names(){return this.rhs instanceof le._CodeOrName?this.rhs.names:{}}},io=class extends Tt{constructor(e,n,r){super(),this.lhs=e,this.rhs=n,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof le.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Nn(this.rhs,e,n),this}get names(){let e=this.lhs instanceof le.Name?{}:{...this.lhs.names};return lo(e,this.rhs)}},Va=class extends io{constructor(e,n,r,s){super(e,r,s),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Ga=class extends Tt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Wa=class extends Tt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Ja=class extends Tt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Za=class extends Tt{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,n){return this.code=Nn(this.code,e,n),this}get names(){return this.code instanceof le._CodeOrName?this.code.names:{}}},Er=class extends Tt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((n,r)=>n+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,n=e.length;for(;n--;){let r=e[n].optimizeNodes();Array.isArray(r)?e.splice(n,1,...r):r?e[n]=r:e.splice(n,1)}return e.length>0?this:void 0}optimizeNames(e,n){let{nodes:r}=this,s=r.length;for(;s--;){let o=r[s];o.optimizeNames(e,n)||(tS(e,o.names),r.splice(s,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>an(e,n.names),{})}},Rt=class extends Er{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Ya=class extends Er{},On=class extends Rt{};On.kind="else";var sn=class t extends Rt{constructor(e,n){super(n),this.condition=e}render(e){let n=`if(${this.condition})`+super.render(e);return this.else&&(n+="else "+this.else.render(e)),n}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let n=this.else;if(n){let r=n.optimizeNodes();n=this.else=Array.isArray(r)?new On(r):r}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(Vp(e),n instanceof t?[n]:n.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,n){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,n),!!(super.optimizeNames(e,n)||this.else))return this.condition=Nn(this.condition,e,n),this}get names(){let e=super.names;return lo(e,this.condition),this.else&&an(e,this.else.names),e}};sn.kind="if";var on=class extends Rt{};on.kind="for";var Qa=class extends on{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iteration=Nn(this.iteration,e,n),this}get names(){return an(super.names,this.iteration.names)}},Xa=class extends on{constructor(e,n,r,s){super(),this.varKind=e,this.name=n,this.from=r,this.to=s}render(e){let n=e.es5?ut.varKinds.var:this.varKind,{name:r,from:s,to:o}=this;return`for(${n} ${r}=${s}; ${r}<${o}; ${r}++)`+super.render(e)}get names(){let e=lo(super.names,this.from);return lo(e,this.to)}},ao=class extends on{constructor(e,n,r,s){super(),this.loop=e,this.varKind=n,this.name=r,this.iterable=s}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iterable=Nn(this.iterable,e,n),this}get names(){return an(super.names,this.iterable.names)}},Pr=class extends Rt{constructor(e,n,r){super(),this.name=e,this.args=n,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Pr.kind="func";var Ar=class extends Er{render(e){return"return "+super.render(e)}};Ar.kind="return";var el=class extends Rt{render(e){let n="try"+super.render(e);return this.catch&&(n+=this.catch.render(e)),this.finally&&(n+=this.finally.render(e)),n}optimizeNodes(){var e,n;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(e,n){var r,s;return super.optimizeNames(e,n),(r=this.catch)===null||r===void 0||r.optimizeNames(e,n),(s=this.finally)===null||s===void 0||s.optimizeNames(e,n),this}get names(){let e=super.names;return this.catch&&an(e,this.catch.names),this.finally&&an(e,this.finally.names),e}},Ir=class extends Rt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Ir.kind="catch";var Cr=class extends Rt{render(e){return"finally"+super.render(e)}};Cr.kind="finally";var tl=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
|
|
939
|
+
`:""},this._extScope=e,this._scope=new ut.Scope({parent:e}),this._nodes=[new Ya]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,n){let r=this._extScope.value(e,n);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,n){return this._extScope.getValue(e,n)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,n,r,s){let o=this._scope.toName(n);return r!==void 0&&s&&(this._constants[o.str]=r),this._leafNode(new Ka(e,o,r)),o}const(e,n,r){return this._def(ut.varKinds.const,e,n,r)}let(e,n,r){return this._def(ut.varKinds.let,e,n,r)}var(e,n,r){return this._def(ut.varKinds.var,e,n,r)}assign(e,n,r){return this._leafNode(new io(e,n,r))}add(e,n){return this._leafNode(new Va(e,Q.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==le.nil&&this._leafNode(new Za(e)),this}object(...e){let n=["{"];for(let[r,s]of e)n.length>1&&n.push(","),n.push(r),(r!==s||this.opts.es5)&&(n.push(":"),(0,le.addCodeArg)(n,s));return n.push("}"),new le._Code(n)}if(e,n,r){if(this._blockNode(new sn(e)),n&&r)this.code(n).else().code(r).endIf();else if(n)this.code(n).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new sn(e))}else(){return this._elseNode(new On)}endIf(){return this._endBlockNode(sn,On)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new Qa(e),n)}forRange(e,n,r,s,o=this.opts.es5?ut.varKinds.var:ut.varKinds.let){let i=this._scope.toName(e);return this._for(new Xa(o,i,n,r),()=>s(i))}forOf(e,n,r,s=ut.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=n instanceof le.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,le._)`${i}.length`,a=>{this.var(o,(0,le._)`${i}[${a}]`),r(o)})}return this._for(new ao("of",s,o,n),()=>r(o))}forIn(e,n,r,s=this.opts.es5?ut.varKinds.var:ut.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,le._)`Object.keys(${n})`,r);let o=this._scope.toName(e);return this._for(new ao("in",s,o,n),()=>r(o))}endFor(){return this._endBlockNode(on)}label(e){return this._leafNode(new Ga(e))}break(e){return this._leafNode(new Wa(e))}return(e){let n=new Ar;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Ar)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new el;if(this._blockNode(s),this.code(e),n){let o=this.name("e");this._currNode=s.catch=new Ir(o),n(o)}return r&&(this._currNode=s.finally=new Cr,this.code(r)),this._endBlockNode(Ir,Cr)}throw(e){return this._leafNode(new Ja(e))}block(e,n){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(n),this}endBlock(e){let n=this._blockStarts.pop();if(n===void 0)throw new Error("CodeGen: not in self-balancing block");let r=this._nodes.length-n;if(r<0||e!==void 0&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=n,this}func(e,n=le.nil,r,s){return this._blockNode(new Pr(e,n,r)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(Pr)}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,n){let r=this._currNode;if(r instanceof e||n&&r instanceof n)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${n?`${e.kind}/${n.kind}`:e.kind}"`)}_elseNode(e){let n=this._currNode;if(!(n instanceof sn))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let n=this._nodes;n[n.length-1]=e}};Q.CodeGen=tl;function an(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function lo(t,e){return e instanceof le._CodeOrName?an(t,e.names):t}function Nn(t,e,n){if(t instanceof le.Name)return r(t);if(!s(t))return t;return new le._Code(t._items.reduce((o,i)=>(i instanceof le.Name&&(i=r(i)),i instanceof le._Code?o.push(...i._items):o.push(i),o),[]));function r(o){let i=n[o.str];return i===void 0||e[o.str]!==1?o:(delete e[o.str],i)}function s(o){return o instanceof le._Code&&o._items.some(i=>i instanceof le.Name&&e[i.str]===1&&n[i.str]!==void 0)}}function tS(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function Vp(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,le._)`!${nl(t)}`}Q.not=Vp;var nS=Gp(Q.operators.AND);function rS(...t){return t.reduce(nS)}Q.and=rS;var sS=Gp(Q.operators.OR);function oS(...t){return t.reduce(sS)}Q.or=oS;function Gp(t){return(e,n)=>e===le.nil?n:n===le.nil?e:(0,le._)`${nl(e)} ${t} ${nl(n)}`}function nl(t){return t instanceof le.Name?t:(0,le._)`(${t})`}});var ue=L(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.checkStrictMode=te.getErrorPath=te.Type=te.useFunc=te.setEvaluated=te.evaluatedPropsToName=te.mergeEvaluated=te.eachItem=te.unescapeJsonPointer=te.escapeJsonPointer=te.escapeFragment=te.unescapeFragment=te.schemaRefOrVal=te.schemaHasRulesButRef=te.schemaHasRules=te.checkUnknownRules=te.alwaysValidSchema=te.toHash=void 0;var me=Y(),iS=Rr();function aS(t){let e={};for(let n of t)e[n]=!0;return e}te.toHash=aS;function lS(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Zp(t,e),!Yp(e,t.self.RULES.all))}te.alwaysValidSchema=lS;function Zp(t,e=t.schema){let{opts:n,self:r}=t;if(!n.strictSchema||typeof e=="boolean")return;let s=r.RULES.keywords;for(let o in e)s[o]||ef(t,`unknown keyword: "${o}"`)}te.checkUnknownRules=Zp;function Yp(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}te.schemaHasRules=Yp;function cS(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}te.schemaHasRulesButRef=cS;function uS({topSchemaRef:t,schemaPath:e},n,r,s){if(!s){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,me._)`${n}`}return(0,me._)`${t}${e}${(0,me.getProperty)(r)}`}te.schemaRefOrVal=uS;function dS(t){return Qp(decodeURIComponent(t))}te.unescapeFragment=dS;function pS(t){return encodeURIComponent(sl(t))}te.escapeFragment=pS;function sl(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}te.escapeJsonPointer=sl;function Qp(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}te.unescapeJsonPointer=Qp;function fS(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}te.eachItem=fS;function Wp({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(s,o,i,a)=>{let c=i===void 0?o:i instanceof me.Name?(o instanceof me.Name?t(s,o,i):e(s,o,i),i):o instanceof me.Name?(e(s,i,o),o):n(o,i);return a===me.Name&&!(c instanceof me.Name)?r(s,c):c}}te.mergeEvaluated={props:Wp({mergeNames:(t,e,n)=>t.if((0,me._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,me._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,me._)`${n} || {}`).code((0,me._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,me._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,me._)`${n} || {}`),ol(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Xp}),items:Wp({mergeNames:(t,e,n)=>t.if((0,me._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,me._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,me._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,me._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Xp(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,me._)`{}`);return e!==void 0&&ol(t,n,e),n}te.evaluatedPropsToName=Xp;function ol(t,e,n){Object.keys(n).forEach(r=>t.assign((0,me._)`${e}${(0,me.getProperty)(r)}`,!0))}te.setEvaluated=ol;var Jp={};function hS(t,e){return t.scopeValue("func",{ref:e,code:Jp[e.code]||(Jp[e.code]=new iS._Code(e.code))})}te.useFunc=hS;var rl;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(rl||(te.Type=rl={}));function mS(t,e,n){if(t instanceof me.Name){let r=e===rl.Num;return n?r?(0,me._)`"[" + ${t} + "]"`:(0,me._)`"['" + ${t} + "']"`:r?(0,me._)`"/" + ${t}`:(0,me._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,me.getProperty)(t).toString():"/"+sl(t)}te.getErrorPath=mS;function ef(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}te.checkStrictMode=ef});var Et=L(il=>{"use strict";Object.defineProperty(il,"__esModule",{value:!0});var Pe=Y(),gS={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")};il.default=gS});var Or=L(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 de=Y(),uo=ue(),Le=Et();Ae.keywordError={message:({keyword:t})=>(0,de.str)`must pass "${t}" keyword validation`};Ae.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,de.str)`"${t}" keyword must be ${e} ($data)`:(0,de.str)`"${t}" keyword is invalid ($data)`};function yS(t,e=Ae.keywordError,n,r){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,c=rf(t,e,n);r??(i||a)?tf(o,c):nf(s,(0,de._)`[${c}]`)}Ae.reportError=yS;function bS(t,e=Ae.keywordError,n){let{it:r}=t,{gen:s,compositeRule:o,allErrors:i}=r,a=rf(t,e,n);tf(s,a),o||i||nf(r,Le.default.vErrors)}Ae.reportExtraError=bS;function wS(t,e){t.assign(Le.default.errors,e),t.if((0,de._)`${Le.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,de._)`${Le.default.vErrors}.length`,e),()=>t.assign(Le.default.vErrors,null)))}Ae.resetErrorsCount=wS;function vS({gen:t,keyword:e,schemaValue:n,data:r,errsCount:s,it:o}){if(s===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",s,Le.default.errors,a=>{t.const(i,(0,de._)`${Le.default.vErrors}[${a}]`),t.if((0,de._)`${i}.instancePath === undefined`,()=>t.assign((0,de._)`${i}.instancePath`,(0,de.strConcat)(Le.default.instancePath,o.errorPath))),t.assign((0,de._)`${i}.schemaPath`,(0,de.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,de._)`${i}.schema`,n),t.assign((0,de._)`${i}.data`,r))})}Ae.extendErrors=vS;function tf(t,e){let n=t.const("err",e);t.if((0,de._)`${Le.default.vErrors} === null`,()=>t.assign(Le.default.vErrors,(0,de._)`[${n}]`),(0,de._)`${Le.default.vErrors}.push(${n})`),t.code((0,de._)`${Le.default.errors}++`)}function nf(t,e){let{gen:n,validateName:r,schemaEnv:s}=t;s.$async?n.throw((0,de._)`new ${t.ValidationError}(${e})`):(n.assign((0,de._)`${r}.errors`,e),n.return(!1))}var ln={keyword:new de.Name("keyword"),schemaPath:new de.Name("schemaPath"),params:new de.Name("params"),propertyName:new de.Name("propertyName"),message:new de.Name("message"),schema:new de.Name("schema"),parentSchema:new de.Name("parentSchema")};function rf(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,de._)`{}`:SS(t,e,n)}function SS(t,e,n={}){let{gen:r,it:s}=t,o=[kS(s,n),_S(t,n)];return $S(t,e,o),r.object(...o)}function kS({errorPath:t},{instancePath:e}){let n=e?(0,de.str)`${t}${(0,uo.getErrorPath)(e,uo.Type.Str)}`:t;return[Le.default.instancePath,(0,de.strConcat)(Le.default.instancePath,n)]}function _S({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let s=r?e:(0,de.str)`${e}/${t}`;return n&&(s=(0,de.str)`${s}${(0,uo.getErrorPath)(n,uo.Type.Str)}`),[ln.schemaPath,s]}function $S(t,{params:e,message:n},r){let{keyword:s,data:o,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:p,schemaPath:h}=a;r.push([ln.keyword,s],[ln.params,typeof e=="function"?e(t):e||(0,de._)`{}`]),c.messages&&r.push([ln.message,typeof n=="function"?n(t):n]),c.verbose&&r.push([ln.schema,i],[ln.parentSchema,(0,de._)`${p}${h}`],[Le.default.data,o]),u&&r.push([ln.propertyName,u])}});var of=L(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.boolOrEmptySchema=jn.topBoolOrEmptySchema=void 0;var xS=Or(),TS=Y(),RS=Et(),ES={message:"boolean schema is false"};function PS(t){let{gen:e,schema:n,validateName:r}=t;n===!1?sf(t,!1):typeof n=="object"&&n.$async===!0?e.return(RS.default.data):(e.assign((0,TS._)`${r}.errors`,null),e.return(!0))}jn.topBoolOrEmptySchema=PS;function AS(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),sf(t)):n.var(e,!0)}jn.boolOrEmptySchema=AS;function sf(t,e){let{gen:n,data:r}=t,s={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,xS.reportError)(s,ES,void 0,e)}});var al=L(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.getRules=Ln.isJSONType=void 0;var IS=["string","number","integer","boolean","null","object","array"],CS=new Set(IS);function OS(t){return typeof t=="string"&&CS.has(t)}Ln.isJSONType=OS;function NS(){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:{}}}Ln.getRules=NS});var ll=L(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.shouldUseRule=Bt.shouldUseGroup=Bt.schemaHasRulesForType=void 0;function jS({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&af(t,r)}Bt.schemaHasRulesForType=jS;function af(t,e){return e.rules.some(n=>lf(t,n))}Bt.shouldUseGroup=af;function lf(t,e){var n;return t[e.keyword]!==void 0||((n=e.definition.implements)===null||n===void 0?void 0:n.some(r=>t[r]!==void 0))}Bt.shouldUseRule=lf});var Nr=L(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 LS=al(),zS=ll(),US=Or(),J=Y(),cf=ue(),zn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(zn||(Ie.DataType=zn={}));function DS(t){let e=uf(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=DS;function uf(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(LS.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ie.getJSONTypes=uf;function qS(t,e){let{gen:n,data:r,opts:s}=t,o=MS(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,zS.schemaHasRulesForType)(t,e[0]));if(i){let a=ul(e,r,s.strictNumbers,zn.Wrong);n.if(a,()=>{o.length?BS(t,e,o):dl(t)})}return i}Ie.coerceAndCheckDataType=qS;var df=new Set(["string","number","integer","boolean","null"]);function MS(t,e){return e?t.filter(n=>df.has(n)||e==="array"&&n==="array"):[]}function BS(t,e,n){let{gen:r,data:s,opts:o}=t,i=r.let("dataType",(0,J._)`typeof ${s}`),a=r.let("coerced",(0,J._)`undefined`);o.coerceTypes==="array"&&r.if((0,J._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>r.assign(s,(0,J._)`${s}[0]`).assign(i,(0,J._)`typeof ${s}`).if(ul(e,s,o.strictNumbers),()=>r.assign(a,s))),r.if((0,J._)`${a} !== undefined`);for(let u of n)(df.has(u)||u==="array"&&o.coerceTypes==="array")&&c(u);r.else(),dl(t),r.endIf(),r.if((0,J._)`${a} !== undefined`,()=>{r.assign(s,a),FS(t,a)});function c(u){switch(u){case"string":r.elseIf((0,J._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,J._)`"" + ${s}`).elseIf((0,J._)`${s} === null`).assign(a,(0,J._)`""`);return;case"number":r.elseIf((0,J._)`${i} == "boolean" || ${s} === null
|
|
940
|
+
|| (${i} == "string" && ${s} && ${s} == +${s})`).assign(a,(0,J._)`+${s}`);return;case"integer":r.elseIf((0,J._)`${i} === "boolean" || ${s} === null
|
|
941
|
+
|| (${i} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(a,(0,J._)`+${s}`);return;case"boolean":r.elseIf((0,J._)`${s} === "false" || ${s} === 0 || ${s} === null`).assign(a,!1).elseIf((0,J._)`${s} === "true" || ${s} === 1`).assign(a,!0);return;case"null":r.elseIf((0,J._)`${s} === "" || ${s} === 0 || ${s} === false`),r.assign(a,null);return;case"array":r.elseIf((0,J._)`${i} === "string" || ${i} === "number"
|
|
942
|
+
|| ${i} === "boolean" || ${s} === null`).assign(a,(0,J._)`[${s}]`)}}}function FS({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,J._)`${e} !== undefined`,()=>t.assign((0,J._)`${e}[${n}]`,r))}function cl(t,e,n,r=zn.Correct){let s=r===zn.Correct?J.operators.EQ:J.operators.NEQ,o;switch(t){case"null":return(0,J._)`${e} ${s} null`;case"array":o=(0,J._)`Array.isArray(${e})`;break;case"object":o=(0,J._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,J._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,J._)`typeof ${e} ${s} ${t}`}return r===zn.Correct?o:(0,J.not)(o);function i(a=J.nil){return(0,J.and)((0,J._)`typeof ${e} == "number"`,a,n?(0,J._)`isFinite(${e})`:J.nil)}}Ie.checkDataType=cl;function ul(t,e,n,r){if(t.length===1)return cl(t[0],e,n,r);let s,o=(0,cf.toHash)(t);if(o.array&&o.object){let i=(0,J._)`typeof ${e} != "object"`;s=o.null?i:(0,J._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=J.nil;o.number&&delete o.integer;for(let i in o)s=(0,J.and)(s,cl(i,e,n,r));return s}Ie.checkDataTypes=ul;var HS={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,J._)`{type: ${t}}`:(0,J._)`{type: ${e}}`};function dl(t){let e=KS(t);(0,US.reportError)(e,HS)}Ie.reportTypeError=dl;function KS(t){let{gen:e,data:n,schema:r}=t,s=(0,cf.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:s,schemaValue:s,parentSchema:r,params:{},it:t}}});var ff=L(po=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});po.assignDefaults=void 0;var Un=Y(),VS=ue();function GS(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let s in n)pf(t,s,n[s].default);else e==="array"&&Array.isArray(r)&&r.forEach((s,o)=>pf(t,o,s.default))}po.assignDefaults=GS;function pf(t,e,n){let{gen:r,compositeRule:s,data:o,opts:i}=t;if(n===void 0)return;let a=(0,Un._)`${o}${(0,Un.getProperty)(e)}`;if(s){(0,VS.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Un._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Un._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,Un._)`${a} = ${(0,Un.stringify)(n)}`)}});var rt=L(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.validateUnion=he.validateArray=he.usePattern=he.callValidateCode=he.schemaProperties=he.allSchemaProperties=he.noPropertyInData=he.propertyInData=he.isOwnProperty=he.hasPropFunc=he.reportMissingProp=he.checkMissingProp=he.checkReportMissingProp=void 0;var ge=Y(),pl=ue(),Ft=Et(),WS=ue();function JS(t,e){let{gen:n,data:r,it:s}=t;n.if(hl(n,r,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ge._)`${e}`},!0),t.error()})}he.checkReportMissingProp=JS;function ZS({gen:t,data:e,it:{opts:n}},r,s){return(0,ge.or)(...r.map(o=>(0,ge.and)(hl(t,e,o,n.ownProperties),(0,ge._)`${s} = ${o}`)))}he.checkMissingProp=ZS;function YS(t,e){t.setParams({missingProperty:e},!0),t.error()}he.reportMissingProp=YS;function hf(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ge._)`Object.prototype.hasOwnProperty`})}he.hasPropFunc=hf;function fl(t,e,n){return(0,ge._)`${hf(t)}.call(${e}, ${n})`}he.isOwnProperty=fl;function QS(t,e,n,r){let s=(0,ge._)`${e}${(0,ge.getProperty)(n)} !== undefined`;return r?(0,ge._)`${s} && ${fl(t,e,n)}`:s}he.propertyInData=QS;function hl(t,e,n,r){let s=(0,ge._)`${e}${(0,ge.getProperty)(n)} === undefined`;return r?(0,ge.or)(s,(0,ge.not)(fl(t,e,n))):s}he.noPropertyInData=hl;function mf(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}he.allSchemaProperties=mf;function XS(t,e){return mf(e).filter(n=>!(0,pl.alwaysValidSchema)(t,e[n]))}he.schemaProperties=XS;function ek({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:s,errorPath:o},it:i},a,c,u){let p=u?(0,ge._)`${t}, ${e}, ${r}${s}`:e,h=[[Ft.default.instancePath,(0,ge.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 k=(0,ge._)`${p}, ${n.object(...h)}`;return c!==ge.nil?(0,ge._)`${a}.call(${c}, ${k})`:(0,ge._)`${a}(${k})`}he.callValidateCode=ek;var tk=(0,ge._)`new RegExp`;function nk({gen:t,it:{opts:e}},n){let r=e.unicodeRegExp?"u":"",{regExp:s}=e.code,o=s(n,r);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,ge._)`${s.code==="new RegExp"?tk:(0,WS.useFunc)(t,s)}(${n}, ${r})`})}he.usePattern=nk;function rk(t){let{gen:e,data:n,keyword:r,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 c=e.const("len",(0,ge._)`${n}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:r,dataProp:u,dataPropType:pl.Type.Num},o),e.if((0,ge.not)(o),a)})}}he.validateArray=rk;function sk(t){let{gen:e,schema:n,keyword:r,it:s}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(c=>(0,pl.alwaysValidSchema)(s,c))&&!s.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>n.forEach((c,u)=>{let p=t.subschema({keyword:r,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,ge._)`${i} || ${a}`),t.mergeValidEvaluated(p,a)||e.if((0,ge.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}he.validateUnion=sk});var bf=L(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.validateKeywordUsage=bt.validSchemaType=bt.funcKeywordCode=bt.macroKeywordCode=void 0;var ze=Y(),cn=Et(),ok=rt(),ik=Or();function ak(t,e){let{gen:n,keyword:r,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),c=yf(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=n.name("valid");t.subschema({schema:a,schemaPath:ze.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}bt.macroKeywordCode=ak;function lk(t,e){var n;let{gen:r,keyword:s,schema:o,parentSchema:i,$data:a,it:c}=t;uk(c,e);let u=!a&&e.compile?e.compile.call(c.self,o,i,c):e.validate,p=yf(r,s,u),h=r.let("valid");t.block$data(h,k),t.ok((n=e.valid)!==null&&n!==void 0?n:h);function k(){if(e.errors===!1)T(),e.modifying&&gf(t),R(()=>t.error());else{let E=e.async?b():v();e.modifying&&gf(t),R(()=>ck(t,E))}}function b(){let E=r.let("ruleErrs",null);return r.try(()=>T((0,ze._)`await `),I=>r.assign(h,!1).if((0,ze._)`${I} instanceof ${c.ValidationError}`,()=>r.assign(E,(0,ze._)`${I}.errors`),()=>r.throw(I))),E}function v(){let E=(0,ze._)`${p}.errors`;return r.assign(E,null),T(ze.nil),E}function T(E=e.async?(0,ze._)`await `:ze.nil){let I=c.opts.passContext?cn.default.this:cn.default.self,z=!("compile"in e&&!a||e.schema===!1);r.assign(h,(0,ze._)`${E}${(0,ok.callValidateCode)(t,p,I,z)}`,e.modifying)}function R(E){var I;r.if((0,ze.not)((I=e.valid)!==null&&I!==void 0?I:h),E)}}bt.funcKeywordCode=lk;function gf(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,ze._)`${r.parentData}[${r.parentDataProperty}]`))}function ck(t,e){let{gen:n}=t;n.if((0,ze._)`Array.isArray(${e})`,()=>{n.assign(cn.default.vErrors,(0,ze._)`${cn.default.vErrors} === null ? ${e} : ${cn.default.vErrors}.concat(${e})`).assign(cn.default.errors,(0,ze._)`${cn.default.vErrors}.length`),(0,ik.extendErrors)(t)},()=>t.error())}function uk({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function yf(t,e,n){if(n===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,ze.stringify)(n)})}function dk(t,e,n=!1){return!e.length||e.some(r=>r==="array"?Array.isArray(t):r==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==r||n&&typeof t>"u")}bt.validSchemaType=dk;function pk({schema:t,opts:e,self:n,errSchemaPath:r},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 c=`keyword "${o}" value is invalid at path "${r}": `+n.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")n.logger.error(c);else throw new Error(c)}}bt.validateKeywordUsage=pk});var vf=L(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.extendSubschemaMode=Ht.extendSubschemaData=Ht.getSubschema=void 0;var wt=Y(),wf=ue();function fk(t,{keyword:e,schemaProp:n,schema:r,schemaPath:s,errSchemaPath:o,topSchemaRef:i}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return n===void 0?{schema:a,schemaPath:(0,wt._)`${t.schemaPath}${(0,wt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,wt._)`${t.schemaPath}${(0,wt.getProperty)(e)}${(0,wt.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,wf.escapeFragment)(n)}`}}if(r!==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:r,schemaPath:s,topSchemaRef:i,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}Ht.getSubschema=fk;function hk(t,e,{dataProp:n,dataPropType:r,data:s,dataTypes:o,propertyName:i}){if(s!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(n!==void 0){let{errorPath:u,dataPathArr:p,opts:h}=e,k=a.let("data",(0,wt._)`${e.data}${(0,wt.getProperty)(n)}`,!0);c(k),t.errorPath=(0,wt.str)`${u}${(0,wf.getErrorPath)(n,r,h.jsPropertySyntax)}`,t.parentDataProperty=(0,wt._)`${n}`,t.dataPathArr=[...p,t.parentDataProperty]}if(s!==void 0){let u=s instanceof wt.Name?s:a.let("data",s,!0);c(u),i!==void 0&&(t.propertyName=i)}o&&(t.dataTypes=o);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}Ht.extendSubschemaData=hk;function mk(t,{jtdDiscriminator:e,jtdMetadata:n,compositeRule:r,createErrors:s,allErrors:o}){r!==void 0&&(t.compositeRule=r),s!==void 0&&(t.createErrors=s),o!==void 0&&(t.allErrors=o),t.jtdDiscriminator=e,t.jtdMetadata=n}Ht.extendSubschemaMode=mk});var ml=L((_C,Sf)=>{"use strict";Sf.exports=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var r,s,o;if(Array.isArray(e)){if(r=e.length,r!=n.length)return!1;for(s=r;s--!==0;)if(!t(e[s],n[s]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(o=Object.keys(e),r=o.length,r!==Object.keys(n).length)return!1;for(s=r;s--!==0;)if(!Object.prototype.hasOwnProperty.call(n,o[s]))return!1;for(s=r;s--!==0;){var i=o[s];if(!t(e[i],n[i]))return!1}return!0}return e!==e&&n!==n}});var _f=L(($C,kf)=>{"use strict";var Kt=kf.exports=function(t,e,n){typeof e=="function"&&(n=e,e={}),n=e.cb||n;var r=typeof n=="function"?n:n.pre||function(){},s=n.post||function(){};fo(e,r,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 fo(t,e,n,r,s,o,i,a,c,u){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,s,o,i,a,c,u);for(var p in r){var h=r[p];if(Array.isArray(h)){if(p in Kt.arrayKeywords)for(var k=0;k<h.length;k++)fo(t,e,n,h[k],s+"/"+p+"/"+k,o,s,p,r,k)}else if(p in Kt.propsKeywords){if(h&&typeof h=="object")for(var b in h)fo(t,e,n,h[b],s+"/"+p+"/"+gk(b),o,s,p,r,b)}else(p in Kt.keywords||t.allKeys&&!(p in Kt.skipKeywords))&&fo(t,e,n,h,s+"/"+p,o,s,p,r)}n(r,s,o,i,a,c,u)}}function gk(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var jr=L(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.getSchemaRefs=Fe.resolveUrl=Fe.normalizeId=Fe._getFullPath=Fe.getFullPath=Fe.inlineRef=void 0;var yk=ue(),bk=ml(),wk=_f(),vk=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Sk(t,e=!0){return typeof t=="boolean"?!0:e===!0?!gl(t):e?$f(t)<=e:!1}Fe.inlineRef=Sk;var kk=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function gl(t){for(let e in t){if(kk.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(gl)||typeof n=="object"&&gl(n))return!0}return!1}function $f(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!vk.has(n)&&(typeof t[n]=="object"&&(0,yk.eachItem)(t[n],r=>e+=$f(r)),e===1/0))return 1/0}return e}function xf(t,e="",n){n!==!1&&(e=Dn(e));let r=t.parse(e);return Tf(t,r)}Fe.getFullPath=xf;function Tf(t,e){return t.serialize(e).split("#")[0]+"#"}Fe._getFullPath=Tf;var _k=/#\/?$/;function Dn(t){return t?t.replace(_k,""):""}Fe.normalizeId=Dn;function $k(t,e,n){return n=Dn(n),t.resolve(e,n)}Fe.resolveUrl=$k;var xk=/^[a-z_][-a-z0-9._]*$/i;function Tk(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,s=Dn(t[n]||e),o={"":s},i=xf(r,s,!1),a={},c=new Set;return wk(t,{allKeys:!0},(h,k,b,v)=>{if(v===void 0)return;let T=i+k,R=o[v];typeof h[n]=="string"&&(R=E.call(this,h[n])),I.call(this,h.$anchor),I.call(this,h.$dynamicAnchor),o[k]=R;function E(z){let ie=this.opts.uriResolver.resolve;if(z=Dn(R?ie(R,z):z),c.has(z))throw p(z);c.add(z);let H=this.refs[z];return typeof H=="string"&&(H=this.refs[H]),typeof H=="object"?u(h,H.schema,z):z!==Dn(T)&&(z[0]==="#"?(u(h,a[z],z),a[z]=h):this.refs[z]=T),z}function I(z){if(typeof z=="string"){if(!xk.test(z))throw new Error(`invalid anchor "${z}"`);E.call(this,`#${z}`)}}}),a;function u(h,k,b){if(k!==void 0&&!bk(h,k))throw p(b)}function p(h){return new Error(`reference "${h}" resolves to more than one schema`)}}Fe.getSchemaRefs=Tk});var Ur=L(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.getData=Vt.KeywordCxt=Vt.validateFunctionCode=void 0;var If=of(),Rf=Nr(),bl=ll(),ho=Nr(),Rk=ff(),zr=bf(),yl=vf(),D=Y(),K=Et(),Ek=jr(),Pt=ue(),Lr=Or();function Pk(t){if(Nf(t)&&(jf(t),Of(t))){Ck(t);return}Cf(t,()=>(0,If.topBoolOrEmptySchema)(t))}Vt.validateFunctionCode=Pk;function Cf({gen:t,validateName:e,schema:n,schemaEnv:r,opts:s},o){s.code.es5?t.func(e,(0,D._)`${K.default.data}, ${K.default.valCxt}`,r.$async,()=>{t.code((0,D._)`"use strict"; ${Ef(n,s)}`),Ik(t,s),t.code(o)}):t.func(e,(0,D._)`${K.default.data}, ${Ak(s)}`,r.$async,()=>t.code(Ef(n,s)).code(o))}function Ak(t){return(0,D._)`{${K.default.instancePath}="", ${K.default.parentData}, ${K.default.parentDataProperty}, ${K.default.rootData}=${K.default.data}${t.dynamicRef?(0,D._)`, ${K.default.dynamicAnchors}={}`:D.nil}}={}`}function Ik(t,e){t.if(K.default.valCxt,()=>{t.var(K.default.instancePath,(0,D._)`${K.default.valCxt}.${K.default.instancePath}`),t.var(K.default.parentData,(0,D._)`${K.default.valCxt}.${K.default.parentData}`),t.var(K.default.parentDataProperty,(0,D._)`${K.default.valCxt}.${K.default.parentDataProperty}`),t.var(K.default.rootData,(0,D._)`${K.default.valCxt}.${K.default.rootData}`),e.dynamicRef&&t.var(K.default.dynamicAnchors,(0,D._)`${K.default.valCxt}.${K.default.dynamicAnchors}`)},()=>{t.var(K.default.instancePath,(0,D._)`""`),t.var(K.default.parentData,(0,D._)`undefined`),t.var(K.default.parentDataProperty,(0,D._)`undefined`),t.var(K.default.rootData,K.default.data),e.dynamicRef&&t.var(K.default.dynamicAnchors,(0,D._)`{}`)})}function Ck(t){let{schema:e,opts:n,gen:r}=t;Cf(t,()=>{n.$comment&&e.$comment&&zf(t),zk(t),r.let(K.default.vErrors,null),r.let(K.default.errors,0),n.unevaluated&&Ok(t),Lf(t),qk(t)})}function Ok(t){let{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,D._)`${n}.evaluated`),e.if((0,D._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,D._)`${t.evaluated}.props`,(0,D._)`undefined`)),e.if((0,D._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,D._)`${t.evaluated}.items`,(0,D._)`undefined`))}function Ef(t,e){let n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,D._)`/*# sourceURL=${n} */`:D.nil}function Nk(t,e){if(Nf(t)&&(jf(t),Of(t))){jk(t,e);return}(0,If.boolOrEmptySchema)(t,e)}function Of({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let n in t)if(e.RULES.all[n])return!0;return!1}function Nf(t){return typeof t.schema!="boolean"}function jk(t,e){let{schema:n,gen:r,opts:s}=t;s.$comment&&n.$comment&&zf(t),Uk(t),Dk(t);let o=r.const("_errs",K.default.errors);Lf(t,o),r.var(e,(0,D._)`${o} === ${K.default.errors}`)}function jf(t){(0,Pt.checkUnknownRules)(t),Lk(t)}function Lf(t,e){if(t.opts.jtd)return Pf(t,[],!1,e);let n=(0,Rf.getSchemaTypes)(t.schema),r=(0,Rf.coerceAndCheckDataType)(t,n);Pf(t,n,!r,e)}function Lk(t){let{schema:e,errSchemaPath:n,opts:r,self:s}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,Pt.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function zk(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,Pt.checkStrictMode)(t,"default is ignored in the schema root")}function Uk(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,Ek.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Dk(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function zf({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:s}){let o=n.$comment;if(s.$comment===!0)t.code((0,D._)`${K.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,D.str)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,D._)`${K.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function qk(t){let{gen:e,schemaEnv:n,validateName:r,ValidationError:s,opts:o}=t;n.$async?e.if((0,D._)`${K.default.errors} === 0`,()=>e.return(K.default.data),()=>e.throw((0,D._)`new ${s}(${K.default.vErrors})`)):(e.assign((0,D._)`${r}.errors`,K.default.vErrors),o.unevaluated&&Mk(t),e.return((0,D._)`${K.default.errors} === 0`))}function Mk({gen:t,evaluated:e,props:n,items:r}){n instanceof D.Name&&t.assign((0,D._)`${e}.props`,n),r instanceof D.Name&&t.assign((0,D._)`${e}.items`,r)}function Pf(t,e,n,r){let{gen:s,schema:o,data:i,allErrors:a,opts:c,self:u}=t,{RULES:p}=u;if(o.$ref&&(c.ignoreKeywordsWithRef||!(0,Pt.schemaHasRulesButRef)(o,p))){s.block(()=>Df(t,"$ref",p.all.$ref.definition));return}c.jtd||Bk(t,e),s.block(()=>{for(let k of p.rules)h(k);h(p.post)});function h(k){(0,bl.shouldUseGroup)(o,k)&&(k.type?(s.if((0,ho.checkDataType)(k.type,i,c.strictNumbers)),Af(t,k),e.length===1&&e[0]===k.type&&n&&(s.else(),(0,ho.reportTypeError)(t)),s.endIf()):Af(t,k),a||s.if((0,D._)`${K.default.errors} === ${r||0}`))}}function Af(t,e){let{gen:n,schema:r,opts:{useDefaults:s}}=t;s&&(0,Rk.assignDefaults)(t,e.type),n.block(()=>{for(let o of e.rules)(0,bl.shouldUseRule)(r,o)&&Df(t,o.keyword,o.definition,e.type)})}function Bk(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Fk(t,e),t.opts.allowUnionTypes||Hk(t,e),Kk(t,t.dataTypes))}function Fk(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{Uf(t.dataTypes,n)||wl(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),Gk(t,e)}}function Hk(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&wl(t,"use allowUnionTypes to allow union type keyword")}function Kk(t,e){let n=t.self.RULES.all;for(let r in n){let s=n[r];if(typeof s=="object"&&(0,bl.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>Vk(e,i))&&wl(t,`missing type "${o.join(",")}" for keyword "${r}"`)}}}function Vk(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Uf(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Gk(t,e){let n=[];for(let r of t.dataTypes)Uf(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function wl(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,Pt.checkStrictMode)(t,e,t.opts.strictTypes)}var mo=class{constructor(e,n,r){if((0,zr.validateKeywordUsage)(e,n,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=n.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Pt.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",qf(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,zr.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=e.gen.const("_errs",K.default.errors))}result(e,n,r){this.failResult((0,D.not)(e),n,r)}failResult(e,n,r){this.gen.if(e),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,n){this.failResult((0,D.not)(e),void 0,n)}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:n}=this;this.fail((0,D._)`${n} !== undefined && (${(0,D.or)(this.invalid$data(),e)})`)}error(e,n,r){if(n){this.setParams(n),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,n){(e?Lr.reportExtraError:Lr.reportError)(this,this.def.error,n)}$dataError(){(0,Lr.reportError)(this,this.def.$dataError||Lr.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Lr.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,n){n?Object.assign(this.params,e):this.params=e}block$data(e,n,r=D.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=D.nil,n=D.nil){if(!this.$data)return;let{gen:r,schemaCode:s,schemaType:o,def:i}=this;r.if((0,D.or)((0,D._)`${s} === undefined`,n)),e!==D.nil&&r.assign(e,!0),(o.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==D.nil&&r.assign(e,!1)),r.else()}invalid$data(){let{gen:e,schemaCode:n,schemaType:r,def:s,it:o}=this;return(0,D.or)(i(),a());function i(){if(r.length){if(!(n instanceof D.Name))throw new Error("ajv implementation error");let c=Array.isArray(r)?r:[r];return(0,D._)`${(0,ho.checkDataTypes)(c,n,o.opts.strictNumbers,ho.DataType.Wrong)}`}return D.nil}function a(){if(s.validateSchema){let c=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,D._)`!${c}(${n})`}return D.nil}}subschema(e,n){let r=(0,yl.getSubschema)(this.it,e);(0,yl.extendSubschemaData)(r,this.it,e),(0,yl.extendSubschemaMode)(r,e);let s={...this.it,...r,items:void 0,props:void 0};return Nk(s,n),s}mergeEvaluated(e,n){let{it:r,gen:s}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=Pt.mergeEvaluated.props(s,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=Pt.mergeEvaluated.items(s,e.items,r.items,n)))}mergeValidEvaluated(e,n){let{it:r,gen:s}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return s.if(n,()=>this.mergeEvaluated(e,D.Name)),!0}};Vt.KeywordCxt=mo;function Df(t,e,n,r){let s=new mo(t,n,e);"code"in n?n.code(s,r):s.$data&&n.validate?(0,zr.funcKeywordCode)(s,n):"macro"in n?(0,zr.macroKeywordCode)(s,n):(n.compile||n.validate)&&(0,zr.funcKeywordCode)(s,n)}var Wk=/^\/(?:[^~]|~0|~1)*$/,Jk=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function qf(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let s,o;if(t==="")return K.default.rootData;if(t[0]==="/"){if(!Wk.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=K.default.rootData}else{let u=Jk.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(c("property/index",p));return r[e-p]}if(p>e)throw new Error(c("data",p));if(o=n[e-p],!s)return o}let i=o,a=s.split("/");for(let u of a)u&&(o=(0,D._)`${o}${(0,D.getProperty)((0,Pt.unescapeJsonPointer)(u))}`,i=(0,D._)`${i} && ${o}`);return i;function c(u,p){return`Cannot access ${u} ${p} levels up, current level is ${e}`}}Vt.getData=qf});var go=L(Sl=>{"use strict";Object.defineProperty(Sl,"__esModule",{value:!0});var vl=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Sl.default=vl});var Dr=L($l=>{"use strict";Object.defineProperty($l,"__esModule",{value:!0});var kl=jr(),_l=class extends Error{constructor(e,n,r,s){super(s||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,kl.resolveUrl)(e,n,r),this.missingSchema=(0,kl.normalizeId)((0,kl.getFullPath)(e,this.missingRef))}};$l.default=_l});var bo=L(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.resolveSchema=st.getCompilingSchema=st.resolveRef=st.compileSchema=st.SchemaEnv=void 0;var dt=Y(),Zk=go(),un=Et(),pt=jr(),Mf=ue(),Yk=Ur(),qn=class{constructor(e){var n;this.refs={},this.dynamicAnchors={};let r;typeof e.schema=="object"&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(n=e.baseId)!==null&&n!==void 0?n:(0,pt.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={}}};st.SchemaEnv=qn;function Tl(t){let e=Bf.call(this,t);if(e)return e;let n=(0,pt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new dt.CodeGen(this.scope,{es5:r,lines:s,ownProperties:o}),a;t.$async&&(a=i.scopeValue("Error",{ref:Zk.default,code:(0,dt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:un.default.data,parentData:un.default.parentData,parentDataProperty:un.default.parentDataProperty,dataNames:[un.default.data],dataPathArr:[dt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,dt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:dt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,dt._)`""`,opts:this.opts,self:this},p;try{this._compilations.add(t),(0,Yk.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let h=i.toString();p=`${i.scopeRefs(un.default.scope)}return ${h}`,this.opts.code.process&&(p=this.opts.code.process(p,t));let b=new Function(`${un.default.self}`,`${un.default.scope}`,p)(this,this.scope.get());if(this.scope.value(c,{ref:b}),b.errors=null,b.schema=t.schema,b.schemaEnv=t,t.$async&&(b.$async=!0),this.opts.code.source===!0&&(b.source={validateName:c,validateCode:h,scopeValues:i._values}),this.opts.unevaluated){let{props:v,items:T}=u;b.evaluated={props:v instanceof dt.Name?void 0:v,items:T instanceof dt.Name?void 0:T,dynamicProps:v instanceof dt.Name,dynamicItems:T instanceof dt.Name},b.source&&(b.source.evaluated=(0,dt.stringify)(b.evaluated))}return t.validate=b,t}catch(h){throw delete t.validate,delete t.validateName,p&&this.logger.error("Error compiling schema, function code:",p),h}finally{this._compilations.delete(t)}}st.compileSchema=Tl;function Qk(t,e,n){var r;n=(0,pt.resolveUrl)(this.opts.uriResolver,e,n);let s=t.refs[n];if(s)return s;let o=t_.call(this,t,n);if(o===void 0){let i=(r=t.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;i&&(o=new qn({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[n]=Xk.call(this,o)}st.resolveRef=Qk;function Xk(t){return(0,pt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Tl.call(this,t)}function Bf(t){for(let e of this._compilations)if(e_(e,t))return e}st.getCompilingSchema=Bf;function e_(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function t_(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||yo.call(this,t,e)}function yo(t,e){let n=this.opts.uriResolver.parse(e),r=(0,pt._getFullPath)(this.opts.uriResolver,n),s=(0,pt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===s)return xl.call(this,n,t);let o=(0,pt.normalizeId)(r),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=yo.call(this,t,i);return typeof a?.schema!="object"?void 0:xl.call(this,n,a)}if(typeof i?.schema=="object"){if(i.validate||Tl.call(this,i),o===(0,pt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(s=(0,pt.resolveUrl)(this.opts.uriResolver,s,u)),new qn({schema:a,schemaId:c,root:t,baseId:s})}return xl.call(this,n,i)}}st.resolveSchema=yo;var n_=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function xl(t,{baseId:e,schema:n,root:r}){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 n=="boolean")return;let c=n[(0,Mf.unescapeFragment)(a)];if(c===void 0)return;n=c;let u=typeof n=="object"&&n[this.opts.schemaId];!n_.has(a)&&u&&(e=(0,pt.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof n!="boolean"&&n.$ref&&!(0,Mf.schemaHasRulesButRef)(n,this.RULES)){let a=(0,pt.resolveUrl)(this.opts.uriResolver,e,n.$ref);o=yo.call(this,r,a)}let{schemaId:i}=this.opts;if(o=o||new qn({schema:n,schemaId:i,root:r,baseId:e}),o.schema!==o.root.schema)return o}});var Ff=L((AC,r_)=>{r_.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 Pl=L((IC,Jf)=>{"use strict";var s_=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),Rl=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Vf=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),o_=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function El(t){let e="",n=0,r=0;for(r=0;r<t.length;r++)if(n=t[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r];break}for(r+=1;r<t.length;r++){if(n=t[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r]}return e}var i_=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Hf(t){return t.length=0,!0}function a_(t,e,n){if(t.length){let r=El(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function l_(t){let e=0,n={error:!1,address:"",zone:""},r=[],s=[],o=!1,i=!1,a=a_;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(o===!0&&(i=!0),!a(s,r,n))break;if(++e>7){n.error=!0;break}c>0&&t[c-1]===":"&&(o=!0),r.push(":");continue}else if(u==="%"){if(!a(s,r,n))break;a=Hf}else{s.push(u);continue}}return s.length&&(a===Hf?n.zone=s.join(""):i?r.push(s.join("")):r.push(El(s))),n.address=r.join(""),n}function Gf(t){if(c_(t,":")<2)return{host:t,isIPV6:!1};let e=l_(t);if(e.error)return{host:t,isIPV6:!1};{let n=e.address,r=e.address;return e.zone&&(n+="%"+e.zone,r+="%25"+e.zone),{host:n,isIPV6:!0,escapedHost:r}}}function c_(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function u_(t){let e=t,n=[],r=-1,s=0;for(;s=e.length;){if(s===1){if(e===".")break;if(e==="/"){n.push("/");break}else{n.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]==="/")){n.push("/");break}}else if(s===3&&e==="/.."){n.length!==0&&n.pop(),n.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),n.length!==0&&n.pop();continue}}if((r=e.indexOf("/",1))===-1){n.push(e);break}else n.push(e.slice(0,r)),e=e.slice(r)}return n.join("")}var d_={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},p_=/[@/?#:]/g,f_=/[@/?#]/g;function Wf(t,e){let n=e?f_:p_;return n.lastIndex=0,t.replace(n,r=>d_[r])}function h_(t,e=!1){if(t.indexOf("%")===-1)return t;let n="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let s=t.slice(r+1,r+3);if(Rl(s)){let o=s.toUpperCase(),i=String.fromCharCode(parseInt(o,16));e&&Vf(i)?n+=i:n+="%"+o,r+=2;continue}}n+=t[r]}return n}function m_(t){let e="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let r=t.slice(n+1,n+3);if(Rl(r)){let s=r.toUpperCase(),o=String.fromCharCode(parseInt(s,16));o!=="."&&Vf(o)?e+=o:e+="%"+s,n+=2;continue}}o_(t[n])?e+=t[n]:e+=escape(t[n])}return e}function g_(t){let e="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let r=t.slice(n+1,n+3);if(Rl(r)){e+="%"+r.toUpperCase(),n+=2;continue}}e+=escape(t[n])}return e}function y_(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!Kf(n)){let r=Gf(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=Wf(n,!1)}e.push(n)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}Jf.exports={nonSimpleDomain:i_,recomposeAuthority:y_,reescapeHostDelimiters:Wf,normalizePercentEncoding:h_,normalizePathEncoding:m_,escapePreservingEscapes:g_,removeDotSegments:u_,isIPv4:Kf,isUUID:s_,normalizeIPv6:Gf,stringArrayToHexStripped:El}});var eh=L((CC,Xf)=>{"use strict";var{isUUID:b_}=Pl(),w_=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,v_=["http","https","ws","wss","urn","urn:uuid"];function S_(t){return v_.indexOf(t)!==-1}function Al(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 Zf(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Yf(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 k_(t){return t.secure=Al(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function __(t){if((t.port===(Al(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,n]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=n,t.resourceName=void 0}return t.fragment=void 0,t}function $_(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(w_);if(n){let r=e.scheme||t.scheme||"urn";t.nid=n[1].toLowerCase(),t.nss=n[2];let s=`${r}:${e.nid||t.nid}`,o=Il(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function x_(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let n=e.scheme||t.scheme||"urn",r=t.nid.toLowerCase(),s=`${n}:${e.nid||r}`,o=Il(s);o&&(t=o.serialize(t,e));let i=t,a=t.nss;return i.path=`${r||e.nid}:${a}`,e.skipEscape=!0,i}function T_(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!b_(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function R_(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Qf={scheme:"http",domainHost:!0,parse:Zf,serialize:Yf},E_={scheme:"https",domainHost:Qf.domainHost,parse:Zf,serialize:Yf},wo={scheme:"ws",domainHost:!0,parse:k_,serialize:__},P_={scheme:"wss",domainHost:wo.domainHost,parse:wo.parse,serialize:wo.serialize},A_={scheme:"urn",parse:$_,serialize:x_,skipNormalize:!0},I_={scheme:"urn:uuid",parse:T_,serialize:R_,skipNormalize:!0},vo={http:Qf,https:E_,ws:wo,wss:P_,urn:A_,"urn:uuid":I_};Object.setPrototypeOf(vo,null);function Il(t){return t&&(vo[t]||vo[t.toLowerCase()])||void 0}Xf.exports={wsIsSecure:Al,SCHEMES:vo,isValidSchemeName:S_,getSchemeHandler:Il}});var oh=L((OC,_o)=>{"use strict";var{normalizeIPv6:C_,removeDotSegments:qr,recomposeAuthority:O_,normalizePercentEncoding:N_,normalizePathEncoding:j_,escapePreservingEscapes:L_,reescapeHostDelimiters:z_,isIPv4:U_,nonSimpleDomain:D_}=Pl(),{SCHEMES:q_,getSchemeHandler:nh}=eh();function M_(t,e){return typeof t=="string"?t=W_(t,e):typeof t=="object"&&(t=ko(dn(t,e),e)),t}function B_(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},{parsed:s,malformedAuthorityOrPort:o}=So(t,r),{parsed:i,malformedAuthorityOrPort:a}=So(e,r);if(o||a)throw new Error(s.error||i.error||"URI is malformed.");let c=rh(s,i,r,!0);return r.skipEscape=!0,dn(c,r)}function rh(t,e,n,r){let s={};return r||(t=ko(dn(t,n),n),e=ko(dn(e,n),n)),n=n||{},!n.tolerant&&e.scheme?(s.scheme=e.scheme,s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=qr(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=qr(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=qr(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=qr(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,n){let r=th(t,n),s=th(e,n);return r!==void 0&&s!==void 0&&r.toLowerCase()===s.toLowerCase()}function dn(t,e){let n={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:""},r=Object.assign({},e),s=[],o=nh(r.scheme||n.scheme);o&&o.serialize&&o.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=N_(n.path):(n.path=L_(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&s.push(n.scheme,":");let i=O_(n);if(i!==void 0&&(r.reference!=="suffix"&&s.push("//"),s.push(i),n.path&&n.path[0]!=="/"&&s.push("/")),n.path!==void 0){let a=n.path;!r.absolutePath&&(!o||!o.absolutePath)&&(a=qr(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),s.push(a)}return n.query!==void 0&&s.push("?",n.query),n.fragment!==void 0&&s.push("#",n.fragment),s.join("")}var H_=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,K_=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,V_=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;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 So(t,e){let n=Object.assign({},e),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},s=!1,o=!1;n.reference==="suffix"&&(n.scheme?t=n.scheme+":"+t:t="//"+t);let i=t.match(K_);i!==null&&i[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",s=!0);let a=t.match(V_);if(a!==null){let u=a[1],p=u.replace(/[\t\n\r]/g,"");p.length>=2&&(p.slice(0,2)!=="//"?(r.error=r.error||"URI authority must not contain a literal backslash.",s=!0):u.length!==p.length&&(r.error=r.error||"URI authority introducer must not contain whitespace.",s=!0))}let c=t.match(H_);if(c){r.scheme=c[1],r.userinfo=c[3],r.host=c[4],r.port=parseInt(c[5],10),r.path=c[6]||"",r.query=c[7],r.fragment=c[8],isNaN(r.port)&&(r.port=c[5]);let u=G_(r,c);if(u!==void 0&&(r.error=r.error||u,s=!0),r.host)if(U_(r.host)===!1){let k=C_(r.host);r.host=k.host.toLowerCase(),o=k.isIPV6}else o=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");let p=nh(n.scheme||r.scheme);if(!n.unicodeSupport&&(!p||!p.unicodeSupport)&&r.host&&(n.domainHost||p&&p.domainHost)&&o===!1&&D_(r.host))try{r.host=new URL("http://"+r.host).hostname}catch(h){r.error=r.error||"Host's domain name can not be converted to ASCII: "+h}if((!p||p&&!p.skipNormalize)&&(t.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=z_(unescape(r.host),o))),r.path&&(r.path=j_(r.path)),r.fragment))try{r.fragment=encodeURI(decodeURIComponent(r.fragment))}catch{r.error=r.error||"URI malformed"}p&&p.parse&&p.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return{parsed:r,malformedAuthorityOrPort:s}}function ko(t,e){return So(t,e).parsed}function W_(t,e){return sh(t,e).normalized}function sh(t,e){let{parsed:n,malformedAuthorityOrPort:r}=So(t,e);return{normalized:r?t:dn(n,e),malformedAuthorityOrPort:r}}function th(t,e){if(typeof t=="string"){let{normalized:n,malformedAuthorityOrPort:r}=sh(t,e);return r?void 0:n}if(typeof t=="object")return dn(t,e)}var Cl={SCHEMES:q_,normalize:M_,resolve:B_,resolveComponent:rh,equal:F_,serialize:dn,parse:ko};_o.exports=Cl;_o.exports.default=Cl;_o.exports.fastUri=Cl});var ah=L(Ol=>{"use strict";Object.defineProperty(Ol,"__esModule",{value:!0});var ih=oh();ih.code='require("ajv/dist/runtime/uri").default';Ol.default=ih});var mh=L(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 J_=Ur();Object.defineProperty(Re,"KeywordCxt",{enumerable:!0,get:function(){return J_.KeywordCxt}});var Mn=Y();Object.defineProperty(Re,"_",{enumerable:!0,get:function(){return Mn._}});Object.defineProperty(Re,"str",{enumerable:!0,get:function(){return Mn.str}});Object.defineProperty(Re,"stringify",{enumerable:!0,get:function(){return Mn.stringify}});Object.defineProperty(Re,"nil",{enumerable:!0,get:function(){return Mn.nil}});Object.defineProperty(Re,"Name",{enumerable:!0,get:function(){return Mn.Name}});Object.defineProperty(Re,"CodeGen",{enumerable:!0,get:function(){return Mn.CodeGen}});var Z_=go(),ph=Dr(),Y_=al(),Mr=bo(),Q_=Y(),Br=jr(),$o=Nr(),jl=ue(),lh=Ff(),X_=ah(),fh=(t,e)=>new RegExp(t,e);fh.code="new RegExp";var e$=["removeAdditional","useDefaults","coerceTypes"],t$=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),n$={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."},r$={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},ch=200;function s$(t){var e,n,r,s,o,i,a,c,u,p,h,k,b,v,T,R,E,I,z,ie,H,Ce,Ue,Qn,mt;let Zt=t.strict,_t=(e=t.code)===null||e===void 0?void 0:e.optimize,mn=_t===!0||_t===void 0?1:_t||0,gn=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:fh,ns=(s=t.uriResolver)!==null&&s!==void 0?s:X_.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:Zt)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Zt)!==null&&c!==void 0?c:!0,strictTypes:(p=(u=t.strictTypes)!==null&&u!==void 0?u:Zt)!==null&&p!==void 0?p:"log",strictTuples:(k=(h=t.strictTuples)!==null&&h!==void 0?h:Zt)!==null&&k!==void 0?k:"log",strictRequired:(v=(b=t.strictRequired)!==null&&b!==void 0?b:Zt)!==null&&v!==void 0?v:!1,code:t.code?{...t.code,optimize:mn,regExp:gn}:{optimize:mn,regExp:gn},loopRequired:(T=t.loopRequired)!==null&&T!==void 0?T:ch,loopEnum:(R=t.loopEnum)!==null&&R!==void 0?R:ch,meta:(E=t.meta)!==null&&E!==void 0?E:!0,messages:(I=t.messages)!==null&&I!==void 0?I:!0,inlineRefs:(z=t.inlineRefs)!==null&&z!==void 0?z:!0,schemaId:(ie=t.schemaId)!==null&&ie!==void 0?ie:"$id",addUsedSchema:(H=t.addUsedSchema)!==null&&H!==void 0?H:!0,validateSchema:(Ce=t.validateSchema)!==null&&Ce!==void 0?Ce:!0,validateFormats:(Ue=t.validateFormats)!==null&&Ue!==void 0?Ue:!0,unicodeRegExp:(Qn=t.unicodeRegExp)!==null&&Qn!==void 0?Qn:!0,int32range:(mt=t.int32range)!==null&&mt!==void 0?mt:!0,uriResolver:ns}}var Fr=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,...s$(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new Q_.ValueScope({scope:{},prefixes:t$,es5:n,lines:r}),this.logger=u$(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Y_.getRules)(),uh.call(this,n$,e,"NOT SUPPORTED"),uh.call(this,r$,e,"DEPRECATED","warn"),this._metaOpts=l$.call(this),e.formats&&i$.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&a$.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),o$.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,s=lh;r==="id"&&(s={...lh},s.id=s.$id,delete s.$id),n&&e&&this.addMetaSchema(s,s[r],!1)}defaultMeta(){let{meta:e,schemaId:n}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[n]||e:void 0}validate(e,n){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let s=r(n);return"$async"in r||(this.errors=r.errors),s}compile(e,n){let r=this._addSchema(e,n);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,n){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return s.call(this,e,n);async function s(p,h){await o.call(this,p.$schema);let k=this._addSchema(p,h);return k.validate||i.call(this,k)}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(h){if(!(h instanceof ph.default))throw h;return a.call(this,h),await c.call(this,h.missingSchema),i.call(this,p)}}function a({missingSchema:p,missingRef:h}){if(this.refs[p])throw new Error(`AnySchema ${p} is loaded but ${h} cannot be resolved`)}async function c(p){let h=await u.call(this,p);this.refs[p]||await o.call(this,h.$schema),this.refs[p]||this.addSchema(h,p,n)}async function u(p){let h=this._loading[p];if(h)return h;try{return await(this._loading[p]=r(p))}finally{delete this._loading[p]}}}addSchema(e,n,r,s=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,r,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 n=(0,Br.normalizeId)(n||o),this._checkUnique(n),this.schemas[n]=this._addSchema(e,r,n,s,!0),this}addMetaSchema(e,n,r=this.opts.validateSchema){return this.addSchema(e,n,!0,r),this}validateSchema(e,n){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let s=this.validate(r,e);if(!s&&n){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 n;for(;typeof(n=dh.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,s=new Mr.SchemaEnv({schema:{},schemaId:r});if(n=Mr.resolveSchema.call(this,s,e),!n)return;this.refs[e]=n}return n.validate||this._compileSchemaEnv(n)}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 n=dh.call(this,e);return typeof n=="object"&&this._cache.delete(n.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let n=e;this._cache.delete(n);let r=e[this.opts.schemaId];return r&&(r=(0,Br.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let n of e)this.addKeyword(n);return this}addKeyword(e,n){let r;if(typeof e=="string")r=e,typeof n=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),n.keyword=r);else if(typeof e=="object"&&n===void 0){if(n=e,r=n.keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(p$.call(this,r,n),!n)return(0,jl.eachItem)(r,o=>Nl.call(this,o)),this;h$.call(this,n);let s={...n,type:(0,$o.getJSONTypes)(n.type),schemaType:(0,$o.getJSONTypes)(n.schemaType)};return(0,jl.eachItem)(r,s.type.length===0?o=>Nl.call(this,o,s):o=>s.type.forEach(i=>Nl.call(this,o,s,i))),this}getKeyword(e){let n=this.RULES.all[e];return typeof n=="object"?n.definition:!!n}removeKeyword(e){let{RULES:n}=this;delete n.keywords[e],delete n.all[e];for(let r of n.rules){let s=r.rules.findIndex(o=>o.keyword===e);s>=0&&r.rules.splice(s,1)}return this}addFormat(e,n){return typeof n=="string"&&(n=new RegExp(n)),this.formats[e]=n,this}errorsText(e=this.errors,{separator:n=", ",dataVar:r="data"}={}){return!e||e.length===0?"No errors":e.map(s=>`${r}${s.instancePath} ${s.message}`).reduce((s,o)=>s+n+o)}$dataMetaSchema(e,n){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let s of n){let o=s.split("/").slice(1),i=e;for(let a of o)i=i[a];for(let a in r){let c=r[a];if(typeof c!="object")continue;let{$data:u}=c.definition,p=i[a];u&&p&&(i[a]=hh(p))}}return e}_removeAllSchemas(e,n){for(let r in e){let s=e[r];(!n||n.test(r))&&(typeof s=="string"?delete e[r]:s&&!s.meta&&(this._cache.delete(s.schema),delete e[r]))}}_addSchema(e,n,r,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 c=this._cache.get(e);if(c!==void 0)return c;r=(0,Br.normalizeId)(i||r);let u=Br.getSchemaRefs.call(this,e,r);return c=new Mr.SchemaEnv({schema:e,schemaId:a,meta:n,baseId:r,localRefs:u}),this._cache.set(c.schema,c),o&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=c),s&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Mr.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let n=this.opts;this.opts=this._metaOpts;try{Mr.compileSchema.call(this,e)}finally{this.opts=n}}};Fr.ValidationError=Z_.default;Fr.MissingRefError=ph.default;Re.default=Fr;function uh(t,e,n,r="error"){for(let s in t){let o=s;o in e&&this.logger[r](`${n}: option ${s}. ${t[o]}`)}}function dh(t){return t=(0,Br.normalizeId)(t),this.schemas[t]||this.refs[t]}function o$(){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 i$(){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 n=t[e];n.keyword||(n.keyword=e),this.addKeyword(n)}}function l$(){let t={...this.opts};for(let e of e$)delete t[e];return t}var c$={log(){},warn(){},error(){}};function u$(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 d$=/^[a-z_$][a-z0-9_$:-]*$/i;function p$(t,e){let{RULES:n}=this;if((0,jl.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!d$.test(r))throw new Error(`Keyword ${r} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Nl(t,e,n){var r;let s=e?.post;if(n&&s)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,i=s?o.post:o.rules.find(({type:c})=>c===n);if(i||(i={type:n,rules:[]},o.rules.push(i)),o.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,$o.getJSONTypes)(e.type),schemaType:(0,$o.getJSONTypes)(e.schemaType)}};e.before?f$.call(this,i,a,e.before):i.rules.push(a),o.all[t]=a,(r=e.implements)===null||r===void 0||r.forEach(c=>this.addKeyword(c))}function f$(t,e,n){let r=t.rules.findIndex(s=>s.keyword===n);r>=0?t.rules.splice(r,0,e):(t.rules.push(e),this.logger.warn(`rule ${n} is not defined`))}function h$(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=hh(e)),t.validateSchema=this.compile(e,!0))}var m$={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function hh(t){return{anyOf:[t,m$]}}});var gh=L(Ll=>{"use strict";Object.defineProperty(Ll,"__esModule",{value:!0});var g$={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ll.default=g$});var vh=L(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.callRef=pn.getValidate=void 0;var y$=Dr(),yh=rt(),He=Y(),Bn=Et(),bh=bo(),xo=ue(),b$={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:n,it:r}=t,{baseId:s,schemaEnv:o,validateName:i,opts:a,self:c}=r,{root:u}=o;if((n==="#"||n==="#/")&&s===u.baseId)return h();let p=bh.resolveRef.call(c,u,s,n);if(p===void 0)throw new y$.default(r.opts.uriResolver,s,n);if(p instanceof bh.SchemaEnv)return k(p);return b(p);function h(){if(o===u)return To(t,i,o,o.$async);let v=e.scopeValue("root",{ref:u});return To(t,(0,He._)`${v}.validate`,u,u.$async)}function k(v){let T=wh(t,v);To(t,T,v,v.$async)}function b(v){let T=e.scopeValue("schema",a.code.source===!0?{ref:v,code:(0,He.stringify)(v)}:{ref:v}),R=e.name("valid"),E=t.subschema({schema:v,dataTypes:[],schemaPath:He.nil,topSchemaRef:T,errSchemaPath:n},R);t.mergeEvaluated(E),t.ok(R)}}};function wh(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,He._)`${n.scopeValue("wrapper",{ref:e})}.validate`}pn.getValidate=wh;function To(t,e,n,r){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:c}=o,u=c.passContext?Bn.default.this:He.nil;r?p():h();function p(){if(!a.$async)throw new Error("async schema referenced by sync schema");let v=s.let("valid");s.try(()=>{s.code((0,He._)`await ${(0,yh.callValidateCode)(t,e,u)}`),b(e),i||s.assign(v,!0)},T=>{s.if((0,He._)`!(${T} instanceof ${o.ValidationError})`,()=>s.throw(T)),k(T),i||s.assign(v,!1)}),t.ok(v)}function h(){t.result((0,yh.callValidateCode)(t,e,u),()=>b(e),()=>k(e))}function k(v){let T=(0,He._)`${v}.errors`;s.assign(Bn.default.vErrors,(0,He._)`${Bn.default.vErrors} === null ? ${T} : ${Bn.default.vErrors}.concat(${T})`),s.assign(Bn.default.errors,(0,He._)`${Bn.default.vErrors}.length`)}function b(v){var T;if(!o.opts.unevaluated)return;let R=(T=n?.validate)===null||T===void 0?void 0:T.evaluated;if(o.props!==!0)if(R&&!R.dynamicProps)R.props!==void 0&&(o.props=xo.mergeEvaluated.props(s,R.props,o.props));else{let E=s.var("props",(0,He._)`${v}.evaluated.props`);o.props=xo.mergeEvaluated.props(s,E,o.props,He.Name)}if(o.items!==!0)if(R&&!R.dynamicItems)R.items!==void 0&&(o.items=xo.mergeEvaluated.items(s,R.items,o.items));else{let E=s.var("items",(0,He._)`${v}.evaluated.items`);o.items=xo.mergeEvaluated.items(s,E,o.items,He.Name)}}}pn.callRef=To;pn.default=b$});var Sh=L(zl=>{"use strict";Object.defineProperty(zl,"__esModule",{value:!0});var w$=gh(),v$=vh(),S$=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",w$.default,v$.default];zl.default=S$});var kh=L(Ul=>{"use strict";Object.defineProperty(Ul,"__esModule",{value:!0});var Ro=Y(),Gt=Ro.operators,Eo={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}},k$={message:({keyword:t,schemaCode:e})=>(0,Ro.str)`must be ${Eo[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Ro._)`{comparison: ${Eo[t].okStr}, limit: ${e}}`},_$={keyword:Object.keys(Eo),type:"number",schemaType:"number",$data:!0,error:k$,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,Ro._)`${n} ${Eo[e].fail} ${r} || isNaN(${n})`)}};Ul.default=_$});var _h=L(Dl=>{"use strict";Object.defineProperty(Dl,"__esModule",{value:!0});var Hr=Y(),$$={message:({schemaCode:t})=>(0,Hr.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Hr._)`{multipleOf: ${t}}`},x$={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:$$,code(t){let{gen:e,data:n,schemaCode:r,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,Hr._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,Hr._)`${i} !== parseInt(${i})`;t.fail$data((0,Hr._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};Dl.default=x$});var xh=L(ql=>{"use strict";Object.defineProperty(ql,"__esModule",{value:!0});function $h(t){let e=t.length,n=0,r=0,s;for(;r<e;)n++,s=t.charCodeAt(r++),s>=55296&&s<=56319&&r<e&&(s=t.charCodeAt(r),(s&64512)===56320&&r++);return n}ql.default=$h;$h.code='require("ajv/dist/runtime/ucs2length").default'});var Th=L(Ml=>{"use strict";Object.defineProperty(Ml,"__esModule",{value:!0});var fn=Y(),T$=ue(),R$=xh(),E$={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,fn.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,fn._)`{limit: ${t}}`},P$={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:E$,code(t){let{keyword:e,data:n,schemaCode:r,it:s}=t,o=e==="maxLength"?fn.operators.GT:fn.operators.LT,i=s.opts.unicode===!1?(0,fn._)`${n}.length`:(0,fn._)`${(0,T$.useFunc)(t.gen,R$.default)}(${n})`;t.fail$data((0,fn._)`${i} ${o} ${r}`)}};Ml.default=P$});var Rh=L(Bl=>{"use strict";Object.defineProperty(Bl,"__esModule",{value:!0});var A$=rt(),I$=ue(),Fn=Y(),C$={message:({schemaCode:t})=>(0,Fn.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Fn._)`{pattern: ${t}}`},O$={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:C$,code(t){let{gen:e,data:n,$data:r,schema:s,schemaCode:o,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(r){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,Fn._)`new RegExp`:(0,I$.useFunc)(e,c),p=e.let("valid");e.try(()=>e.assign(p,(0,Fn._)`${u}(${o}, ${a}).test(${n})`),()=>e.assign(p,!1)),t.fail$data((0,Fn._)`!${p}`)}else{let c=(0,A$.usePattern)(t,s);t.fail$data((0,Fn._)`!${c}.test(${n})`)}}};Bl.default=O$});var Eh=L(Fl=>{"use strict";Object.defineProperty(Fl,"__esModule",{value:!0});var Kr=Y(),N$={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,Kr.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,Kr._)`{limit: ${t}}`},j$={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:N$,code(t){let{keyword:e,data:n,schemaCode:r}=t,s=e==="maxProperties"?Kr.operators.GT:Kr.operators.LT;t.fail$data((0,Kr._)`Object.keys(${n}).length ${s} ${r}`)}};Fl.default=j$});var Ph=L(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});var Vr=rt(),Gr=Y(),L$=ue(),z$={message:({params:{missingProperty:t}})=>(0,Gr.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Gr._)`{missingProperty: ${t}}`},U$={keyword:"required",type:"object",schemaType:"array",$data:!0,error:z$,code(t){let{gen:e,schema:n,schemaCode:r,data:s,$data:o,it:i}=t,{opts:a}=i;if(!o&&n.length===0)return;let c=n.length>=a.loopRequired;if(i.allErrors?u():p(),a.strictRequired){let b=t.parentSchema.properties,{definedProperties:v}=t.it;for(let T of n)if(b?.[T]===void 0&&!v.has(T)){let R=i.schemaEnv.baseId+i.errSchemaPath,E=`required property "${T}" is not defined at "${R}" (strictRequired)`;(0,L$.checkStrictMode)(i,E,i.opts.strictRequired)}}function u(){if(c||o)t.block$data(Gr.nil,h);else for(let b of n)(0,Vr.checkReportMissingProp)(t,b)}function p(){let b=e.let("missing");if(c||o){let v=e.let("valid",!0);t.block$data(v,()=>k(b,v)),t.ok(v)}else e.if((0,Vr.checkMissingProp)(t,n,b)),(0,Vr.reportMissingProp)(t,b),e.else()}function h(){e.forOf("prop",r,b=>{t.setParams({missingProperty:b}),e.if((0,Vr.noPropertyInData)(e,s,b,a.ownProperties),()=>t.error())})}function k(b,v){t.setParams({missingProperty:b}),e.forOf(b,r,()=>{e.assign(v,(0,Vr.propertyInData)(e,s,b,a.ownProperties)),e.if((0,Gr.not)(v),()=>{t.error(),e.break()})},Gr.nil)}}};Hl.default=U$});var Ah=L(Kl=>{"use strict";Object.defineProperty(Kl,"__esModule",{value:!0});var Wr=Y(),D$={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,Wr.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,Wr._)`{limit: ${t}}`},q$={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:D$,code(t){let{keyword:e,data:n,schemaCode:r}=t,s=e==="maxItems"?Wr.operators.GT:Wr.operators.LT;t.fail$data((0,Wr._)`${n}.length ${s} ${r}`)}};Kl.default=q$});var Po=L(Vl=>{"use strict";Object.defineProperty(Vl,"__esModule",{value:!0});var Ih=ml();Ih.code='require("ajv/dist/runtime/equal").default';Vl.default=Ih});var Ch=L(Wl=>{"use strict";Object.defineProperty(Wl,"__esModule",{value:!0});var Gl=Nr(),Ee=Y(),M$=ue(),B$=Po(),F$={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}}`},H$={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:F$,code(t){let{gen:e,data:n,$data:r,schema:s,parentSchema:o,schemaCode:i,it:a}=t;if(!r&&!s)return;let c=e.let("valid"),u=o.items?(0,Gl.getSchemaTypes)(o.items):[];t.block$data(c,p,(0,Ee._)`${i} === false`),t.ok(c);function p(){let v=e.let("i",(0,Ee._)`${n}.length`),T=e.let("j");t.setParams({i:v,j:T}),e.assign(c,!0),e.if((0,Ee._)`${v} > 1`,()=>(h()?k:b)(v,T))}function h(){return u.length>0&&!u.some(v=>v==="object"||v==="array")}function k(v,T){let R=e.name("item"),E=(0,Gl.checkDataTypes)(u,R,a.opts.strictNumbers,Gl.DataType.Wrong),I=e.const("indices",(0,Ee._)`{}`);e.for((0,Ee._)`;${v}--;`,()=>{e.let(R,(0,Ee._)`${n}[${v}]`),e.if(E,(0,Ee._)`continue`),u.length>1&&e.if((0,Ee._)`typeof ${R} == "string"`,(0,Ee._)`${R} += "_"`),e.if((0,Ee._)`typeof ${I}[${R}] == "number"`,()=>{e.assign(T,(0,Ee._)`${I}[${R}]`),t.error(),e.assign(c,!1).break()}).code((0,Ee._)`${I}[${R}] = ${v}`)})}function b(v,T){let R=(0,M$.useFunc)(e,B$.default),E=e.name("outer");e.label(E).for((0,Ee._)`;${v}--;`,()=>e.for((0,Ee._)`${T} = ${v}; ${T}--;`,()=>e.if((0,Ee._)`${R}(${n}[${v}], ${n}[${T}])`,()=>{t.error(),e.assign(c,!1).break(E)})))}}};Wl.default=H$});var Oh=L(Zl=>{"use strict";Object.defineProperty(Zl,"__esModule",{value:!0});var Jl=Y(),K$=ue(),V$=Po(),G$={message:"must be equal to constant",params:({schemaCode:t})=>(0,Jl._)`{allowedValue: ${t}}`},W$={keyword:"const",$data:!0,error:G$,code(t){let{gen:e,data:n,$data:r,schemaCode:s,schema:o}=t;r||o&&typeof o=="object"?t.fail$data((0,Jl._)`!${(0,K$.useFunc)(e,V$.default)}(${n}, ${s})`):t.fail((0,Jl._)`${o} !== ${n}`)}};Zl.default=W$});var Nh=L(Yl=>{"use strict";Object.defineProperty(Yl,"__esModule",{value:!0});var Jr=Y(),J$=ue(),Z$=Po(),Y$={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Jr._)`{allowedValues: ${t}}`},Q$={keyword:"enum",schemaType:"array",$data:!0,error:Y$,code(t){let{gen:e,data:n,$data:r,schema:s,schemaCode:o,it:i}=t;if(!r&&s.length===0)throw new Error("enum must have non-empty array");let a=s.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,J$.useFunc)(e,Z$.default)),p;if(a||r)p=e.let("valid"),t.block$data(p,h);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let b=e.const("vSchema",o);p=(0,Jr.or)(...s.map((v,T)=>k(b,T)))}t.pass(p);function h(){e.assign(p,!1),e.forOf("v",o,b=>e.if((0,Jr._)`${u()}(${n}, ${b})`,()=>e.assign(p,!0).break()))}function k(b,v){let T=s[v];return typeof T=="object"&&T!==null?(0,Jr._)`${u()}(${n}, ${b}[${v}])`:(0,Jr._)`${n} === ${T}`}}};Yl.default=Q$});var jh=L(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});var X$=kh(),ex=_h(),tx=Th(),nx=Rh(),rx=Eh(),sx=Ph(),ox=Ah(),ix=Ch(),ax=Oh(),lx=Nh(),cx=[X$.default,ex.default,tx.default,nx.default,rx.default,sx.default,ox.default,ix.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},ax.default,lx.default];Ql.default=cx});var ec=L(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});Zr.validateAdditionalItems=void 0;var hn=Y(),Xl=ue(),ux={message:({params:{len:t}})=>(0,hn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,hn._)`{limit: ${t}}`},dx={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:ux,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,Xl.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}Lh(t,r)}};function Lh(t,e){let{gen:n,schema:r,data:s,keyword:o,it:i}=t;i.items=!0;let a=n.const("len",(0,hn._)`${s}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,hn._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,Xl.alwaysValidSchema)(i,r)){let u=n.var("valid",(0,hn._)`${a} <= ${e.length}`);n.if((0,hn.not)(u),()=>c(u)),t.ok(u)}function c(u){n.forRange("i",e.length,a,p=>{t.subschema({keyword:o,dataProp:p,dataPropType:Xl.Type.Num},u),i.allErrors||n.if((0,hn.not)(u),()=>n.break())})}}Zr.validateAdditionalItems=Lh;Zr.default=dx});var tc=L(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.validateTuple=void 0;var zh=Y(),Ao=ue(),px=rt(),fx={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return Uh(t,"additionalItems",e);n.items=!0,!(0,Ao.alwaysValidSchema)(n,e)&&t.ok((0,px.validateArray)(t))}};function Uh(t,e,n=t.schema){let{gen:r,parentSchema:s,data:o,keyword:i,it:a}=t;p(s),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=Ao.mergeEvaluated.items(r,n.length,a.items));let c=r.name("valid"),u=r.const("len",(0,zh._)`${o}.length`);n.forEach((h,k)=>{(0,Ao.alwaysValidSchema)(a,h)||(r.if((0,zh._)`${u} > ${k}`,()=>t.subschema({keyword:i,schemaProp:k,dataProp:k},c)),t.ok(c))});function p(h){let{opts:k,errSchemaPath:b}=a,v=n.length,T=v===h.minItems&&(v===h.maxItems||h[e]===!1);if(k.strictTuples&&!T){let R=`"${i}" is ${v}-tuple, but minItems or maxItems/${e} are not specified or different at path "${b}"`;(0,Ao.checkStrictMode)(a,R,k.strictTuples)}}}Yr.validateTuple=Uh;Yr.default=fx});var Dh=L(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});var hx=tc(),mx={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,hx.validateTuple)(t,"items")};nc.default=mx});var Mh=L(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});var qh=Y(),gx=ue(),yx=rt(),bx=ec(),wx={message:({params:{len:t}})=>(0,qh.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,qh._)`{limit: ${t}}`},vx={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:wx,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:s}=n;r.items=!0,!(0,gx.alwaysValidSchema)(r,e)&&(s?(0,bx.validateAdditionalItems)(t,s):t.ok((0,yx.validateArray)(t)))}};rc.default=vx});var Bh=L(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});var ot=Y(),Io=ue(),Sx={message:({params:{min:t,max:e}})=>e===void 0?(0,ot.str)`must contain at least ${t} valid item(s)`:(0,ot.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,ot._)`{minContains: ${t}}`:(0,ot._)`{minContains: ${t}, maxContains: ${e}}`},kx={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Sx,code(t){let{gen:e,schema:n,parentSchema:r,data:s,it:o}=t,i,a,{minContains:c,maxContains:u}=r;o.opts.next?(i=c===void 0?1:c,a=u):i=1;let p=e.const("len",(0,ot._)`${s}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Io.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Io.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Io.alwaysValidSchema)(o,n)){let T=(0,ot._)`${p} >= ${i}`;a!==void 0&&(T=(0,ot._)`${T} && ${p} <= ${a}`),t.pass(T);return}o.items=!0;let h=e.name("valid");a===void 0&&i===1?b(h,()=>e.if(h,()=>e.break())):i===0?(e.let(h,!0),a!==void 0&&e.if((0,ot._)`${s}.length > 0`,k)):(e.let(h,!1),k()),t.result(h,()=>t.reset());function k(){let T=e.name("_valid"),R=e.let("count",0);b(T,()=>e.if(T,()=>v(R)))}function b(T,R){e.forRange("i",0,p,E=>{t.subschema({keyword:"contains",dataProp:E,dataPropType:Io.Type.Num,compositeRule:!0},T),R()})}function v(T){e.code((0,ot._)`${T}++`),a===void 0?e.if((0,ot._)`${T} >= ${i}`,()=>e.assign(h,!0).break()):(e.if((0,ot._)`${T} > ${a}`,()=>e.assign(h,!1).break()),i===1?e.assign(h,!0):e.if((0,ot._)`${T} >= ${i}`,()=>e.assign(h,!0)))}}};sc.default=kx});var Kh=L(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.validateSchemaDeps=vt.validatePropertyDeps=vt.error=void 0;var oc=Y(),_x=ue(),Qr=rt();vt.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,oc.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,oc._)`{property: ${t},
|
|
943
|
+
missingProperty: ${r},
|
|
944
944
|
depsCount: ${e},
|
|
945
|
-
deps: ${r}}`};var px={keyword:"dependencies",type:"object",schemaType:"object",error:bt.error,code(t){let[e,r]=fx(t);Oh(t,e),Nh(t,r)}};function fx({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 Oh(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 c=(0,Zn.propertyInData)(r,n,i,s.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),s.allErrors?r.if(c,()=>{for(let d of a)(0,Zn.checkReportMissingProp)(t,d)}):(r.if((0,rc._)`${c} && (${(0,Zn.checkMissingProp)(t,a,o)})`),(0,Zn.reportMissingProp)(t,o),r.else())}}bt.validatePropertyDeps=Oh;function Nh(t,e=t.schema){let{gen:r,data:n,keyword:s,it:o}=t,i=r.name("valid");for(let a in e)(0,ux.alwaysValidSchema)(o,e[a])||(r.if((0,Zn.propertyInData)(r,n,a,o.opts.ownProperties),()=>{let c=t.subschema({keyword:s,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}bt.validateSchemaDeps=Nh;bt.default=px});var Lh=z(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});var zh=Z(),hx=ae(),mx={message:"property name must be valid",params:({params:t})=>(0,zh._)`{propertyName: ${t.propertyName}}`},gx={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:mx,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,hx.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,zh.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};nc.default=gx});var oc=z(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});var Po=nt(),ut=Z(),yx=Et(),Ao=ae(),bx={message:"must NOT have additional properties",params:({params:t})=>(0,ut._)`{additionalProperty: ${t.additionalProperty}}`},wx={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:bx,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:c}=i;if(i.props=!0,c.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} === ${yx.default.errors}`);function h(){e.forIn("key",s,R=>{!d.length&&!u.length?w(R):e.if(S(R),()=>w(R))})}function S(R){let E;if(d.length>8){let I=(0,Ao.schemaRefOrVal)(i,n.properties,"properties");E=(0,Po.isOwnProperty)(e,I,R)}else d.length?E=(0,ut.or)(...d.map(I=>(0,ut._)`${R} === ${I}`)):E=ut.nil;return u.length&&(E=(0,ut.or)(E,...u.map(I=>(0,ut._)`${(0,Po.usePattern)(t,I)}.test(${R})`))),(0,ut.not)(E)}function b(R){e.code((0,ut._)`delete ${s}[${R}]`)}function w(R){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){b(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");c.removeAdditional==="failing"?(k(R,E,!1),e.if((0,ut.not)(E),()=>{t.reset(),b(R)})):(k(R,E),a||e.if((0,ut.not)(E),()=>e.break()))}}function k(R,E,I){let L={keyword:"additionalProperties",dataProp:R,dataPropType:Ao.Type.Str};I===!1&&Object.assign(L,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(L,E)}}};sc.default=wx});var qh=z(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});var vx=zn(),Uh=nt(),ic=ae(),Dh=oc(),Sx={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&&Dh.default.code(new vx.KeywordCxt(o,Dh.default,"additionalProperties"));let i=(0,Uh.allSchemaProperties)(r);for(let h of i)o.definedProperties.add(h);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=ic.mergeEvaluated.props(e,(0,ic.toHash)(i),o.props));let a=i.filter(h=>!(0,ic.alwaysValidSchema)(o,r[h]));if(a.length===0)return;let c=e.name("valid");for(let h of a)d(h)?u(h):(e.if((0,Uh.propertyInData)(e,s,h,o.opts.ownProperties)),u(h),o.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(h),t.ok(c);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},c)}}};ac.default=Sx});var Hh=z(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});var Mh=nt(),Io=Z(),Bh=ae(),Fh=ae(),_x={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,Mh.allSchemaProperties)(r),c=a.filter(k=>(0,Bh.alwaysValidSchema)(o,r[k]));if(a.length===0||c.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,Fh.evaluatedPropsToName)(e,o.props));let{props:h}=o;S();function S(){for(let k of a)d&&b(k),o.allErrors?w(k):(e.var(u,!0),w(k),e.if(u))}function b(k){for(let R in d)new RegExp(k).test(R)&&(0,Bh.checkStrictMode)(o,`property ${R} matches pattern ${k} (use allowMatchingProperties)`)}function w(k){e.forIn("key",n,R=>{e.if((0,Io._)`${(0,Mh.usePattern)(t,k)}.test(${R})`,()=>{let E=c.includes(k);E||t.subschema({keyword:"patternProperties",schemaProp:k,dataProp:R,dataPropType:Fh.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())})})}}};lc.default=_x});var Kh=z(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});var kx=ae(),$x={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,kx.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"}};cc.default=$x});var Vh=z(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});var xx=nt(),Tx={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:xx.validateUnion,error:{message:"must match a schema in anyOf"}};dc.default=Tx});var Gh=z(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});var Co=Z(),Rx=ae(),Ex={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Co._)`{passingSchemas: ${t.passing}}`},Px={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Ex,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),c=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 S;(0,Rx.alwaysValidSchema)(s,u)?e.var(c,!0):S=t.subschema({keyword:"oneOf",schemaProp:h,compositeRule:!0},c),h>0&&e.if((0,Co._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Co._)`[${a}, ${h}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,h),S&&t.mergeEvaluated(S,Co.Name)})})}}};uc.default=Px});var Wh=z(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});var Ax=ae(),Ix={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,Ax.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};pc.default=Ix});var Yh=z(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});var Oo=Z(),Zh=ae(),Cx={message:({params:t})=>(0,Oo.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Oo._)`{failingKeyword: ${t.ifClause}}`},Ox={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Cx,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Zh.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=Jh(n,"then"),o=Jh(n,"else");if(!s&&!o)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),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 c(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function d(u,h){return()=>{let S=t.subschema({keyword:u},a);e.assign(i,a),t.mergeValidEvaluated(S,i),h?e.assign(h,(0,Oo._)`${u}`):t.setParams({ifClause:u})}}}};function Jh(t,e){let r=t.schema[e];return r!==void 0&&!(0,Zh.alwaysValidSchema)(t,r)}fc.default=Ox});var Qh=z(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});var Nx=ae(),jx={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,Nx.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};hc.default=jx});var Xh=z(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});var zx=Yl(),Lx=Ph(),Ux=Ql(),Dx=Ih(),qx=Ch(),Mx=jh(),Bx=Lh(),Fx=oc(),Hx=qh(),Kx=Hh(),Vx=Kh(),Gx=Vh(),Wx=Gh(),Jx=Wh(),Zx=Yh(),Yx=Qh();function Qx(t=!1){let e=[Vx.default,Gx.default,Wx.default,Jx.default,Zx.default,Yx.default,Bx.default,Fx.default,Mx.default,Hx.default,Kx.default];return t?e.push(Lx.default,Dx.default):e.push(zx.default,Ux.default),e.push(qx.default),e}mc.default=Qx});var em=z(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});var we=Z(),Xx={message:({schemaCode:t})=>(0,we.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,we._)`{format: ${t}}`},eT={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Xx,code(t,e){let{gen:r,data:n,$data:s,schema:o,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:d,schemaEnv:u,self:h}=a;if(!c.validateFormats)return;s?S():b();function S(){let w=r.scopeValue("formats",{ref:h.formats,code:c.code.formats}),k=r.const("fDef",(0,we._)`${w}[${i}]`),R=r.let("fType"),E=r.let("format");r.if((0,we._)`typeof ${k} == "object" && !(${k} instanceof RegExp)`,()=>r.assign(R,(0,we._)`${k}.type || "string"`).assign(E,(0,we._)`${k}.validate`),()=>r.assign(R,(0,we._)`"string"`).assign(E,k)),t.fail$data((0,we.or)(I(),L()));function I(){return c.strictSchema===!1?we.nil:(0,we._)`${i} && !${E}`}function L(){let ne=u.$async?(0,we._)`(${k}.async ? await ${E}(${n}) : ${E}(${n}))`:(0,we._)`${E}(${n})`,F=(0,we._)`(typeof ${E} == "function" ? ${ne} : ${E}.test(${n}))`;return(0,we._)`${E} && ${E} !== true && ${R} === ${e} && !${F}`}}function b(){let w=h.formats[o];if(!w){I();return}if(w===!0)return;let[k,R,E]=L(w);k===e&&t.pass(ne());function I(){if(c.strictSchema===!1){h.logger.warn(F());return}throw new Error(F());function F(){return`unknown format "${o}" ignored in schema at path "${d}"`}}function L(F){let Ce=F instanceof RegExp?(0,we.regexpCode)(F):c.code.formats?(0,we._)`${c.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 ne(){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})`}}}};gc.default=eT});var tm=z(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});var tT=em(),rT=[tT.default];yc.default=rT});var rm=z(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});Mr.contentVocabulary=Mr.metadataVocabulary=void 0;Mr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Mr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var sm=z(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});var nT=uh(),sT=xh(),oT=Xh(),iT=tm(),nm=rm(),aT=[nT.default,sT.default,(0,oT.default)(),iT.default,nm.metadataVocabulary,nm.contentVocabulary];bc.default=aT});var im=z(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});No.DiscrError=void 0;var om;(function(t){t.Tag="tag",t.Mapping="mapping"})(om||(No.DiscrError=om={}))});var lm=z(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});var Br=Z(),wc=im(),am=mo(),lT=Ln(),cT=ae(),dT={message:({params:{discrError:t,tagName:e}})=>t===wc.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Br._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},uT={keyword:"discriminator",type:"object",schemaType:"object",error:dT,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 c=e.let("valid",!1),d=e.const("tag",(0,Br._)`${r}${(0,Br.getProperty)(a)}`);e.if((0,Br._)`typeof ${d} == "string"`,()=>u(),()=>t.error(!1,{discrError:wc.DiscrError.Tag,tag:d,tagName:a})),t.ok(c);function u(){let b=S();e.if(!1);for(let w in b)e.elseIf((0,Br._)`${d} === ${w}`),e.assign(c,h(b[w]));e.else(),t.error(!1,{discrError:wc.DiscrError.Mapping,tag:d,tagName:a}),e.endIf()}function h(b){let w=e.name("valid"),k=t.subschema({keyword:"oneOf",schemaProp:b},w);return t.mergeEvaluated(k,Br.Name),w}function S(){var b;let w={},k=E(s),R=!0;for(let ne=0;ne<i.length;ne++){let F=i[ne];if(F?.$ref&&!(0,cT.schemaHasRulesButRef)(F,o.self.RULES)){let Ue=F.$ref;if(F=am.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,Ue),F instanceof am.SchemaEnv&&(F=F.schema),F===void 0)throw new lT.default(o.opts.uriResolver,o.baseId,Ue)}let Ce=(b=F?.properties)===null||b===void 0?void 0:b[a];if(typeof Ce!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);R=R&&(k||E(F)),I(Ce,ne)}if(!R)throw new Error(`discriminator: "${a}" must be required`);return w;function E({required:ne}){return Array.isArray(ne)&&ne.includes(a)}function I(ne,F){if(ne.const)L(ne.const,F);else if(ne.enum)for(let Ce of ne.enum)L(Ce,F);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function L(ne,F){if(typeof ne!="string"||ne in w)throw new Error(`discriminator: "${a}" values must be unique strings`);w[ne]=F}}}};vc.default=uT});var cm=z((oO,pT)=>{pT.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 _c=z((ye,Sc)=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.MissingRefError=ye.ValidationError=ye.CodeGen=ye.Name=ye.nil=ye.stringify=ye.str=ye._=ye.KeywordCxt=ye.Ajv=void 0;var fT=oh(),hT=sm(),mT=lm(),dm=cm(),gT=["/properties"],jo="http://json-schema.org/draft-07/schema",Fr=class extends fT.default{_addVocabularies(){super._addVocabularies(),hT.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(mT.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(dm,gT):dm;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)}};ye.Ajv=Fr;Sc.exports=ye=Fr;Sc.exports.Ajv=Fr;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=Fr;var yT=zn();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return yT.KeywordCxt}});var Hr=Z();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return Hr._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return Hr.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return Hr.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return Hr.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return Hr.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return Hr.CodeGen}});var bT=fo();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return bT.default}});var wT=Ln();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return wT.default}})});var bm=z(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(hm,Tc),time:wt($c(!0),Rc),"date-time":wt(um(!0),gm),"iso-time":wt($c(),mm),"iso-date-time":wt(um(),ym),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:xT,"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:CT,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:TT,int32:{type:"number",validate:PT},int64:{type:"number",validate:AT},float:{type:"number",validate:fm},double:{type:"number",validate:fm},password:!0,binary:!0};vt.fastFormats={...vt.fullFormats,date:wt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Tc),time:wt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Rc),"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,gm),"iso-time":wt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,mm),"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,ym),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 vT(t){return t%4===0&&(t%100!==0||t%400===0)}var ST=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,_T=[0,31,28,31,30,31,30,31,31,30,31,30,31];function hm(t){let e=ST.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&&vT(r)?29:_T[n])}function Tc(t,e){if(t&&e)return t>e?1:t<e?-1:0}var kc=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function $c(t){return function(r){let n=kc.exec(r);if(!n)return!1;let s=+n[1],o=+n[2],i=+n[3],a=n[4],c=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*c,S=s-d*c-(h<0?1:0);return(S===23||S===-1)&&(h===59||h===-1)&&i<61}}function Rc(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 mm(t,e){if(!(t&&e))return;let r=kc.exec(t),n=kc.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 xc=/t|\s/i;function um(t){let e=$c(t);return function(n){let s=n.split(xc);return s.length===2&&hm(s[0])&&e(s[1])}}function gm(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function ym(t,e){if(!(t&&e))return;let[r,n]=t.split(xc),[s,o]=e.split(xc),i=Tc(r,s);if(i!==void 0)return i||Rc(n,o)}var kT=/\/|:/,$T=/^(?:[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 xT(t){return kT.test(t)&&$T.test(t)}var pm=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function TT(t){return pm.lastIndex=0,pm.test(t)}var RT=-(2**31),ET=2**31-1;function PT(t){return Number.isInteger(t)&&t<=ET&&t>=RT}function AT(t){return Number.isInteger(t)}function fm(){return!0}var IT=/[^\\]\\Z/;function CT(t){if(IT.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var wm=z(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.formatLimitDefinition=void 0;var OT=_c(),pt=Z(),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}},NT={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}}`};Kr.formatLimitDefinition={keyword:Object.keys(zo),type:"string",schemaType:"string",$data:!0,error:NT,code(t){let{gen:e,data:r,schemaCode:n,keyword:s,it:o}=t,{opts:i,self:a}=o;if(!i.validateFormats)return;let c=new OT.KeywordCxt(o,a.RULES.all.format.definition,"format");c.$data?d():u();function d(){let S=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),b=e.const("fmt",(0,pt._)`${S}[${c.schemaCode}]`);t.fail$data((0,pt.or)((0,pt._)`typeof ${b} != "object"`,(0,pt._)`${b} instanceof RegExp`,(0,pt._)`typeof ${b}.compare != "function"`,h(b)))}function u(){let S=c.schema,b=a.formats[S];if(!b||b===!0)return;if(typeof b!="object"||b instanceof RegExp||typeof b.compare!="function")throw new Error(`"${s}": format "${S}" does not define "compare" function`);let w=e.scopeValue("formats",{key:S,ref:b,code:i.code.formats?(0,pt._)`${i.code.formats}${(0,pt.getProperty)(S)}`:void 0});t.fail$data(h(w))}function h(S){return(0,pt._)`${S}.compare(${r}, ${n}) ${zo[s].fail} 0`}},dependencies:["format"]};var jT=t=>(t.addKeyword(Kr.formatLimitDefinition),t);Kr.default=jT});var km=z((Yn,_m)=>{"use strict";Object.defineProperty(Yn,"__esModule",{value:!0});var Vr=bm(),zT=wm(),Ec=Z(),vm=new Ec.Name("fullFormats"),LT=new Ec.Name("fastFormats"),Pc=(t,e={keywords:!0})=>{if(Array.isArray(e))return Sm(t,e,Vr.fullFormats,vm),t;let[r,n]=e.mode==="fast"?[Vr.fastFormats,LT]:[Vr.fullFormats,vm],s=e.formats||Vr.formatNames;return Sm(t,s,r,n),e.keywords&&(0,zT.default)(t),t};Pc.get=(t,e="full")=>{let n=(e==="fast"?Vr.fastFormats:Vr.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Sm(t,e,r,n){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,Ec._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}_m.exports=Yn=Pc;Object.defineProperty(Yn,"__esModule",{value:!0});Yn.default=Pc});function UT(){let t=new $m.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,xm.default)(t),t}var $m,xm,Lo,Tm=j(()=>{$m=Fc(_c(),1),xm=Fc(km(),1);Lo=class{constructor(e){this._ajv=e??UT()}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,Rm=j(()=>{Pr();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,c=a?Array.isArray(a.content)?a.content:[a.content]:[],d=c.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(c.filter(S=>S.type==="tool_use").map(S=>S.id)),h=new Set(o.filter(S=>S.type==="tool_result").map(S=>S.toolUseId));if(u.size!==h.size||![...u].every(S=>h.has(S)))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},vn,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},Er,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 Em(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 Pm(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 Am=j(()=>{});var Do,Im=j(()=>{Op();Pr();Tm();dn();Rm();Am();Do=class extends Xs{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(wn.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(Fi,n=>this._oninitialize(n)),this.setNotificationHandler(Hi,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Yi,async(n,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=wn.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=Cp(this._capabilities,e)}setRequestHandler(e,r){let s=Lt(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o=kr(s);if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let a=async(c,d)=>{let u=zt(Rr,c);if(!u.success){let w=u.error instanceof Error?u.error.message:String(u.error);throw new U(M.InvalidParams,`Invalid tools/call request: ${w}`)}let{params:h}=u.data,S=await Promise.resolve(r(c,d));if(h.task){let w=zt(xr,S);if(!w.success){let k=w.error instanceof Error?w.error.message:String(w.error);throw new U(M.InvalidParams,`Invalid task creation result: ${k}`)}return w.data}let b=zt(Ms,S);if(!b.success){let w=b.error instanceof Error?b.error.message:String(b.error);throw new U(M.InvalidParams,`Invalid tools/call result: ${w}`)}return b.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){Pm(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Em(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:Iu.includes(r)?r:Ui,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]:[],c=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(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){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},Qi,r):this.request({method:"sampling/createMessage",params:e},vn,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},Er,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},Er,r);if(o.action==="accept"&&o.content&&s.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!a.valid)throw new U(M.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof U?i:new U(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},Xi,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 Ac(t){return!!t&&typeof t=="object"&&Om in t}function Nm(t){return t[Om]?.complete}var Om,Cm,jm=j(()=>{Om=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(Cm||(Cm={}))});var zm=j(()=>{});function qT(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"),!DT.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 MT(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 Ic(t){let e=qT(t);return MT(t,e.warnings),e.isValid}var DT,Lm=j(()=>{DT=/^[A-Za-z0-9._-]{1,128}$/});var qo,Um=j(()=>{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 BT}from"zod";function Mm(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Bm(t){return"_def"in t||"_zod"in t||Mm(t)}function Cc(t){return typeof t!="object"||t===null||Bm(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Mm)}function Dm(t){if(t){if(Cc(t))return tr(t);if(!Bm(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function HT(t){let e=Lt(t);return e?Object.entries(e).map(([r,n])=>{let s=Pu(n),o=Au(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=kr(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function qm(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Mo,FT,Qn,Fm=j(()=>{Im();dn();za();Pr();jm();zm();Lm();Um();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(Rr)),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=_r(r.inputSchema);return s?Oa(s,{strictUnions:!0,pipeStrategy:"input"}):FT})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let s=_r(r.outputSchema);s&&(n.outputSchema=Oa(s,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Rr,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new U(M.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new U(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 U(M.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!s)throw new U(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),c=await this.executeToolHandler(n,a,r);return s||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof U&&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=_r(e.inputSchema)??e.inputSchema,i=await vs(o,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Ss(a);throw new U(M.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new U(M.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let s=_r(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 U(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)),c=a.task.taskId,d=a.task,u=d.pollInterval??5e3;for(;d.status!=="completed"&&d.status!=="failed"&&d.status!=="cancelled";){await new Promise(S=>setTimeout(S,u));let h=await n.taskStore.getTask(c);if(!h)throw new U(M.InternalError,`Task ${c} not found during polling`);d=h}return await n.taskStore.getTaskResult(c)}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 Gu(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Wu(e),this.handleResourceCompletion(e,e.params.ref);default:throw new U(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 U(M.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new U(M.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Qn;let o=Lt(n.argsSchema)?.[e.params.argument.name];if(!Ac(o))return Qn;let i=Nm(o);if(!i)return Qn;let a=await i(e.params.argument.value,e.params.context);return qm(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 Qn;throw new U(M.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=n.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return Qn;let o=await s(e.params.argument.value,e.params.context);return qm(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 U(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 U(M.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?HT(r.argsSchema):void 0}))})),this.server.setRequestHandler(Ds,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new U(M.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new U(M.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let s=_r(n.argsSchema),o=await vs(s,e.params.arguments);if(!o.success){let c="error"in o?o.error:"Unknown error",d=Ss(c);throw new U(M.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(c=>{let d=c instanceof BT?c._def?.innerType:c;return Ac(d)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,s,o,i,a,c,d){Ic(e);let u={title:r,description:n,inputSchema:Dm(s),outputSchema:Dm(o),annotations:i,execution:a,_meta:c,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"&&Ic(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 c=r[0];if(Cc(c))s=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Cc(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).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:c,_meta:d}=r;return this._createRegisteredTool(e,s,o,i,a,c,{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()}},FT={type:"object",properties:{}};Qn={completion:{values:[],hasMore:!1}}});function VT(t){return Du.parse(JSON.parse(t))}function Hm(t){return JSON.stringify(t)+`
|
|
946
|
-
`}var
|
|
947
|
-
`);if(e===-1)return null;let
|
|
948
|
-
|
|
949
|
-
`)}}]}})}u.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:b,token:w}=await e(),k=await fetch(`${b}/v1/catalog/records`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});if(!k.ok)throw new Error(`catalog fetch failed: ${k.status}`);return ve(await k.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:q.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:q.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:b,source:w})=>{let{baseUrl:k,token:R}=await e(),E=w?`?source=${encodeURIComponent(w)}`:"",I=await fetch(`${k}/v1/catalog/records/${encodeURIComponent(b)}${E}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(I.status===404)throw new Error(`unknown record type "${b}" \u2014 list them with catalog_get.`);if(!I.ok)throw new Error(`record anatomy fetch failed: ${I.status}`);return ve(await I.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:q.array(q.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:q.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:b,source:w})=>{let{baseUrl:k,token:R}=await e(),E=new URLSearchParams({types:b.join(",")});w&&E.set("source",w);let I=await fetch(`${k}/v1/catalog/columns?${E}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(I.status===404)throw new Error(`none of those record types resolved: ${b.join(", ")} \u2014 list them with catalog_get.`);if(!I.ok)throw new Error(`common columns fetch failed: ${I.status}`);return ve(await I.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:b,token:w}=await e(),k=await fetch(`${b}/v1/catalog/census`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});if(!k.ok)throw new Error(`catalog census failed: ${k.status}`);return ve(await k.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:q.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:q.enum(Ym).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:q.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:b,kind:w,limit:k})=>{let{baseUrl:R,token:E}=await e(),I=new URLSearchParams({q:b});w&&I.set("kind",w),k!==void 0&&I.set("limit",String(k));let L=await fetch(`${R}/v1/catalog/objects?${I}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(!L.ok)throw new Error(`catalog object search failed: ${L.status}`);return ve(await L.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:q.enum(Ym),externalId:q.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:b,externalId:w})=>{let{baseUrl:k,token:R}=await e(),E=await fetch(`${k}/v1/catalog/objects/${encodeURIComponent(b)}/${encodeURIComponent(w)}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(E.status===404)throw new Error(`unknown object ${b}:${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:q.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:q.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:b,limit:w})=>{let{baseUrl:k,token:R}=await e(),E=new URLSearchParams({q:b});w!==void 0&&E.set("limit",String(w));let I=await fetch(`${k}/v1/kb/search?${E}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(!I.ok)throw new Error(`kb search failed: ${I.status}`);return ve(await I.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:q.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:b})=>{let{baseUrl:w,token:k}=await e(),R=await fetch(`${w}/v1/kb/document/${encodeURIComponent(b)}`,{headers:{Authorization:`Bearer ${k}`,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:q.boolean().optional()}},async({recordsOnly:b})=>{let{baseUrl:w,token:k}=await e();return{content:[{type:"text",text:await It({baseUrl:w,token:k,recordsOnly:b})}]}}),u.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:q.string(),event:q.string().optional(),template:q.enum(["require-field","enforce-format","blank"]).optional(),field:q.string().optional(),regex:q.string().optional(),source:q.string().optional(),id:q.string().optional()}},async b=>{let w=Sr("hook",{recordType:b.recordType,event:b.event,template:b.template,field:b.field,regex:b.regex,source:b.source,id:b.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:q.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:q.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:q.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:q.string().optional().describe("Target record type (defaults to the trigger record type)."),event:q.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:q.string().optional()}},async b=>{let w=Sr("conduit",{recordType:b.recordType,source:b.source,to:b.to,toRecordType:b.toRecordType,event:b.event,id:b.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:q.string().describe("The extension TS source."),samplesDir:q.string().optional().describe('Samples directory (default "samples").')}},async({source:b,samplesDir:w})=>{let k=Zm(process.cwd(),w??"samples"),R=await en(k),E=await ps(b,R.map(L=>L.fixture)),I=E.filter(L=>!L.pass).length;return ve({total:E.length,passed:E.length-I,results:E})}),u.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:q.string(),recordType:q.string(),event:q.string(),source:q.string().describe('Adapter id or "standalone".'),sourceCode:q.string().describe("The verbatim extension TS."),extensionKind:q.string().optional()}},async b=>{let{baseUrl:w,token:k}=await e(),E=await new H({baseUrl:w,token:k}).deploy({id:b.id,recordType:b.recordType,event:b.event,source:b.source,sourceCode:b.sourceCode,extensionKind:b.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:q.string(),limit:q.number().int().positive().optional()}},async({id:b,limit:w})=>{let{baseUrl:k,token:R}=await e(),E=new H({baseUrl:k,token:R});return ve({id:b,logs:await E.logs(b,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:b,token:w}=await e(),k=new H({baseUrl:b,token:w});return ve(await k.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:q.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:q.string().optional().describe("Display name (defaults to the slug)."),description:q.string().optional().describe("Short description.")}},async({slug:b,name:w,description:k})=>{let{baseUrl:R,token:E}=await e(),I=new H({baseUrl:R,token:E});return ve(await I.appsCreate({slug:b,name:w,description:k}))}),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:q.string().describe("App slug or id.")}},async({app:b})=>{let{baseUrl:w,token:k}=await e(),R=new H({baseUrl:w,token:k});return ve(await R.appsPull(b))}),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:q.string().describe("App slug or id."),files:q.record(q.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:q.string().optional().describe("Short note stored with the revision.")}},async({app:b,files:w,note:k})=>{let{baseUrl:R,token:E}=await e(),I=new H({baseUrl:R,token:E});return ve(await I.appsPush(b,w,{note:k}))});let h=q.object({name:q.string().describe("Field name (lowercase identifier)."),type:q.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:q.boolean().optional()}),S=q.object({slug:q.string().describe("Table slug; the physical table is cr_<slug>."),displayName:q.string().optional(),fields:q.array(h).describe("At least one field."),rowLevelOwner:q.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:b,token:w}=await e(),k=new H({baseUrl:b,token:w});return ve(await k.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:q.array(S),claimedBy:q.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:b,claimedBy:w})=>{let{baseUrl:k,token:R}=await e(),E=new H({baseUrl:k,token:R});return ve(await E.tablesPlan({tables:b,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:q.array(S),claimedBy:q.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:b,claimedBy:w})=>{let{baseUrl:k,token:R}=await e(),E=new H({baseUrl:k,token:R});return ve(await E.tablesApply({tables:b,claimedBy:w}))}),u.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async b=>{let{baseUrl:w,token:k}=await e(),E=await(await fetch(`${w}/v1/catalog/records`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}})).text();return{contents:[{uri:b.href,mimeType:"application/json",text:E}]}}),u.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async b=>{let{baseUrl:w,token:k}=await e(),R=await It({baseUrl:w,token:k});return{contents:[{uri:b.href,mimeType:"text/plain",text:R}]}}),u.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async b=>{let w=Zm(process.cwd(),"samples"),k=[];try{k=(await GT.readdir(w)).filter(E=>E.endsWith(".json"))}catch{k=[]}let R=await en(w);return{contents:[{uri:b.href,mimeType:"application/json",text:JSON.stringify({files:k,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 b=>{let w=await Xm(),k=[];if(w){let{baseUrl:R,token:E}=await e();k=await w.listRecipesForSurface({surface:"mcp-authoring",baseUrl:R,token:E},r)}return{contents:[{uri:b.href,mimeType:"application/json",text:JSON.stringify({recipes:k})}]}}),u}async function YT(t={}){let e=await rg(t),r=new Fo;await e.connect(r)}var Ym,Qm,eg,tg,ng,JT,ZT,og=j(()=>{Fm();Gm();oi();cs();yr();hi();Si();Jm();Ym=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];eg="turbobase-authoring",tg="0.1.0";ng=["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"],JT=[...ng,...Wm],ZT=["catalog:///","types://all","samples:///","recipes:///"]});oi();cs();yr();hi();import{spawn as Uc}from"node:child_process";import{promises as te}from"node:fs";import{homedir as QT}from"node:os";import{basename as ag,dirname as Gr,join as Ve,relative as Ho,resolve as ce,sep as Lc}from"node:path";import{Command as XT}from"commander";pi();import{promises as fd}from"node:fs";function ud(t,e){return e===t?"same-type-merge":"different-type-mint"}var hd=4;function mi(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=br(t,"id"),r=br(t,"on"),n=br(t,"source"),s=br(t,"recordType"),o=/to\s*:\s*\{([^}]*)\}/.exec(t)?.[1]??"",i=br(o,"source"),a=br(o,"recordType"),c=/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:c?Number(c[1]):hd}}function br(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function Mg(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 md(t,e,r="fixture"){let n=e.name??r,s=[],o;try{o=mi(t)}catch(c){return{fixtureName:n,conduit:Fg(),guards:s,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],logs:[],error:c instanceof Error?c.message:String(c)}}let i=Mg(e),a=Object.entries(e.atlasLinks??{}).map(([c,d])=>({key:c,resolved:d}));try{let c=await us(t),u=!!(await Xr(c,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 S=await Xr(c,i,{member:"transform",timeoutMs:200}),b=S.effects.logs,w=S.effects.result;if(!w||typeof w!="object")throw new Error(`conduit ${o.id} transform returned no result (expected { patch, createdFrom? })`);let k=w,R=ud(o.fromRecordType,o.toRecordType),{wouldWriteBindings:E,masterAction:I}=Bg(o,R,e);return{fixtureName:n,conduit:o,guards:s,whenPassed:u,atlasResolutions:a,transformResult:k,applyBranch:R,wouldWriteBindings:E,masterAction:I,logs:b}}catch(c){return{fixtureName:n,conduit:o,guards:s,whenPassed:!1,atlasResolutions:a,wouldWriteBindings:[],logs:[],error:c instanceof Error?c.message:String(c)}}}function Bg(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 Fg(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",cycleBudget:hd}}async function gd(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 yd(t){let e=await fd.readFile(t,"utf8");return JSON.parse(e)}function bd(t){return fd.readFile(t,"utf8")}function wd(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(`
|
|
950
|
-
`);if(
|
|
951
|
-
`)}function
|
|
952
|
-
`).map(
|
|
953
|
-
`)}var
|
|
954
|
-
`);for(let a of e.warnings)i.push(` ${
|
|
955
|
-
lint: ${
|
|
956
|
-
`)}function
|
|
945
|
+
deps: ${n}}`};var $x={keyword:"dependencies",type:"object",schemaType:"object",error:vt.error,code(t){let[e,n]=xx(t);Fh(t,e),Hh(t,n)}};function xx({schema:t}){let e={},n={};for(let r in t){if(r==="__proto__")continue;let s=Array.isArray(t[r])?e:n;s[r]=t[r]}return[e,n]}function Fh(t,e=t.schema){let{gen:n,data:r,it:s}=t;if(Object.keys(e).length===0)return;let o=n.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Qr.propertyInData)(n,r,i,s.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),s.allErrors?n.if(c,()=>{for(let u of a)(0,Qr.checkReportMissingProp)(t,u)}):(n.if((0,oc._)`${c} && (${(0,Qr.checkMissingProp)(t,a,o)})`),(0,Qr.reportMissingProp)(t,o),n.else())}}vt.validatePropertyDeps=Fh;function Hh(t,e=t.schema){let{gen:n,data:r,keyword:s,it:o}=t,i=n.name("valid");for(let a in e)(0,_x.alwaysValidSchema)(o,e[a])||(n.if((0,Qr.propertyInData)(n,r,a,o.opts.ownProperties),()=>{let c=t.subschema({keyword:s,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>n.var(i,!0)),t.ok(i))}vt.validateSchemaDeps=Hh;vt.default=$x});var Gh=L(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});var Vh=Y(),Tx=ue(),Rx={message:"property name must be valid",params:({params:t})=>(0,Vh._)`{propertyName: ${t.propertyName}}`},Ex={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Rx,code(t){let{gen:e,schema:n,data:r,it:s}=t;if((0,Tx.alwaysValidSchema)(s,n))return;let o=e.name("valid");e.forIn("key",r,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},o),e.if((0,Vh.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};ic.default=Ex});var lc=L(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});var Co=rt(),ft=Y(),Px=Et(),Oo=ue(),Ax={message:"must NOT have additional properties",params:({params:t})=>(0,ft._)`{additionalProperty: ${t.additionalProperty}}`},Ix={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Ax,code(t){let{gen:e,schema:n,parentSchema:r,data:s,errsCount:o,it:i}=t;if(!o)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Oo.alwaysValidSchema)(i,n))return;let u=(0,Co.allSchemaProperties)(r.properties),p=(0,Co.allSchemaProperties)(r.patternProperties);h(),t.ok((0,ft._)`${o} === ${Px.default.errors}`);function h(){e.forIn("key",s,R=>{!u.length&&!p.length?v(R):e.if(k(R),()=>v(R))})}function k(R){let E;if(u.length>8){let I=(0,Oo.schemaRefOrVal)(i,r.properties,"properties");E=(0,Co.isOwnProperty)(e,I,R)}else u.length?E=(0,ft.or)(...u.map(I=>(0,ft._)`${R} === ${I}`)):E=ft.nil;return p.length&&(E=(0,ft.or)(E,...p.map(I=>(0,ft._)`${(0,Co.usePattern)(t,I)}.test(${R})`))),(0,ft.not)(E)}function b(R){e.code((0,ft._)`delete ${s}[${R}]`)}function v(R){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){b(R);return}if(n===!1){t.setParams({additionalProperty:R}),t.error(),a||e.break();return}if(typeof n=="object"&&!(0,Oo.alwaysValidSchema)(i,n)){let E=e.name("valid");c.removeAdditional==="failing"?(T(R,E,!1),e.if((0,ft.not)(E),()=>{t.reset(),b(R)})):(T(R,E),a||e.if((0,ft.not)(E),()=>e.break()))}}function T(R,E,I){let z={keyword:"additionalProperties",dataProp:R,dataPropType:Oo.Type.Str};I===!1&&Object.assign(z,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(z,E)}}};ac.default=Ix});var Zh=L(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});var Cx=Ur(),Wh=rt(),cc=ue(),Jh=lc(),Ox={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,parentSchema:r,data:s,it:o}=t;o.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&Jh.default.code(new Cx.KeywordCxt(o,Jh.default,"additionalProperties"));let i=(0,Wh.allSchemaProperties)(n);for(let h of i)o.definedProperties.add(h);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=cc.mergeEvaluated.props(e,(0,cc.toHash)(i),o.props));let a=i.filter(h=>!(0,cc.alwaysValidSchema)(o,n[h]));if(a.length===0)return;let c=e.name("valid");for(let h of a)u(h)?p(h):(e.if((0,Wh.propertyInData)(e,s,h,o.opts.ownProperties)),p(h),o.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(h),t.ok(c);function u(h){return o.opts.useDefaults&&!o.compositeRule&&n[h].default!==void 0}function p(h){t.subschema({keyword:"properties",schemaProp:h,dataProp:h},c)}}};uc.default=Ox});var em=L(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});var Yh=rt(),No=Y(),Qh=ue(),Xh=ue(),Nx={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,data:r,parentSchema:s,it:o}=t,{opts:i}=o,a=(0,Yh.allSchemaProperties)(n),c=a.filter(T=>(0,Qh.alwaysValidSchema)(o,n[T]));if(a.length===0||c.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 No.Name)&&(o.props=(0,Xh.evaluatedPropsToName)(e,o.props));let{props:h}=o;k();function k(){for(let T of a)u&&b(T),o.allErrors?v(T):(e.var(p,!0),v(T),e.if(p))}function b(T){for(let R in u)new RegExp(T).test(R)&&(0,Qh.checkStrictMode)(o,`property ${R} matches pattern ${T} (use allowMatchingProperties)`)}function v(T){e.forIn("key",r,R=>{e.if((0,No._)`${(0,Yh.usePattern)(t,T)}.test(${R})`,()=>{let E=c.includes(T);E||t.subschema({keyword:"patternProperties",schemaProp:T,dataProp:R,dataPropType:Xh.Type.Str},p),o.opts.unevaluated&&h!==!0?e.assign((0,No._)`${h}[${R}]`,!0):!E&&!o.allErrors&&e.if((0,No.not)(p),()=>e.break())})})}}};dc.default=Nx});var tm=L(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});var jx=ue(),Lx={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,jx.alwaysValidSchema)(r,n)){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"}};pc.default=Lx});var nm=L(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});var zx=rt(),Ux={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:zx.validateUnion,error:{message:"must match a schema in anyOf"}};fc.default=Ux});var rm=L(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});var jo=Y(),Dx=ue(),qx={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,jo._)`{passingSchemas: ${t.passing}}`},Mx={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:qx,code(t){let{gen:e,schema:n,parentSchema:r,it:s}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(s.opts.discriminator&&r.discriminator)return;let o=n,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){o.forEach((p,h)=>{let k;(0,Dx.alwaysValidSchema)(s,p)?e.var(c,!0):k=t.subschema({keyword:"oneOf",schemaProp:h,compositeRule:!0},c),h>0&&e.if((0,jo._)`${c} && ${i}`).assign(i,!1).assign(a,(0,jo._)`[${a}, ${h}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,h),k&&t.mergeEvaluated(k,jo.Name)})})}}};hc.default=Mx});var sm=L(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});var Bx=ue(),Fx={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:n,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");let s=e.name("valid");n.forEach((o,i)=>{if((0,Bx.alwaysValidSchema)(r,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};mc.default=Fx});var am=L(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});var Lo=Y(),im=ue(),Hx={message:({params:t})=>(0,Lo.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Lo._)`{failingKeyword: ${t.ifClause}}`},Kx={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Hx,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,im.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let s=om(r,"then"),o=om(r,"else");if(!s&&!o)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),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,Lo.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let p=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(p)}function u(p,h){return()=>{let k=t.subschema({keyword:p},a);e.assign(i,a),t.mergeValidEvaluated(k,i),h?e.assign(h,(0,Lo._)`${p}`):t.setParams({ifClause:p})}}}};function om(t,e){let n=t.schema[e];return n!==void 0&&!(0,im.alwaysValidSchema)(t,n)}gc.default=Kx});var lm=L(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});var Vx=ue(),Gx={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,Vx.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};yc.default=Gx});var cm=L(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});var Wx=ec(),Jx=Dh(),Zx=tc(),Yx=Mh(),Qx=Bh(),Xx=Kh(),eT=Gh(),tT=lc(),nT=Zh(),rT=em(),sT=tm(),oT=nm(),iT=rm(),aT=sm(),lT=am(),cT=lm();function uT(t=!1){let e=[sT.default,oT.default,iT.default,aT.default,lT.default,cT.default,eT.default,tT.default,Xx.default,nT.default,rT.default];return t?e.push(Jx.default,Yx.default):e.push(Wx.default,Zx.default),e.push(Qx.default),e}bc.default=uT});var um=L(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});var we=Y(),dT={message:({schemaCode:t})=>(0,we.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,we._)`{format: ${t}}`},pT={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:dT,code(t,e){let{gen:n,data:r,$data:s,schema:o,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:p,self:h}=a;if(!c.validateFormats)return;s?k():b();function k(){let v=n.scopeValue("formats",{ref:h.formats,code:c.code.formats}),T=n.const("fDef",(0,we._)`${v}[${i}]`),R=n.let("fType"),E=n.let("format");n.if((0,we._)`typeof ${T} == "object" && !(${T} instanceof RegExp)`,()=>n.assign(R,(0,we._)`${T}.type || "string"`).assign(E,(0,we._)`${T}.validate`),()=>n.assign(R,(0,we._)`"string"`).assign(E,T)),t.fail$data((0,we.or)(I(),z()));function I(){return c.strictSchema===!1?we.nil:(0,we._)`${i} && !${E}`}function z(){let ie=p.$async?(0,we._)`(${T}.async ? await ${E}(${r}) : ${E}(${r}))`:(0,we._)`${E}(${r})`,H=(0,we._)`(typeof ${E} == "function" ? ${ie} : ${E}.test(${r}))`;return(0,we._)`${E} && ${E} !== true && ${R} === ${e} && !${H}`}}function b(){let v=h.formats[o];if(!v){I();return}if(v===!0)return;let[T,R,E]=z(v);T===e&&t.pass(ie());function I(){if(c.strictSchema===!1){h.logger.warn(H());return}throw new Error(H());function H(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function z(H){let Ce=H instanceof RegExp?(0,we.regexpCode)(H):c.code.formats?(0,we._)`${c.code.formats}${(0,we.getProperty)(o)}`:void 0,Ue=n.scopeValue("formats",{key:o,ref:H,code:Ce});return typeof H=="object"&&!(H instanceof RegExp)?[H.type||"string",H.validate,(0,we._)`${Ue}.validate`]:["string",H,Ue]}function ie(){if(typeof v=="object"&&!(v instanceof RegExp)&&v.async){if(!p.$async)throw new Error("async format in sync schema");return(0,we._)`await ${E}(${r})`}return typeof R=="function"?(0,we._)`${E}(${r})`:(0,we._)`${E}.test(${r})`}}}};wc.default=pT});var dm=L(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});var fT=um(),hT=[fT.default];vc.default=hT});var pm=L(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.contentVocabulary=Hn.metadataVocabulary=void 0;Hn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Hn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var hm=L(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});var mT=Sh(),gT=jh(),yT=cm(),bT=dm(),fm=pm(),wT=[mT.default,gT.default,(0,yT.default)(),bT.default,fm.metadataVocabulary,fm.contentVocabulary];Sc.default=wT});var gm=L(zo=>{"use strict";Object.defineProperty(zo,"__esModule",{value:!0});zo.DiscrError=void 0;var mm;(function(t){t.Tag="tag",t.Mapping="mapping"})(mm||(zo.DiscrError=mm={}))});var bm=L(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var Kn=Y(),kc=gm(),ym=bo(),vT=Dr(),ST=ue(),kT={message:({params:{discrError:t,tagName:e}})=>t===kc.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,Kn._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},_T={keyword:"discriminator",type:"object",schemaType:"object",error:kT,code(t){let{gen:e,data:n,schema:r,parentSchema:s,it:o}=t,{oneOf:i}=s;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=r.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(r.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,Kn._)`${n}${(0,Kn.getProperty)(a)}`);e.if((0,Kn._)`typeof ${u} == "string"`,()=>p(),()=>t.error(!1,{discrError:kc.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function p(){let b=k();e.if(!1);for(let v in b)e.elseIf((0,Kn._)`${u} === ${v}`),e.assign(c,h(b[v]));e.else(),t.error(!1,{discrError:kc.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function h(b){let v=e.name("valid"),T=t.subschema({keyword:"oneOf",schemaProp:b},v);return t.mergeEvaluated(T,Kn.Name),v}function k(){var b;let v={},T=E(s),R=!0;for(let ie=0;ie<i.length;ie++){let H=i[ie];if(H?.$ref&&!(0,ST.schemaHasRulesButRef)(H,o.self.RULES)){let Ue=H.$ref;if(H=ym.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,Ue),H instanceof ym.SchemaEnv&&(H=H.schema),H===void 0)throw new vT.default(o.opts.uriResolver,o.baseId,Ue)}let Ce=(b=H?.properties)===null||b===void 0?void 0:b[a];if(typeof Ce!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);R=R&&(T||E(H)),I(Ce,ie)}if(!R)throw new Error(`discriminator: "${a}" must be required`);return v;function E({required:ie}){return Array.isArray(ie)&&ie.includes(a)}function I(ie,H){if(ie.const)z(ie.const,H);else if(ie.enum)for(let Ce of ie.enum)z(Ce,H);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function z(ie,H){if(typeof ie!="string"||ie in v)throw new Error(`discriminator: "${a}" values must be unique strings`);v[ie]=H}}}};_c.default=_T});var wm=L((SO,$T)=>{$T.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var xc=L((ye,$c)=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.MissingRefError=ye.ValidationError=ye.CodeGen=ye.Name=ye.nil=ye.stringify=ye.str=ye._=ye.KeywordCxt=ye.Ajv=void 0;var xT=mh(),TT=hm(),RT=bm(),vm=wm(),ET=["/properties"],Uo="http://json-schema.org/draft-07/schema",Vn=class extends xT.default{_addVocabularies(){super._addVocabularies(),TT.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(RT.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(vm,ET):vm;this.addMetaSchema(e,Uo,!1),this.refs["http://json-schema.org/schema"]=Uo}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Uo)?Uo:void 0)}};ye.Ajv=Vn;$c.exports=ye=Vn;$c.exports.Ajv=Vn;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=Vn;var PT=Ur();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return PT.KeywordCxt}});var Gn=Y();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return Gn._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return Gn.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return Gn.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return Gn.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return Gn.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return Gn.CodeGen}});var AT=go();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return AT.default}});var IT=Dr();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return IT.default}})});var Em=L(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.formatNames=kt.fastFormats=kt.fullFormats=void 0;function St(t,e){return{validate:t,compare:e}}kt.fullFormats={date:St($m,Pc),time:St(Rc(!0),Ac),"date-time":St(Sm(!0),Tm),"iso-time":St(Rc(),xm),"iso-date-time":St(Sm(),Rm),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:zT,"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:HT,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:UT,int32:{type:"number",validate:MT},int64:{type:"number",validate:BT},float:{type:"number",validate:_m},double:{type:"number",validate:_m},password:!0,binary:!0};kt.fastFormats={...kt.fullFormats,date:St(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Pc),time:St(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Ac),"date-time":St(/^\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,Tm),"iso-time":St(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,xm),"iso-date-time":St(/^\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,Rm),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};kt.formatNames=Object.keys(kt.fullFormats);function CT(t){return t%4===0&&(t%100!==0||t%400===0)}var OT=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,NT=[0,31,28,31,30,31,30,31,31,30,31,30,31];function $m(t){let e=OT.exec(t);if(!e)return!1;let n=+e[1],r=+e[2],s=+e[3];return r>=1&&r<=12&&s>=1&&s<=(r===2&&CT(n)?29:NT[r])}function Pc(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Tc=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Rc(t){return function(n){let r=Tc.exec(n);if(!r)return!1;let s=+r[1],o=+r[2],i=+r[3],a=r[4],c=r[5]==="-"?-1:1,u=+(r[6]||0),p=+(r[7]||0);if(u>23||p>59||t&&!a)return!1;if(s<=23&&o<=59&&i<60)return!0;let h=o-p*c,k=s-u*c-(h<0?1:0);return(k===23||k===-1)&&(h===59||h===-1)&&i<61}}function Ac(t,e){if(!(t&&e))return;let n=new Date("2020-01-01T"+t).valueOf(),r=new Date("2020-01-01T"+e).valueOf();if(n&&r)return n-r}function xm(t,e){if(!(t&&e))return;let n=Tc.exec(t),r=Tc.exec(e);if(n&&r)return t=n[1]+n[2]+n[3],e=r[1]+r[2]+r[3],t>e?1:t<e?-1:0}var Ec=/t|\s/i;function Sm(t){let e=Rc(t);return function(r){let s=r.split(Ec);return s.length===2&&$m(s[0])&&e(s[1])}}function Tm(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function Rm(t,e){if(!(t&&e))return;let[n,r]=t.split(Ec),[s,o]=e.split(Ec),i=Pc(n,s);if(i!==void 0)return i||Ac(r,o)}var jT=/\/|:/,LT=/^(?:[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 zT(t){return jT.test(t)&<.test(t)}var km=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function UT(t){return km.lastIndex=0,km.test(t)}var DT=-(2**31),qT=2**31-1;function MT(t){return Number.isInteger(t)&&t<=qT&&t>=DT}function BT(t){return Number.isInteger(t)}function _m(){return!0}var FT=/[^\\]\\Z/;function HT(t){if(FT.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Pm=L(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.formatLimitDefinition=void 0;var KT=xc(),ht=Y(),Wt=ht.operators,Do={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}},VT={message:({keyword:t,schemaCode:e})=>(0,ht.str)`should be ${Do[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ht._)`{comparison: ${Do[t].okStr}, limit: ${e}}`};Wn.formatLimitDefinition={keyword:Object.keys(Do),type:"string",schemaType:"string",$data:!0,error:VT,code(t){let{gen:e,data:n,schemaCode:r,keyword:s,it:o}=t,{opts:i,self:a}=o;if(!i.validateFormats)return;let c=new KT.KeywordCxt(o,a.RULES.all.format.definition,"format");c.$data?u():p();function u(){let k=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),b=e.const("fmt",(0,ht._)`${k}[${c.schemaCode}]`);t.fail$data((0,ht.or)((0,ht._)`typeof ${b} != "object"`,(0,ht._)`${b} instanceof RegExp`,(0,ht._)`typeof ${b}.compare != "function"`,h(b)))}function p(){let k=c.schema,b=a.formats[k];if(!b||b===!0)return;if(typeof b!="object"||b instanceof RegExp||typeof b.compare!="function")throw new Error(`"${s}": format "${k}" does not define "compare" function`);let v=e.scopeValue("formats",{key:k,ref:b,code:i.code.formats?(0,ht._)`${i.code.formats}${(0,ht.getProperty)(k)}`:void 0});t.fail$data(h(v))}function h(k){return(0,ht._)`${k}.compare(${n}, ${r}) ${Do[s].fail} 0`}},dependencies:["format"]};var GT=t=>(t.addKeyword(Wn.formatLimitDefinition),t);Wn.default=GT});var Om=L((Xr,Cm)=>{"use strict";Object.defineProperty(Xr,"__esModule",{value:!0});var Jn=Em(),WT=Pm(),Ic=Y(),Am=new Ic.Name("fullFormats"),JT=new Ic.Name("fastFormats"),Cc=(t,e={keywords:!0})=>{if(Array.isArray(e))return Im(t,e,Jn.fullFormats,Am),t;let[n,r]=e.mode==="fast"?[Jn.fastFormats,JT]:[Jn.fullFormats,Am],s=e.formats||Jn.formatNames;return Im(t,s,n,r),e.keywords&&(0,WT.default)(t),t};Cc.get=(t,e="full")=>{let r=(e==="fast"?Jn.fastFormats:Jn.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function Im(t,e,n,r){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,Ic._)`require("ajv-formats/dist/formats").${r}`);for(let i of e)t.addFormat(i,n[i])}Cm.exports=Xr=Cc;Object.defineProperty(Xr,"__esModule",{value:!0});Xr.default=Cc});function ZT(){let t=new Nm.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,jm.default)(t),t}var Nm,jm,qo,Lm=j(()=>{Nm=Vc(xc(),1),jm=Vc(Om(),1);qo=class{constructor(e){this._ajv=e??ZT()}getValidator(e){let n="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return r=>n(r)?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}}});var Mo,zm=j(()=>{Cn();Mo=class{constructor(e){this._server=e}requestStream(e,n,r){return this._server.requestStream(e,n,r)}createMessageStream(e,n){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.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,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.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(c.filter(k=>k.type==="tool_use").map(k=>k.id)),h=new Set(o.filter(k=>k.type==="tool_result").map(k=>k.toolUseId));if(p.size!==h.size||![...p].every(k=>h.has(k)))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},kr,n)}elicitInputStream(e,n){let r=this._server.getClientCapabilities(),s=e.mode??"form";switch(s){case"url":{if(!r?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!r?.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},In,n)}async getTask(e,n){return this._server.getTask({taskId:e},n)}async getTaskResult(e,n,r){return this._server.getTaskResult({taskId:e},n,r)}async listTasks(e,n){return this._server.listTasks(e?{cursor:e}:void 0,n)}async cancelTask(e,n){return this._server.cancelTask({taskId:e},n)}}});function Um(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${e})`);break;default:break}}function Dm(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var qm=j(()=>{});var Bo,Mm=j(()=>{Fp();Cn();Lm();pr();zm();qm();Bo=class extends no{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Sr.options.map((r,s)=>[r,s])),this.isMessageIgnored=(r,s)=>{let o=this._loggingLevels.get(s);return o?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=n?.capabilities??{},this._instructions=n?.instructions,this._jsonSchemaValidator=n?.jsonSchemaValidator??new qo,this.setRequestHandler(Vi,r=>this._oninitialize(r)),this.setNotificationHandler(Gi,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(ea,async(r,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,a=Sr.safeParse(i);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Mo(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Bp(this._capabilities,e)}setRequestHandler(e,n){let s=zt(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o=Tn(s);if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let a=async(c,u)=>{let p=Lt(An,c);if(!p.success){let v=p.error instanceof Error?p.error.message:String(p.error);throw new U(M.InvalidParams,`Invalid tools/call request: ${v}`)}let{params:h}=p.data,k=await Promise.resolve(n(c,u));if(h.task){let v=Lt(En,k);if(!v.success){let T=v.error instanceof Error?v.error.message:String(v.error);throw new U(M.InvalidParams,`Invalid task creation result: ${T}`)}return v.data}let b=Lt(Hs,k);if(!b.success){let v=b.error instanceof Error?b.error.message:String(b.error);throw new U(M.InvalidParams,`Invalid tools/call result: ${v}`)}return b.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,n)}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){Dm(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Um(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let n=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Md.includes(n)?n:Mi,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"},Es)}async createMessage(e,n){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 r=e.messages[e.messages.length-1],s=Array.isArray(r.content)?r.content:[r.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]:[],c=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(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(h=>h.type==="tool_use").map(h=>h.id)),p=new Set(s.filter(h=>h.type==="tool_result").map(h=>h.toolUseId));if(u.size!==p.size||![...u].every(h=>p.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},ta,n):this.request({method:"sampling/createMessage",params:e},kr,n)}async elicitInput(e,n){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},In,n)}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},In,n);if(o.action==="accept"&&o.content&&s.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!a.valid)throw new U(M.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof U?i:new U(M.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return o}}}createElicitationCompletionNotifier(e,n){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}},n)}async listRoots(e,n){return this.request({method:"roots/list",params:e},na,n)}async sendLoggingMessage(e,n){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,n))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 Oc(t){return!!t&&typeof t=="object"&&Fm in t}function Hm(t){return t[Fm]?.complete}var Fm,Bm,Km=j(()=>{Fm=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(Bm||(Bm={}))});var Vm=j(()=>{});function QT(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"),!YT.test(t)){let n=t.split("").filter(r=>!/[A-Za-z0-9._-]/.test(r)).filter((r,s,o)=>o.indexOf(r)===s);return e.push(`Tool name contains invalid characters: ${n.map(r=>`"${r}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function XT(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let n of e)console.warn(` - ${n}`);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 Nc(t){let e=QT(t);return XT(t,e.warnings),e.isValid}var YT,Gm=j(()=>{YT=/^[A-Za-z0-9._-]{1,128}$/});var Fo,Wm=j(()=>{Fo=class{constructor(e){this._mcpServer=e}registerToolTask(e,n,r){let s={taskSupport:"required",...n.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,n.title,n.description,n.inputSchema,n.outputSchema,n.annotations,s,n._meta,r)}}});import{ZodOptional as eR}from"zod";function Ym(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Qm(t){return"_def"in t||"_zod"in t||Ym(t)}function jc(t){return typeof t!="object"||t===null||Qm(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Ym)}function Jm(t){if(t){if(jc(t))return nn(t);if(!Qm(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function nR(t){let e=zt(t);return e?Object.entries(e).map(([n,r])=>{let s=Dd(r),o=qd(r);return{name:n,description:s,required:!o}}):[]}function Jt(t){let n=zt(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=Tn(n);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function Zm(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Ho,tR,es,Xm=j(()=>{Mm();pr();Da();Cn();Km();Vm();Gm();Wm();Ho=class{constructor(e,n){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Bo(e,n)}get experimental(){return this._experimental||(this._experimental={tasks:new Fo(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(Fs)),this.server.assertCanSetRequestHandler(Jt(An)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Fs,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,n])=>{let r={name:e,title:n.title,description:n.description,inputSchema:(()=>{let s=xn(n.inputSchema);return s?La(s,{strictUnions:!0,pipeStrategy:"input"}):tR})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){let s=xn(n.outputSchema);s&&(r.outputSchema=La(s,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(An,async(e,n)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new U(M.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new U(M.InvalidParams,`Tool ${e.params.name} disabled`);let s=!!e.params.task,o=r.execution?.taskSupport,i="createTask"in r.handler;if((o==="required"||o==="optional")&&!i)throw new U(M.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!s)throw new U(M.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!s&&i)return await this.handleAutomaticTaskPolling(r,e,n);let a=await this.validateToolInput(r,e.params.arguments,e.params.name),c=await this.executeToolHandler(r,a,n);return s||await this.validateToolOutput(r,c,e.params.name),c}catch(r){if(r instanceof U&&r.code===M.UrlElicitationRequired)throw r;return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,n,r){if(!e.inputSchema)return;let o=xn(e.inputSchema)??e.inputSchema,i=await _s(o,n);if(!i.success){let a="error"in i?i.error:"Unknown error",c=$s(a);throw new U(M.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${c}`)}return i.data}async validateToolOutput(e,n,r){if(!e.outputSchema||!("content"in n)||n.isError)return;if(!n.structuredContent)throw new U(M.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let s=xn(e.outputSchema),o=await _s(s,n.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",a=$s(i);throw new U(M.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${a}`)}}async executeToolHandler(e,n,r){let s=e.handler;if("createTask"in s){if(!r.taskStore)throw new Error("No task store provided.");let i={...r,taskStore:r.taskStore};if(e.inputSchema){let a=s;return await Promise.resolve(a.createTask(n,i))}else{let a=s;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=s;return await Promise.resolve(i(n,r))}else{let i=s;return await Promise.resolve(i(r))}}async handleAutomaticTaskPolling(e,n,r){if(!r.taskStore)throw new Error("No task store provided for task-capable tool.");let s=await this.validateToolInput(e,n.params.arguments,n.params.name),o=e.handler,i={...r,taskStore:r.taskStore},a=s?await Promise.resolve(o.createTask(s,i)):await Promise.resolve(o.createTask(i)),c=a.task.taskId,u=a.task,p=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(k=>setTimeout(k,p));let h=await r.taskStore.getTask(c);if(!h)throw new U(M.InternalError,`Task ${c} not found during polling`);u=h}return await r.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Jt(Ks)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ks,async e=>{switch(e.params.ref.type){case"ref/prompt":return rp(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return sp(e),this.handleResourceCompletion(e,e.params.ref);default:throw new U(M.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,n){let r=this._registeredPrompts[n.name];if(!r)throw new U(M.InvalidParams,`Prompt ${n.name} not found`);if(!r.enabled)throw new U(M.InvalidParams,`Prompt ${n.name} disabled`);if(!r.argsSchema)return es;let o=zt(r.argsSchema)?.[e.params.argument.name];if(!Oc(o))return es;let i=Hm(o);if(!i)return es;let a=await i(e.params.argument.value,e.params.context);return Zm(a)}async handleResourceCompletion(e,n){let r=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===n.uri);if(!r){if(this._registeredResources[n.uri])return es;throw new U(M.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=r.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return es;let o=await s(e.params.argument.value,e.params.context);return Zm(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Jt(Us)),this.server.assertCanSetRequestHandler(Jt(Ds)),this.server.assertCanSetRequestHandler(Jt(qs)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Us,async(e,n)=>{let r=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(n);for(let a of i.resources)s.push({...o.metadata,...a})}return{resources:[...r,...s]}}),this.server.setRequestHandler(Ds,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,r])=>({name:n,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(qs,async(e,n)=>{let r=new URL(e.params.uri),s=this._registeredResources[r.toString()];if(s){if(!s.enabled)throw new U(M.InvalidParams,`Resource ${r} disabled`);return s.readCallback(r,n)}for(let o of Object.values(this._registeredResourceTemplates)){let i=o.resourceTemplate.uriTemplate.match(r.toString());if(i)return o.readCallback(r,i,n)}throw new U(M.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Jt(Ms)),this.server.assertCanSetRequestHandler(Jt(Bs)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Ms,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,n])=>({name:e,title:n.title,description:n.description,arguments:n.argsSchema?nR(n.argsSchema):void 0}))})),this.server.setRequestHandler(Bs,async(e,n)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new U(M.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new U(M.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let s=xn(r.argsSchema),o=await _s(s,e.params.arguments);if(!o.success){let c="error"in o?o.error:"Unknown error",u=$s(c);throw new U(M.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=o.data,a=r.callback;return await Promise.resolve(a(i,n))}else{let s=r.callback;return await Promise.resolve(s(n))}}),this._promptHandlersInitialized=!0)}resource(e,n,...r){let s;typeof r[0]=="object"&&(s=r.shift());let o=r[0];if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let i=this._createRegisteredResource(e,void 0,n,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,n,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,n,r,s){if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let o=this._createRegisteredResource(e,r.title,n,r,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,r.title,n,r,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,n,r,s,o){let i={name:e,title:n,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!==r&&(delete this._registeredResources[r],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[r]=i,i}_createRegisteredResourceTemplate(e,n,r,s,o){let i={resourceTemplate:r,title:n,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=r.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!r.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,n,r,s,o){let i={title:n,description:r,argsSchema:s===void 0?void 0:nn(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=nn(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(c=>{let u=c instanceof eR?c._def?.innerType:c;return Oc(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,n,r,s,o,i,a,c,u){Nc(e);let p={title:n,description:r,inputSchema:Jm(s),outputSchema:Jm(o),annotations:i,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>p.update({enabled:!1}),enable:()=>p.update({enabled:!0}),remove:()=>p.update({name:null}),update:h=>{typeof h.name<"u"&&h.name!==e&&(typeof h.name=="string"&&Nc(h.name),delete this._registeredTools[e],h.name&&(this._registeredTools[h.name]=p)),typeof h.title<"u"&&(p.title=h.title),typeof h.description<"u"&&(p.description=h.description),typeof h.paramsSchema<"u"&&(p.inputSchema=nn(h.paramsSchema)),typeof h.outputSchema<"u"&&(p.outputSchema=nn(h.outputSchema)),typeof h.callback<"u"&&(p.handler=h.callback),typeof h.annotations<"u"&&(p.annotations=h.annotations),typeof h._meta<"u"&&(p._meta=h._meta),typeof h.enabled<"u"&&(p.enabled=h.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=p,this.setToolRequestHandlers(),this.sendToolListChanged(),p}tool(e,...n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r,s,o,i;if(typeof n[0]=="string"&&(r=n.shift()),n.length>1){let c=n[0];if(jc(c))s=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!jc(n[0])&&(i=n.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=n.shift()}}let a=n[0];return this._createRegisteredTool(e,void 0,r,s,o,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,n,r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:s,description:o,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=n;return this._createRegisteredTool(e,s,o,i,a,c,{taskSupport:"forbidden"},u,r)}prompt(e,...n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof n[0]=="string"&&(r=n.shift());let s;n.length>1&&(s=n.shift());let o=n[0],i=this._createRegisteredPrompt(e,void 0,r,s,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,n,r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:s,description:o,argsSchema:i}=n,a=this._createRegisteredPrompt(e,s,o,i,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,n){return this.server.sendLoggingMessage(e,n)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},tR={type:"object",properties:{}};es={completion:{values:[],hasMore:!1}}});function sR(t){return Jd.parse(JSON.parse(t))}function eg(t){return JSON.stringify(t)+`
|
|
946
|
+
`}var rR,Ko,tg=j(()=>{Cn();rR=10*1024*1024,Ko=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??rR}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(`
|
|
947
|
+
`);if(e===-1)return null;let n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),sR(n)}clear(){this._buffer=void 0}}});import ng from"node:process";var Vo,rg=j(()=>{tg();Vo=class{constructor(e=ng.stdin,n=ng.stdout,r){this._stdin=e,this._stdout=n,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 Ko({maxBufferSize:r?.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(n=>{let r=eg(e);this._stdout.write(r)?n():this._stdout.once("drain",n)})}}});var sg,og=j(()=>{sg=[]});var hg={};Kc(hg,{AUTHORING_MCP_SERVER_NAME:()=>ug,AUTHORING_MCP_SERVER_VERSION:()=>dg,AUTHORING_RESOURCES:()=>lR,AUTHORING_TOOLS:()=>aR,AUTHORING_TOOLS_PUBLIC:()=>fg,buildAuthoringMcpServer:()=>pg,runAuthoringMcpServer:()=>cR});import{promises as oR}from"node:fs";import{resolve as ig}from"node:path";import{z as q}from"zod";function cg(){return lg??=import("../mcp/grounding.js").then(e=>e,()=>null),lg}function ve(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function iR(t,e={}){let n=e.fetchImpl??fetch;try{let r=await n(`${t.baseUrl.replace(/\/+$/,"")}/v1/extensions`,{headers:{Authorization:`Bearer ${t.token}`,Accept:"application/json"}});return r.ok?((await r.json()).extensions??[]).map(o=>o.hookId).filter(o=>typeof o=="string"):null}catch{return null}}async function pg(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let b=await gt(t.baseUrl);if(!b)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:b.baseUrl,token:b.token}}let n=t.grounding??{},r=await cg(),s=null;if(r)try{let b=await e();s={surface:"mcp-authoring",baseUrl:b.baseUrl,token:b.token}}catch{s=null}let o=r&&s?await r.loadActiveSources(s,n):[],i={...n,loadActiveSourcesImpl:async()=>o},a=[],c=[];if(r&&s){try{a=await r.listMcpPromptSkills(s,i)}catch{a=[]}try{c=(await r.listRecipesForSurface(s,i)).map(b=>({id:b.id,record_type:b.record_type,intent:b.intent}))}catch{c=[]}}let u=s?await iR(s,n):null,p=new Ho({name:ug,version:dg},r?{instructions:r.renderAuthoringInstructions({baseUrl:s?.baseUrl??t.baseUrl??"this instance",sources:o,recipeIntents:c,promptNames:a.map(b=>b.id),deployedExtensions:u,docsToken:n.docsToken??r.docsPublicToken()})}:void 0);if(r&&s){let b=s;for(let v of a)p.registerPrompt(v.id,{title:v.name,description:v.description},async()=>{let T=await r.getMcpPromptSkill(b,v.id,n);if(!T)throw new Error(`unknown prompt: ${v.id}`);return{description:T.description,messages:[{role:"user",content:{type:"text",text:(T.prompts??[]).join(`
|
|
948
|
+
|
|
949
|
+
`)}}]}})}p.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:b,token:v}=await e(),T=await fetch(`${b}/v1/catalog/records`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});if(!T.ok)throw new Error(`catalog fetch failed: ${T.status}`);return ve(await T.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:q.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:q.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:b,source:v})=>{let{baseUrl:T,token:R}=await e(),E=v?`?source=${encodeURIComponent(v)}`:"",I=await fetch(`${T}/v1/catalog/records/${encodeURIComponent(b)}${E}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(I.status===404)throw new Error(`unknown record type "${b}" \u2014 list them with catalog_get.`);if(!I.ok)throw new Error(`record anatomy fetch failed: ${I.status}`);return ve(await I.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:q.array(q.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:q.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:b,source:v})=>{let{baseUrl:T,token:R}=await e(),E=new URLSearchParams({types:b.join(",")});v&&E.set("source",v);let I=await fetch(`${T}/v1/catalog/columns?${E}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(I.status===404)throw new Error(`none of those record types resolved: ${b.join(", ")} \u2014 list them with catalog_get.`);if(!I.ok)throw new Error(`common columns fetch failed: ${I.status}`);return ve(await I.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:b,token:v}=await e(),T=await fetch(`${b}/v1/catalog/census`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});if(!T.ok)throw new Error(`catalog census failed: ${T.status}`);return ve(await T.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:q.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:q.enum(ag).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:q.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:b,kind:v,limit:T})=>{let{baseUrl:R,token:E}=await e(),I=new URLSearchParams({q:b});v&&I.set("kind",v),T!==void 0&&I.set("limit",String(T));let z=await fetch(`${R}/v1/catalog/objects?${I}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(!z.ok)throw new Error(`catalog object search failed: ${z.status}`);return ve(await z.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:q.enum(ag),externalId:q.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:b,externalId:v})=>{let{baseUrl:T,token:R}=await e(),E=await fetch(`${T}/v1/catalog/objects/${encodeURIComponent(b)}/${encodeURIComponent(v)}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(E.status===404)throw new Error(`unknown object ${b}:${v} \u2014 find it with search_catalog.`);if(!E.ok)throw new Error(`catalog object fetch failed: ${E.status}`);return ve(await E.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:q.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:q.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:b,limit:v})=>{let{baseUrl:T,token:R}=await e(),E=new URLSearchParams({q:b});v!==void 0&&E.set("limit",String(v));let I=await fetch(`${T}/v1/kb/search?${E}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(!I.ok)throw new Error(`kb search failed: ${I.status}`);return ve(await I.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:q.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:b})=>{let{baseUrl:v,token:T}=await e(),R=await fetch(`${v}/v1/kb/document/${encodeURIComponent(b)}`,{headers:{Authorization:`Bearer ${T}`,Accept:"application/json"}});if(!R.ok&&R.status!==404)throw new Error(`kb document fetch failed: ${R.status}`);return ve(await R.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:q.boolean().optional()}},async({recordsOnly:b})=>{let{baseUrl:v,token:T}=await e();return{content:[{type:"text",text:await It({baseUrl:v,token:T,recordsOnly:b})}]}}),p.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:q.string(),event:q.string().optional(),template:q.enum(["require-field","enforce-format","blank"]).optional(),field:q.string().optional(),regex:q.string().optional(),source:q.string().optional(),id:q.string().optional()}},async b=>{let v=kn("hook",{recordType:b.recordType,event:b.event,template:b.template,field:b.field,regex:b.regex,source:b.source,id:b.id});return ve({path:v.relativePath,content:v.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:q.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:q.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:q.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:q.string().optional().describe("Target record type (defaults to the trigger record type)."),event:q.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:q.string().optional()}},async b=>{let v=kn("conduit",{recordType:b.recordType,source:b.source,to:b.to,toRecordType:b.toRecordType,event:b.event,id:b.id});return ve({path:v.relativePath,content:v.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:q.string().describe("The extension TS source."),samplesDir:q.string().optional().describe('Samples directory (default "samples").')}},async({source:b,samplesDir:v})=>{let T=ig(process.cwd(),v??"samples"),R=await rr(T),E=await hs(b,R.map(z=>z.fixture)),I=E.filter(z=>!z.pass).length;return ve({total:E.length,passed:E.length-I,results:E})}),p.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:q.string(),recordType:q.string(),event:q.string(),source:q.string().describe('Adapter id or "standalone".'),sourceCode:q.string().describe("The verbatim extension TS."),extensionKind:q.string().optional()}},async b=>{let{baseUrl:v,token:T}=await e(),E=await new B({baseUrl:v,token:T}).deploy({id:b.id,recordType:b.recordType,event:b.event,source:b.source,sourceCode:b.sourceCode,extensionKind:b.extensionKind});return ve(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:q.string(),limit:q.number().int().positive().optional()}},async({id:b,limit:v})=>{let{baseUrl:T,token:R}=await e(),E=new B({baseUrl:T,token:R});return ve({id:b,logs:await E.logs(b,v)})}),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:b,token:v}=await e(),T=new B({baseUrl:b,token:v});return ve(await T.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:q.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:q.string().optional().describe("Display name (defaults to the slug)."),description:q.string().optional().describe("Short description.")}},async({slug:b,name:v,description:T})=>{let{baseUrl:R,token:E}=await e(),I=new B({baseUrl:R,token:E});return ve(await I.appsCreate({slug:b,name:v,description:T}))}),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:q.string().describe("App slug or id.")}},async({app:b})=>{let{baseUrl:v,token:T}=await e(),R=new B({baseUrl:v,token:T});return ve(await R.appsPull(b))}),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:q.string().describe("App slug or id."),files:q.record(q.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:q.string().optional().describe("Short note stored with the revision.")}},async({app:b,files:v,note:T})=>{let{baseUrl:R,token:E}=await e(),I=new B({baseUrl:R,token:E});return ve(await I.appsPush(b,v,{note:T}))});let h=q.object({name:q.string().describe("Field name (lowercase identifier)."),type:q.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:q.boolean().optional()}),k=q.object({slug:q.string().describe("Table slug; the physical table is cr_<slug>."),displayName:q.string().optional(),fields:q.array(h).describe("At least one field."),rowLevelOwner:q.boolean().optional().describe("Restrict non-admins to rows they created.")});return p.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:b,token:v}=await e(),T=new B({baseUrl:b,token:v});return ve(await T.tablesList())}),p.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:q.array(k),claimedBy:q.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:b,claimedBy:v})=>{let{baseUrl:T,token:R}=await e(),E=new B({baseUrl:T,token:R});return ve(await E.tablesPlan({tables:b,claimedBy:v}))}),p.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:q.array(k),claimedBy:q.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:b,claimedBy:v})=>{let{baseUrl:T,token:R}=await e(),E=new B({baseUrl:T,token:R});return ve(await E.tablesApply({tables:b,claimedBy:v}))}),p.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async b=>{let{baseUrl:v,token:T}=await e(),E=await(await fetch(`${v}/v1/catalog/records`,{headers:{Authorization:`Bearer ${T}`,Accept:"application/json"}})).text();return{contents:[{uri:b.href,mimeType:"application/json",text:E}]}}),p.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async b=>{let{baseUrl:v,token:T}=await e(),R=await It({baseUrl:v,token:T});return{contents:[{uri:b.href,mimeType:"text/plain",text:R}]}}),p.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async b=>{let v=ig(process.cwd(),"samples"),T=[];try{T=(await oR.readdir(v)).filter(E=>E.endsWith(".json"))}catch{T=[]}let R=await rr(v);return{contents:[{uri:b.href,mimeType:"application/json",text:JSON.stringify({files:T,samples:R.map(E=>E.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 b=>{let v=await cg(),T=[];if(v){let{baseUrl:R,token:E}=await e();T=await v.listRecipesForSurface({surface:"mcp-authoring",baseUrl:R,token:E},n)}return{contents:[{uri:b.href,mimeType:"application/json",text:JSON.stringify({recipes:T})}]}}),p}async function cR(t={}){let e=await pg(t),n=new Vo;await e.connect(n)}var ag,lg,ug,dg,fg,aR,lR,mg=j(()=>{Xm();rg();li();ds();Qt();yi();$i();og();ag=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];ug="turbobase-authoring",dg="0.1.0";fg=["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"],aR=[...fg,...sg],lR=["catalog:///","types://all","samples:///","recipes:///"]});li();ds();Qt();yi();import{spawn as Mc}from"node:child_process";import{promises as re}from"node:fs";import{homedir as uR}from"node:os";import{basename as yg,dirname as Zn,join as Ve,relative as Go,resolve as pe,sep as qc}from"node:path";import{Command as dR}from"commander";mi();import{promises as gu}from"node:fs";function hu(t,e){return e===t?"same-type-merge":"different-type-mint"}var yu=4;function bi(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=wn(t,"id"),n=wn(t,"on"),r=wn(t,"source"),s=wn(t,"recordType"),o=/to\s*:\s*\{([^}]*)\}/.exec(t)?.[1]??"",i=wn(o,"source"),a=wn(o,"recordType"),c=/cycleBudget\s*:\s*(\d+)/.exec(t);if(!e||!r||!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:n,fromSource:r,fromRecordType:s,toSource:i,toRecordType:a,cycleBudget:c?Number(c[1]):yu}}function wn(t,e){let n=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return n?n[2]:void 0}function Yg(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 bu(t,e,n="fixture"){let r=e.name??n,s=[],o;try{o=bi(t)}catch(c){return{fixtureName:r,conduit:Xg(),guards:s,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],logs:[],error:c instanceof Error?c.message:String(c)}}let i=Yg(e),a=Object.entries(e.atlasLinks??{}).map(([c,u])=>({key:c,resolved:u}));try{let c=await fs(t),p=!!(await nr(c,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 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)"}),!p)return{fixtureName:r,conduit:o,guards:s,whenPassed:p,atlasResolutions:a,wouldWriteBindings:[],logs:[]};let k=await nr(c,i,{member:"transform",timeoutMs:200}),b=k.effects.logs,v=k.effects.result;if(!v||typeof v!="object")throw new Error(`conduit ${o.id} transform returned no result (expected { patch, createdFrom? })`);let T=v,R=hu(o.fromRecordType,o.toRecordType),{wouldWriteBindings:E,masterAction:I}=Qg(o,R,e);return{fixtureName:r,conduit:o,guards:s,whenPassed:p,atlasResolutions:a,transformResult:T,applyBranch:R,wouldWriteBindings:E,masterAction:I,logs:b}}catch(c){return{fixtureName:r,conduit:o,guards:s,whenPassed:!1,atlasResolutions:a,wouldWriteBindings:[],logs:[],error:c instanceof Error?c.message:String(c)}}}function Qg(t,e,n){return e==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${n.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:n.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source: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:n.externalId,role:"replica",why:"firing source bound onto the created master (supplementary lineage; best-effort, may collide in a 1\u2192N fan)"}]}}function Xg(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",cycleBudget:yu}}async function wu(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 vu(t){let e=await gu.readFile(t,"utf8");return JSON.parse(e)}function Su(t){return gu.readFile(t,"utf8")}function ku(t,e){let n=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;if(!e)return t.whenPassed?`replay ${t.fixtureName} [${n.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`:`replay ${t.fixtureName} [${n.id}]: WHEN-FAILED (conduit short-circuited)`;let r=[];r.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),r.push(`conduit: ${n.id}`),r.push(`route: ${n.fromSource}.${n.fromRecordType} \u2192 ${n.toSource}.${n.toRecordType}${n.on?` on=${n.on}`:""}`),r.push(""),r.push("guards (dispatch order):");for(let s of t.guards){let o=s.status==="passed"?"\u2713":s.status==="failed"?"\u2717":"\u2298";r.push(` ${o} ${s.name} [${s.status}] \u2014 ${s.detail}`)}if(r.push(""),r.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)r.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let s of t.atlasResolutions)r.push(` ${s.key} \u2192 ${s.resolved===null?"null (no Atlas link \u2014 noted)":s.resolved}`);if(!t.whenPassed)return r.push(""),r.push("transform: SKIPPED (from.when gate did not fire)."),r.join(`
|
|
950
|
+
`);if(r.push(""),r.push("transform \u2192 patch:"),r.push(ey(JSON.stringify(t.transformResult?.patch??{},null,2)," ")),t.transformResult?.createdFrom&&r.push(` createdFrom: ${JSON.stringify(t.transformResult.createdFrom)}`),t.logs.length>0){r.push(""),r.push("conduit logs:");for(let s of t.logs)r.push(` [${s.level}] ${s.message}${s.meta?` ${JSON.stringify(s.meta)}`:""}`)}r.push(""),r.push(`apply-branch: ${t.applyBranch}`),r.push(` ${t.masterAction}`),r.push(""),r.push("bindings that WOULD be written (txn_source_link):");for(let s of t.wouldWriteBindings)r.push(` ${s.source} role=${s.role} external_id=${s.externalId??"null"} \u2014 ${s.why}`);return r.join(`
|
|
951
|
+
`)}function ey(t,e){return t.split(`
|
|
952
|
+
`).map(n=>e+n).join(`
|
|
953
|
+
`)}var ty="2026-01-01",_u="2026-01-01T00:00:00.000Z";function ny(t,e){let n=t.trim().toLowerCase();return n==="boolean"||n==="bool"?!1:n==="smallint"||n==="integer"||n==="int"||n==="int2"||n==="int4"||n==="int8"||n==="bigint"||n==="serial"||n==="bigserial"?1:n==="numeric"||n==="decimal"||n==="real"||n==="double precision"||n==="float4"||n==="float8"||n==="money"?0:n==="date"?ty:n.startsWith("timestamp")?_u:n.startsWith("time")?"00:00:00":n==="json"||n==="jsonb"?e&&/^cf_[a-z]{2}_/.test(e)?1074:e==="raw"||e==="attrs"?{id:"1074",lastModifiedDate:_u}:{}:n==="uuid"?"00000000-0000-0000-0000-000000000000":n==="array"||n.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function ry(t){let e={};for(let n of t.columns)e[n.name]=ny(n.pgType,n.name);return e}function sy(t,e={}){let n=e.event??"before_save";return{name:`${t.recordType} ${n} (generated)`,context:{recordType:t.recordType,event:n,source:t.source,payload:ry(t)},expect:e.expect??"pass"}}function $u(t,e={}){return t.map(n=>({recordType:n.recordType,fixture:sy(n,e)}))}import{promises as xu}from"node:fs";import{join as Tu,relative as oy,sep as iy}from"node:path";var ay=67324752,ly=33639248,cy=101010256,uy=(()=>{let t=new Uint32Array(256);for(let e=0;e<256;e++){let n=e;for(let r=0;r<8;r++)n=n&1?3988292384^n>>>1:n>>>1;t[e]=n>>>0}return t})();function dy(t){let e=4294967295;for(let n=0;n<t.length;n++)e=uy[(e^t[n])&255]^e>>>8;return(e^4294967295)>>>0}async function py(t){let e=[];async function n(r){let s=await xu.readdir(r,{withFileTypes:!0});for(let o of s){let i=Tu(r,o.name);o.isDirectory()?await n(i):o.isFile()&&e.push(oy(t,i).split(iy).join("/"))}}return await n(t),e.sort(),e}async function Ru(t){let e=await py(t),n=[],r=[],s=0;for(let a of e){let c=Buffer.from(a,"utf8"),u=await xu.readFile(Tu(t,a)),p=dy(u),h=Buffer.alloc(30+c.length);h.writeUInt32LE(ay,0),h.writeUInt16LE(20,4),h.writeUInt16LE(0,6),h.writeUInt16LE(0,8),h.writeUInt32LE(p,14),h.writeUInt32LE(u.length,18),h.writeUInt32LE(u.length,22),h.writeUInt16LE(c.length,26),c.copy(h,30),n.push(h,u);let k=Buffer.alloc(46+c.length);k.writeUInt32LE(ly,0),k.writeUInt16LE(20,4),k.writeUInt16LE(20,6),k.writeUInt16LE(0,10),k.writeUInt32LE(p,16),k.writeUInt32LE(u.length,20),k.writeUInt32LE(u.length,24),k.writeUInt16LE(c.length,28),k.writeUInt32LE(s,42),c.copy(k,46),r.push(k),s+=h.length+u.length}let o=Buffer.concat(r),i=Buffer.alloc(22);return i.writeUInt32LE(cy,0),i.writeUInt16LE(e.length,8),i.writeUInt16LE(e.length,10),i.writeUInt32LE(o.length,12),i.writeUInt32LE(s,16),{buffer:Buffer.concat([...n,o,i]),fileCount:e.length}}function fy(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":"hook"}function ms(t,e){let n=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return n?n[2]:void 0}function hy(t){let e=Eu(t,"from"),n=Eu(t,"to");return{fromSource:e?ms(e,"source"):void 0,fromRecordType:e?ms(e,"recordType"):void 0,toSource:n?ms(n,"source"):void 0,toRecordType:n?ms(n,"recordType"):void 0}}function Eu(t,e){let n=new RegExp(`\\b${e}\\s*:\\s*\\{`).exec(t);if(!n)return null;let r=0,s=n.index+n[0].length-1;for(let o=s;o<t.length;o+=1){let i=t[o];if(i==="{")r+=1;else if(i==="}"&&(r-=1,r===0))return t.slice(s+1,o)}return null}function my(t){let e=/idempotencyKey\s*:/.exec(t);if(!e)return null;let n=e.index+e[0].length,r=0,s=null,o=n;for(;o<t.length;o+=1){let c=t[o];if(s){c==="\\"?o+=1:c===s&&(s=null);continue}if(c==="'"||c==='"'||c==="`"){s=c;continue}if(c==="("||c==="{"||c==="[")r+=1;else if(c===")"||c==="}"||c==="]"){if(r===0)break;r-=1}else if(c===","&&r===0)break}let i=t.slice(n,o),a=i.indexOf("=>");return a>=0?i.slice(a+2):i}function gy(t,e){let n=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return n?Number(n[1]):void 0}function yy(t){return/\bcreatedFrom\b/.test(t)}function Pu(t){let e=fy(t),n=[];if(e==="hook")return{kind:e,warnings:n};let{fromSource:r,toSource:s,fromRecordType:o,toRecordType:i}=hy(t);r&&s&&r===s&&n.push({rule:"same-source-conduit",message:`from.source and to.source are both '${r}' \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=my(t);if(a!==null){let u=/\bexternalId\b/.test(a),p=/\bfromSource\b/.test(a);!u&&!p&&n.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&&!yy(t)&&n.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 c=gy(t,"cycleBudget");return c!==void 0&&(c<1?n.push({rule:"cycle-budget-too-low",message:`cycleBudget=${c} is below 1 \u2014 the cycle fuse trips before the first hop (hop 0 >= budget), so this conduit can never fire.`,fix:"Set cycleBudget to at least 1 (the engine default is 4, a sane range is 1\u201320)."}):c>20&&n.push({rule:"cycle-budget-too-high",message:`cycleBudget=${c} is far above the 20 ceiling \u2014 the max-hop safety fuse is effectively disarmed, so a misconfigured conduit pair can bounce a record dozens of times before anything stops it.`,fix:"Lower cycleBudget into the 1\u201320 range (the engine default is 4); a legitimate chain rarely needs more than a handful of hops."})),{kind:e,warnings:n}}function Au(t,e,n={}){let r=n.warn??(a=>a),s=n.ok??(a=>a),o=n.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(`
|
|
954
|
+
`);for(let a of e.warnings)i.push(` ${r("WARN")} ${o(`[${a.rule}]`)} ${a.message}`),i.push(` ${o("\u2192 fix:")} ${a.fix}`);return i.push(`
|
|
955
|
+
lint: ${r(`${e.warnings.length} warning(s).`)}`),i.join(`
|
|
956
|
+
`)}function Iu(t){return t.cases.filter(e=>e.status==="failed").length}function or(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function by(t){let e=Iu(t),n=[];n.push('<?xml version="1.0" encoding="UTF-8"?>'),n.push(`<testsuite name="${or(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let r of t.cases){let s=` <testcase name="${or(r.name)}"`;if(r.status==="passed"){n.push(`${s} />`);continue}n.push(`${s}>`);let o=r.detail??"failed",i=r.type?` type="${or(r.type)}"`:"";n.push(` <failure${i} message="${or(o)}">${or(o)}</failure>`),n.push(" </testcase>")}return n.push("</testsuite>"),`${n.join(`
|
|
957
957
|
`)}
|
|
958
|
-
`}function
|
|
959
|
-
`}function
|
|
960
|
-
`)}function
|
|
961
|
-
`)}function
|
|
958
|
+
`}function wy(t){let e={suite:t.name,tests:t.cases.length,failures:Iu(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
|
|
959
|
+
`}function gs(t,e){return e==="junit"?by(t):wy(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`},vn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Je={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},Cu=/\x1b\[[0-9;]*m/g;function $t(t){return t.replace(Cu,"").length}function wi(t,e){return e<=0?1:Math.max(1,Math.ceil($t(t)/e))}function vy(){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 vi=vy();function qe(){return vi}function Si(t){vi=t}function it(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function Ze(t,e){return vi?`${t}${e}${De.reset}`:e}var w={bold:t=>Ze(De.bold,t),dim:t=>Ze(De.dim,t),red:t=>Ze(De.red,t),green:t=>Ze(De.green,t),yellow:t=>Ze(De.yellow,t),blue:t=>Ze(De.blue,t),magenta:t=>Ze(De.magenta,t),cyan:t=>Ze(De.cyan,t),grey:t=>Ze(De.grey,t)};var Ne={success:t=>`${w.green("\u2713")} ${t}`,error:t=>`${w.red("\u2716")} ${t}`,warn:t=>`${w.yellow("\u26A0")} ${t}`,info:t=>`${w.dim("\xB7")} ${t}`,step:t=>`${w.cyan("\u25B8")} ${t}`},Ot={add:t=>w.green(`+ ${t}`),change:t=>w.yellow(`~ ${t}`),destroy:t=>w.red(`- ${t}`)},Sy=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),ky=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),_y=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function Sn(t){let e=t.toLowerCase();return Sy.has(e)?w.green(t):ky.has(e)?w.red(t):_y.has(e)?w.yellow(t):t}function Nt(t,e=[]){let n=Math.max($t(t),...e.map($t),0),r=n+2,s=w.cyan(Je.v),o=a=>` ${a}${" ".repeat(n-$t(a))} `,i=[w.cyan(`${Je.tl}${Je.h.repeat(r)}${Je.tr}`),`${s}${w.bold(o(t))}${s}`];if(e.length){i.push(`${w.cyan(Je.ml)}${w.dim(Je.h.repeat(r))}${w.cyan(Je.mr)}`);for(let a of e)i.push(`${s}${o(a)}${s}`)}return i.push(w.cyan(`${Je.bl}${Je.h.repeat(r)}${Je.br}`)),i.join(`
|
|
960
|
+
`)}function Xt(t,e={}){let n=e.indent??" ",r=e.gap??" ",s=e.head?[e.head,...t]:t,o=Math.max(0,...s.map(u=>u.length)),i=[];for(let u=0;u<o;u+=1)i[u]=Math.max(0,...s.map(p=>$t(p[u]??"")));let a=u=>{let p=u.map((h,k)=>{let b=h??"";return k===u.length-1?b:b+" ".repeat(Math.max(0,i[k]-$t(b)))});return n+p.join(r)},c=[];e.head&&(c.push(a(e.head.map(u=>w.bold(u)))),c.push(a(e.head.map((u,p)=>w.dim("\u2500".repeat(i[p]??$t(u)))))));for(let u of t)c.push(a(u));return c.join(`
|
|
961
|
+
`)}function ki(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(r=>Ze(De.cyan,r)).join(`
|
|
962
962
|
`):e.join(`
|
|
963
963
|
`)}
|
|
964
|
-
${
|
|
965
|
-
`),i}catch(i){throw o(),
|
|
966
|
-
`),i}}function
|
|
967
|
-
`),o()},status(c){
|
|
968
|
-
`)},stop(){clearInterval(a),i(),Ye(Se.showCursor)}}}function
|
|
969
|
-
`),a(`${
|
|
970
|
-
`),a(Se.hideCursor);let
|
|
971
|
-
`),R+=
|
|
964
|
+
${w.dim(` ${t}`)}`}var Ye=t=>{process.stderr.write(t)};function ys(){return qe()&&process.stderr.isTTY===!0}function Ou(t,e=15){let n=Math.max(0,Math.min(100,t??0)),r=Math.round(n/100*e);return`${"\u2588".repeat(r)}${w.dim("\u2591".repeat(e-r))}`}async function ee(t,e){let n=ys(),r=0,s;n&&(Ye(Se.hideCursor),s=setInterval(()=>{Ye(`${Se.col0}${Se.clearLine}${w.magenta(vn[r++%vn.length])} ${t}`)},80));let o=()=>{s&&clearInterval(s),n&&Ye(`${Se.col0}${Se.clearLine}${Se.showCursor}`)};try{let i=await e();return o(),n&&Ye(`${Ne.success(t)}
|
|
965
|
+
`),i}catch(i){throw o(),n&&Ye(`${Ne.error(t)}
|
|
966
|
+
`),i}}function _i(t){let e=0,n={stage:"queued"},r=!1,s=()=>{let c=w.magenta(vn[e%vn.length]),u=w.cyan(n.stage),p=n.runStatus?` ${w.dim(`(${n.runStatus})`)}`:"",h=`${String(Math.round(n.percent??0)).padStart(3)}%`;return`${c} ${t} ${w.dim("\u25B8")} ${u}${p} ${Ou(n.percent)} ${h}`},o=()=>{Ye(`${Se.col0}${Se.clearLine}${s()}`),r=!0},i=()=>{r&&Ye(`${Se.col0}${Se.clearLine}`),r=!1};Ye(Se.hideCursor);let a=setInterval(()=>{e+=1,o()},80);return{log(c){i(),Ye(`${c}
|
|
967
|
+
`),o()},status(c){n=c,o()},done(c){clearInterval(a),i(),Ye(Se.showCursor);let u=c.stage!=="failed",p=`${t} ${w.dim("\u25B8")} ${$y(c.stage)}${c.runStatus?` (${c.runStatus})`:""}`;Ye(`${u?Ne.success(p):Ne.error(p)}
|
|
968
|
+
`)},stop(){clearInterval(a),i(),Ye(Se.showCursor)}}}function $y(t){return t==="completed"?w.green(t):t==="failed"?w.red(t):w.cyan(t)}function at(t,e,n={}){return new Promise((r,s)=>{let o=e.findIndex(T=>!T.disabled);if(o===-1){s(new Error("no selectable options"));return}let i=n.defaultIndex!==void 0&&!e[n.defaultIndex]?.disabled?n.defaultIndex:o,a=T=>{process.stderr.write(T)},c=process.stdin,u=c.isRaw;c.setRawMode?.(!0),c.resume(),a(`${w.bold(w.cyan("?"))} ${w.bold(t)}
|
|
969
|
+
`),a(`${w.dim(" (\u2191/\u2193 to move, enter to select, ctrl+c to abort)")}
|
|
970
|
+
`),a(Se.hideCursor);let p=0,h=()=>{let T=process.stderr.columns??process.stdout.columns??80;p>0&&(a(Se.cursorUp(p)),a(Se.clearToEnd));let R=0;for(let E=0;E<e.length;E+=1){let I=e[E],z=E===i,ie=z?w.cyan("\u25B6"):" ",H=I.disabled?w.grey(I.label):z?w.bold(w.cyan(I.label)):I.label,Ce=I.description?` ${w.dim(I.description)}`:"",Ue=` ${ie} ${H}${Ce}`;a(`\r${Ue}
|
|
971
|
+
`),R+=wi(Ue,T)}p=R},k=()=>{c.removeListener("data",v),c.setRawMode?.(u??!1),c.pause(),a(Se.showCursor)},b=T=>{let R=i;for(let E=0;E<e.length;E+=1)if(R=(R+T+e.length)%e.length,!e[R].disabled){i=R;return}},v=T=>{let R=T.toString("utf8");if(R===""||R==="q"){k(),a(`
|
|
972
972
|
`),s(new Error("aborted"));return}if(R==="\r"||R===`
|
|
973
|
-
`){let I=e[i];if(I.disabled)return;
|
|
974
|
-
`)}),s=
|
|
975
|
-
`)});if(e.retry){let s=await t.retryBinding(e.retry);return
|
|
976
|
-
binding: ${
|
|
973
|
+
`){let I=e[i];if(I.disabled)return;k(),r(I.value);return}if(R==="\x1B[A"||R==="k"){b(-1),h();return}if(R==="\x1B[B"||R==="j"){b(1),h();return}let E=Number(R);Number.isFinite(E)&&E>=1&&E<=e.length&&!e[E-1].disabled&&(i=E-1,h())};c.on("data",v),h()})}function ju(t,e){return`${Sn(t)}${" ".repeat(Math.max(0,e-t.length))}`}var xy=t=>new Promise(e=>setTimeout(e,t));function Nu(t){let e=t.toRecordType?`${t.toSource}/${t.toRecordType}`:t.toSource,n=t.reason?` reason="${t.reason}"`:"",r=t.fromExternalId?` ext=${t.fromExternalId}`:"",s=t.toMasterTable&&t.toMasterRowId?` master=${t.toMasterTable}/${t.toMasterRowId}`:"";return`[${t.updatedAt}] ${ju(t.state,9)} ${t.conduitId} \u2192 ${e}${r} hop=${t.hop}${s}${n}`}async function Lu(t,e,n={}){let r=n.sink??(p=>{process.stdout.write(`${p}
|
|
974
|
+
`)}),s=n.sleep??xy,o=n.intervalMs??2e3,i=await t.conduitEvents(e,{limit:n.limit??100});if(i.length===0&&!n.follow)return r(`logs: no conduit_event rows for ${e}.`),0;let a=0,c="";for(let p of[...i].reverse())r(Nu(p)),a+=1,p.updatedAt>c&&(c=p.updatedAt);if(!n.follow)return a;let u=n.maxPolls??Number.POSITIVE_INFINITY;for(let p=0;p<u;p+=1){await s(o);let h=await t.conduitEvents(e,{since:c||void 0,limit:200});for(let k of[...h].reverse())r(Nu(k)),a+=1,k.updatedAt>c&&(c=k.updatedAt)}return a}function Ty(t){let e=t.externalId??"\u2014",n=t.createdByConduit?` via=${t.createdByConduit}`:"",r=t.lastError?` last_error="${t.lastError}"`:"";return`${t.id} ${ju(t.writeStatus,9)} ${t.sourceSystem}/${e} role=${t.role} master=${t.masterTable}/${t.masterRowId}${n}${r}`}async function zu(t,e={}){let n=e.sink??(s=>{process.stdout.write(`${s}
|
|
975
|
+
`)});if(e.retry){let s=await t.retryBinding(e.retry);return n(`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 r=await t.bindings({status:e.status,limit:e.limit});if(r.length===0)return n(e.status?`binding: no bindings with write_status='${e.status}'.`:"binding: no bindings."),{mode:"list",count:0};for(let s of r)n(Ty(s));return n(`
|
|
976
|
+
binding: ${r.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:r.length}}$i();function Du(t,e={}){return t.learningIngestError?{level:"warn",message:`warning: learning ingest was not queued (${t.learningIngestError}). The version is live, but the findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT read. Re-deploy to retry.`}:t.learningIngestTaskId?t.learningSourceRev===null?{level:"warn",message:"warning: this app has no pushed source, so the ingest has nothing to read. The findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT ingested \u2014 deploy uploads the built bundle, `apps push` records the markdown. Run `turbobase apps push <app> .`, then deploy again."}:typeof t.learningSourceRev=="number"?e.localDocsModifiedAt&&t.learningSourceAt&&e.localDocsModifiedAt.getTime()>Date.parse(t.learningSourceAt)?{level:"warn",message:`warning: learning ingest queued (task ${t.learningIngestTaskId}), but it reads source rev ${t.learningSourceRev} and your standing markdown has changed since that push. Those findings will NOT be ingested. Run \`turbobase apps push <app> .\`, then deploy again.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}) \u2014 reading source rev ${t.learningSourceRev}.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}).`}:null}var xi=".github/workflows/turbobase-release-deploy.yml",Ay=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
977
977
|
# Turbobase release deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR repo)
|
|
978
978
|
#
|
|
979
979
|
# Epic #775 "GitHub is just a link": Turbobase hosts nothing and clones nothing.
|
|
@@ -1075,7 +1075,7 @@ jobs:
|
|
|
1075
1075
|
--ref "\${{ github.sha }}" \\
|
|
1076
1076
|
--project . \\
|
|
1077
1077
|
--follow
|
|
1078
|
-
`,
|
|
1078
|
+
`,Iy=".github/workflows/turbobase-tables-plan.yml",Cy=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1079
1079
|
# Turbobase table check \u2014 REUSABLE TEMPLATE (drop this into YOUR app repo)
|
|
1080
1080
|
#
|
|
1081
1081
|
# Runs \`turbobase tables plan\` against your instance on every pull request. It
|
|
@@ -1150,14 +1150,14 @@ jobs:
|
|
|
1150
1150
|
# field and at what type. Writes nothing to the instance either way.
|
|
1151
1151
|
- name: Plan the declared tables
|
|
1152
1152
|
run: turbobase tables plan .
|
|
1153
|
-
`;function
|
|
1154
|
-
`).map(i=>i.trim()).filter(i=>i!==""&&!i.startsWith("#")).map(
|
|
1153
|
+
`;function qu(){return[{path:xi,content:Ay}]}function Mu(){return[{path:Iy,content:Cy}]}var Oy=[".mcp.json"];function Fu(t,e=Oy){let n=i=>i.replace(/^\//,""),r=new Set(t.split(`
|
|
1154
|
+
`).map(i=>i.trim()).filter(i=>i!==""&&!i.startsWith("#")).map(n)),s=e.filter(i=>!r.has(n(i)));return s.length===0?null:`${t===""||t.endsWith(`
|
|
1155
1155
|
`)?t:`${t}
|
|
1156
1156
|
`}
|
|
1157
1157
|
# Added by the Turbobase scaffold.
|
|
1158
1158
|
${s.join(`
|
|
1159
1159
|
`)}
|
|
1160
|
-
`}var
|
|
1160
|
+
`}var Ny=`# Turbobase Extensions \u2014 extension project
|
|
1161
1161
|
|
|
1162
1162
|
This directory authors **Turbobase extensions** (hooks today; conduits later)
|
|
1163
1163
|
against a live instance. The \`turbobase\` CLI is the engine; Claude Code drives it
|
|
@@ -1226,8 +1226,8 @@ order is the signal, and it is the part the product team reads first.
|
|
|
1226
1226
|
|
|
1227
1227
|
Do this WITHOUT being asked \u2014 treat it as part of finishing a task, like
|
|
1228
1228
|
updating a test. It is checked into the repo so the whole team sees it.
|
|
1229
|
-
`,
|
|
1230
|
-
`;function
|
|
1229
|
+
`,jy=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)+`
|
|
1230
|
+
`;function Ly(t){return`---
|
|
1231
1231
|
name: generate-types
|
|
1232
1232
|
description: Regenerate ${t} from the signed-in instance's catalog. Use before authoring or whenever the schema may have changed.
|
|
1233
1233
|
---
|
|
@@ -1238,7 +1238,7 @@ write \`${t}\`. Import the generated record interfaces for typed rows.
|
|
|
1238
1238
|
|
|
1239
1239
|
The OpenAPI half is cookie-session-gated, so a headless run with a stored token
|
|
1240
1240
|
degrades to record shapes only and says so \u2014 that is expected, not a failure.
|
|
1241
|
-
`}var
|
|
1241
|
+
`}var zy=`---
|
|
1242
1242
|
name: mock-test
|
|
1243
1243
|
description: Dry-run a hook against samples/ fixtures using the production sandbox. Use after editing a hook, before deploy.
|
|
1244
1244
|
---
|
|
@@ -1247,7 +1247,7 @@ Run \`turbobase ext test hooks/<file>.ts\`. It bundles the hook through the same
|
|
|
1247
1247
|
self-contained-fence esbuild + isolated-vm the live runtime uses, then runs it
|
|
1248
1248
|
against every \`samples/*.json\` fixture and reports pass/reject per sample. Add a
|
|
1249
1249
|
fixture for each branch (a passing record and a rejecting record).
|
|
1250
|
-
`,
|
|
1250
|
+
`,Uy=`---
|
|
1251
1251
|
name: deploy
|
|
1252
1252
|
description: Deploy a hook to your instance. Use only after mock-test is green.
|
|
1253
1253
|
---
|
|
@@ -1255,7 +1255,7 @@ description: Deploy a hook to your instance. Use only after mock-test is green.
|
|
|
1255
1255
|
Run \`turbobase ext deploy hooks/<file>.ts\`. It POSTs the hook source to
|
|
1256
1256
|
/v1/extensions with the stored admin PAT; the hook lands **active**. Re-deploying
|
|
1257
1257
|
the same id overwrites it (idempotent). Tail with \`turbobase ext logs <id>\`.
|
|
1258
|
-
`;function
|
|
1258
|
+
`;function Dy(t){return`# ${t} \u2014 Turbobase app
|
|
1259
1259
|
|
|
1260
1260
|
This directory is a **hosted Turbobase app**: a Vite + React + TS SPA served
|
|
1261
1261
|
same-origin by the instance at \`/a/${t}\`. The \`turbobase\` CLI ships it; you
|
|
@@ -1440,7 +1440,7 @@ a test. \`turbobase apps deploy\` reads both files and queues what it finds for
|
|
|
1440
1440
|
review, so what you write reaches the knowledge base and the product team instead
|
|
1441
1441
|
of evaporating at the end of the session. Keep the section headings exactly as
|
|
1442
1442
|
they are \u2014 the ingest finds entries by heading, not by filename.
|
|
1443
|
-
`}var
|
|
1443
|
+
`}var qy="---\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",My=`---
|
|
1444
1444
|
name: ship-app
|
|
1445
1445
|
description: Push the app's source to the instance and deploy it live. Use once the app has been previewed and works.
|
|
1446
1446
|
---
|
|
@@ -1483,7 +1483,7 @@ Text files only \u2014 \`push\` skips \`node_modules/\`, \`dist/\`, \`build/\`,
|
|
|
1483
1483
|
non-text, so images and fonts belong in the build pipeline or object storage, not
|
|
1484
1484
|
the source tree. \`INSTANCE-LEARNINGS.md\` and \`TURBOBASE-FEEDBACK.md\` sit at the
|
|
1485
1485
|
project root and DO travel \u2014 deploy reads them.
|
|
1486
|
-
`;function
|
|
1486
|
+
`;function By(t){return`---
|
|
1487
1487
|
name: record-learning
|
|
1488
1488
|
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.
|
|
1489
1489
|
---
|
|
@@ -1528,7 +1528,7 @@ the product team acts on first, so it is maintained with the entries.
|
|
|
1528
1528
|
|
|
1529
1529
|
Do not reword the three headings. The deploy-side ingest recognises entries by
|
|
1530
1530
|
heading, not by filename, so a renamed section is a finding nobody receives.
|
|
1531
|
-
`}function
|
|
1531
|
+
`}function Fy(t){return`# What this instance's source system actually does
|
|
1532
1532
|
|
|
1533
1533
|
Findings from ${t?`building the ${t.slug} app against the live mirror`:"authoring extensions against the live instance"}.
|
|
1534
1534
|
Written for the knowledge base, and **everything here is verified against real
|
|
@@ -1621,10 +1621,33 @@ finding has not been handed to the knowledge base yet.
|
|
|
1621
1621
|
\`entity\` by \`entity_type\`", not "the entity table is shared". Keep it short;
|
|
1622
1622
|
it is paying for space in every prompt.
|
|
1623
1623
|
|
|
1624
|
-
|
|
1625
|
-
|
|
1624
|
+
GROUP THEM UNDER A \`###\` HEADING. The unit that gets written is a SKILL, and
|
|
1625
|
+
the rules under one heading become ONE skill, named after that heading:
|
|
1626
|
+
|
|
1627
|
+
### Reading this mirror safely
|
|
1628
|
+
|
|
1629
|
+
1. **Always filter \`entity\` by \`entity_type\`.** The table is shared.
|
|
1630
|
+
2. **Never read lines out of a header row's \`raw\`.** Embed the line table.
|
|
1631
|
+
|
|
1632
|
+
That heading is the only place the grouping can come from \u2014 you are the one
|
|
1633
|
+
who knows which rules an agent has to apply together. WITHOUT headings every
|
|
1634
|
+
rule becomes its own skill, named from the first ~120 characters of its own
|
|
1635
|
+
text and slugged off whichever \`identifier\` it happens to mention first. A
|
|
1636
|
+
session that recorded 22 rules that way produced 21 separate rows, which is
|
|
1637
|
+
more than anyone will read, so none of them got published and none of them
|
|
1638
|
+
applied. Five headings would have produced five reviewable skills.
|
|
1639
|
+
|
|
1640
|
+
Aim for a heading that names the SUBJECT the rules share ("Reading this
|
|
1641
|
+
mirror safely"), not one rule's specifics.
|
|
1642
|
+
|
|
1643
|
+
WHAT HAPPENS NEXT. \`turbobase skills push\` writes these as DRAFT rules,
|
|
1644
|
+
visible to Everyone on the instance once published. Nothing is injected until
|
|
1645
|
+
someone publishes them \u2014 either an admin in Settings \u203A Skills, or a PAT
|
|
1646
|
+
carrying the \`skills:publish\` scope running \`turbobase skills publish <slug>\`
|
|
1647
|
+
and then \`turbobase skills release\`. \`turbobase skills list\` shows what is
|
|
1648
|
+
already live, which is worth reading before adding another rule. -->
|
|
1626
1649
|
|
|
1627
|
-
`}function
|
|
1650
|
+
`}function Hy(t){return`# Feedback for the Turbobase team \u2014 what ${t?`building the ${t.slug} app`:"authoring extensions here"} actually hit
|
|
1628
1651
|
|
|
1629
1652
|
Everything below cost time or produced a wrong result. Not speculation, and not
|
|
1630
1653
|
a wishlist. This file is about the PLATFORM \u2014 scaffold, catalog, CLI, MCP, API.
|
|
@@ -1680,7 +1703,7 @@ Expected / happened / cost / fix.
|
|
|
1680
1703
|
|
|
1681
1704
|
<!-- Rank the findings above by how much time each would have saved. Position is
|
|
1682
1705
|
the signal \u2014 1 is the biggest win. -->
|
|
1683
|
-
`}function
|
|
1706
|
+
`}function Ky(t,e){let n=e?`
|
|
1684
1707
|
# INSTANCE.md \u2014 the instance's grounding brief (see CLAUDE.md). Reuse the
|
|
1685
1708
|
# --records focus a previous run stamped into the file, so a refresh never
|
|
1686
1709
|
# narrows what an agent deliberately widened.
|
|
@@ -1693,35 +1716,38 @@ turbobase project grounding \${records:+--records "$records"} --query ${JSON.str
|
|
|
1693
1716
|
# session still starts (types just won't refresh).
|
|
1694
1717
|
set -euo pipefail
|
|
1695
1718
|
turbobase project types -o ${t} >/dev/null 2>&1 || echo "turbobase: types refresh skipped (not signed in?)" >&2
|
|
1696
|
-
${
|
|
1697
|
-
`,
|
|
1719
|
+
${n}`}var Vy=JSON.stringify({hooks:{SessionStart:[{hooks:[{type:"command",command:"bash .claude/hooks/session-start-refresh-types.sh"}]}]}},null,2)+`
|
|
1720
|
+
`,Bu="",Gy=t=>`node_modules/
|
|
1698
1721
|
|
|
1699
1722
|
# Holds a live personal access token (written by \`turbobase ${t?"apps":"project"} init\`).
|
|
1700
1723
|
.mcp.json
|
|
1701
1724
|
|
|
1702
1725
|
.DS_Store
|
|
1703
|
-
`;function
|
|
1704
|
-
`))
|
|
1705
|
-
`)}),
|
|
1706
|
-
`)},
|
|
1707
|
-
`)};function $(t){
|
|
1708
|
-
|
|
1709
|
-
`;await
|
|
1710
|
-
`);for(let
|
|
1711
|
-
`)),x(
|
|
1712
|
-
`))}catch(c){if(c instanceof
|
|
1713
|
-
`))
|
|
1714
|
-
`)),x(
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
`).
|
|
1720
|
-
|
|
1721
|
-
|
|
1726
|
+
`;function Ti(t={}){let e=jy.replace(/__BASE_URL__/g,t.baseUrl??"https://<slug>.turbobase.app").replace(/__PAT__/g,t.token??"tb_pat_\u2026"),n=!!t.appSlug,r=n?"src/types.ts":"types.ts",s=n?{slug:t.appSlug}:void 0,o=[{path:".mcp.json",content:e,mode:384},{path:".gitignore",content:Gy(n)},{path:"INSTANCE-LEARNINGS.md",content:Fy(s)},{path:"TURBOBASE-FEEDBACK.md",content:Hy(s)},{path:".claude/settings.json",content:Vy},{path:".claude/skills/generate-types/SKILL.md",content:Ly(r)},{path:".claude/skills/record-learning/SKILL.md",content:By(s)},{path:".claude/hooks/session-start-refresh-types.sh",content:Ky(r,s),executable:!0}];return n?[{path:"CLAUDE.md",content:Dy(t.appSlug)},...o,{path:".claude/skills/preview-app/SKILL.md",content:qy},{path:".claude/skills/ship-app/SKILL.md",content:My},...Mu()]:[{path:"CLAUDE.md",content:Ny},...o,{path:".claude/skills/mock-test/SKILL.md",content:zy},{path:".claude/skills/deploy/SKILL.md",content:Uy},{path:"hooks/.gitkeep",content:Bu},{path:"samples/.gitkeep",content:Bu}]}import{promises as Vu}from"node:fs";import{resolve as Yy}from"node:path";ds();Qt();var Wy=t=>new Promise(e=>setTimeout(e,t));function Hu(t){return t.stage==="completed"||t.stage==="failed"}function Jy(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function Zy(t,e,n){let r=t.outputTail??"";if(r&&r!==e){let o=(r.startsWith(e)?r.slice(e.length):r).replace(/\n+$/,"");if(o)for(let i of o.split(`
|
|
1727
|
+
`))n(i)}return r}async function Ri(t,e={}){let n=e.sink??(k=>{process.stdout.write(`${k}
|
|
1728
|
+
`)}),r=e.sleep??Wy,s=e.intervalMs??2e3,o=e.maxPolls??Number.POSITIVE_INFINITY,i=e.onStage??(k=>n(Jy(k))),a=e.onPoll,c="",u="",p=k=>{a?.(k),k.stage!==u&&i(k),c=Zy(k,c,n),u=k.stage},h=await t();if(p(h),Hu(h))return h;for(let k=0;k<o;k+=1)if(await r(s),h=await t(),p(h),Hu(h))return h;return h}var x=t=>{process.stdout.write(`${t}
|
|
1729
|
+
`)},Z=t=>{process.stderr.write(`${t}
|
|
1730
|
+
`)};function $(t){Z(w.red(`turbobase: ${t}`)),process.exit(1)}var ir=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function Ku(t,e){let n=e.json===!0||typeof e.reporter=="string";(t.color===!1||n)&&Si(!1)}async function V(t){let e=await gt(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let n=await Ct();if(t){let r=n.length?` Stored instances: ${n.map(s=>s.baseUrl).join(", ")}.`:"";$(`not signed in to ${We(t)}.${r} Run \`turbobase auth login --base-url ${We(t)} --token tb_pat_\u2026\`.`)}if(n.length===0&&$("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),it())try{let r=await at("Multiple instances stored \u2014 pick the active one:",n.map(o=>({value:o.baseUrl,label:o.baseUrl,description:`updated ${o.updatedAt}`})));await us(r);let s=await gt();if(s)return{baseUrl:s.baseUrl,token:s.token}}catch{}$(`multiple instances stored (${n.map(r=>r.baseUrl).join(", ")}) and no active default. Run \`turbobase auth use <base-url>\` to pick one, or pass --base-url.`)}function ce(t,e,n){if(!(t instanceof se)||t.status!==403)return;t.body?.error==="approval_required"&&$(`${n} denied (403): an approval-gated deploy needs a recorded approval \u2014 pass --approved-by <email>.`),$(`${n} forbidden (403) \u2014 the stored PAT lacks the '${e}' scope. Re-run \`turbobase auth login\` with a token that has it.`)}async function Ei(t,e,n){let r=n?Number(n):void 0;if(ys()){let o=_i(e),i;try{i=await Ri(t,{intervalMs:r,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(),$(`${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 Ri(t,{sink:x,intervalMs:r})}catch(o){$(`${e} --follow failed: ${o instanceof Error?o.message:String(o)}`)}s.stage==="failed"&&$(`${e} failed${s.runStatus?` (${s.runStatus})`:""}.`),x(`${e} ${s.stage}.`)}var Qy=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function Xy(t){try{let e=await Vu.readFile(t,"utf8");return Qy.exec(e)?.[1]??null}catch{return null}}function Gu(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:n,token:r}=await V(e.baseUrl),s=Yy(process.cwd(),e.out),o=e.since?.trim()||await Xy(s),i=new URLSearchParams;o&&i.set("since",o);let a=i.toString(),c=await fetch(`${n}/v1/catalog/adopt-notes${a?`?${a}`:""}`,{headers:{Authorization:`Bearer ${r}`,Accept:"application/json"}});c.ok||$(`adopt fetch failed: GET /v1/catalog/adopt-notes \u2192 ${c.status}`);let u=await c.json();if(!u.available){x(`${n} ships no release notes to adopt from (nothing written).`);return}let p=u.releases.reduce((b,v)=>b+v.items.length,0);if(p===0){x(`up to date${o?` since v${o.replace(/^v/,"")}`:""}${u.currentVersion?` (instance is on v${u.currentVersion})`:""} \u2014 ${s} left untouched.`);return}let h=u.currentVersion??u.releases[0]?.version??"",k=`<!-- GENERATED by \`turbobase project adopt\` against ${n} \u2014 adopted-through=${h}. Re-run to refresh; delete this file once every line is done. -->
|
|
1731
|
+
|
|
1732
|
+
`;await Vu.writeFile(s,k+u.markdown,"utf8"),x(`wrote ${s} \u2014 ${p} item(s) across ${u.releases.length} release(s)${o?` since v${o.replace(/^v/,"")}`:""}.`)})}Qt();var ar=["suggested_kb_edit","kb_correction"];var eb=[{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 tb(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var pE=new Map(eb.map(t=>[tb(t.heading),t]));function nb(t){return t.diff??!!t.dryRun}var rb={update_page:"append to the existing page",new_page:"create a NEW page"},xt=(t,e)=>` ${w.dim(t.padEnd(11))}${e}`,Ju=t=>t.ownerEmail??t.ownerId,bs=t=>w.green(t?` + ${t}`:" +"),sb=t=>w.red(t?` - ${t}`:" -"),en=t=>w.dim(` ${t}`),ob=` ${w.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,Pi=80;function ib(t){let e=[ob];t.target?(e.push(en(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(sb(`visibility: ${t.target.visibility}`)),e.push(bs("visibility: admin"))):e.push(en(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(en("title, slug, evidence: untouched")),e.push(en("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(en("turbobase.document \xB7 new")),e.push(bs(`title: ${t.pageTitle}`)),e.push(bs("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(en('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(en('appended under "## From app developers":'));let n=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
|
|
1733
|
+
`);for(let r of n.slice(0,Pi))e.push(bs(r?` ${r}`:""));return n.length>Pi&&e.push(w.yellow(` \u2026 ${n.length-Pi} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function ab(t,e={}){let n=[];return t.forEach((r,s)=>{let{target:o,entries:i}=r;if(n.push(`${String(s+1).padStart(2)}. ${w.bold(r.pageTitle)}`),n.push(xt("page",o?`${o.title} (${o.slug}) [${o.visibility}]`:w.dim("new \u2014 no existing page matches"))),n.push(xt("action",r.needsPageRef?w.red("SKIP \u2014 nothing is written"):rb[r.action])),r.needsPageRef){let a=[...new Set(i.map(c=>c.kb_page_ref?.trim()).filter(c=>!!c))];n.push(xt("unresolved",w.red((a.length>0?`no page matches ${a.map(c=>`"${c}"`).join(", ")}`:"the correction names no page at all")+" \u2014 a correction needs a page to correct, so this group is SKIPPED and its findings stay pending. Fix the ref (or write the page) and re-run.")))}if(n.push(xt("findings",`${i.length} ${i.length===1?"finding":"findings"} from ${[...new Set(i.map(a=>a.app_slug))].join(", ")}`)),i.forEach(a=>{let c=a.verdict?` ${w.dim(`\xB7 ${a.verdict}`)}`:"",u=a.kb_page_ref?` ${w.dim(`(${a.kb_page_ref})`)}`:"";n.push(` ${w.dim("\xB7")} ${a.title.trim()}${u}${c}`)}),n.push(xt("confidence",r.withdraws?w.red("WITHDRAWN from readers (text untouched)"):w.dim("untouched"))),r.supersedes&&n.push(xt("supersedes",w.yellow("a finding here AMENDS an earlier claim \u2014 its block is appended and marked, and nothing already on the page is reordered or removed"))),r.blockedBy&&n.push(xt("blocked",w.red(`unpublished work on this page belongs to ${Ju(r.blockedBy)} \u2014 this page will be SKIPPED`))),r.alsoMatched.length>0&&n.push(xt("ambiguous",w.yellow(`${r.alsoMatched.length} other page(s) match this ref: ${r.alsoMatched.map(a=>a.slug).join(", ")}`))),(r.similarTo?.length??0)>0){let a=(r.similarTo??[]).map(c=>{let u=t.findIndex(h=>h.key===c),p=u>=0?t[u]:void 0;return p?`#${u+1} "${p.pageTitle}"`:c});n.push(xt("similar",w.yellow(`this new page looks related to ${a.join(", ")} \u2014 nothing was merged. If they are one page, push one now and re-run: the rest will resolve onto it.`)))}e.diff&&!r.needsPageRef&&n.push(...ib(r)),n.push("")}),n}function lb(t){let e=u=>t.filter(u).length,n=t.reduce((u,p)=>u+p.entries.length,0),r=e(u=>u.withdraws),s=e(u=>u.blockedBy!=null),o=e(u=>u.needsPageRef),i=[`${n} finding${n===1?"":"s"}`,`${t.length-o} page(s)`,`${e(u=>u.action==="update_page"&&!u.needsPageRef)} appended`,`${e(u=>u.action==="new_page"&&!u.needsPageRef)} created (unpublished)`,...o>0?[w.red(`${o} SKIPPED \u2014 correction with no page to correct`)]:[]],a=r>0?w.red(`${r} page(s) WITHDRAWN from readers`):w.dim("no page withdrawn"),c=s>0?` \xB7 ${w.red(`${s} page(s) BLOCKED by another editor`)}`:"";return`${i.join(" \xB7 ")} \xB7 ${a}${c}`}function cb(t,e){let n=new Map(e.map(s=>[s.key,s])),r=[];for(let s of t){let o=n.get(s.key),i=s.pageTitle||o?.pageTitle||s.key;if(s.skipped==="blocked_by_draft_owner"){r.push(`${w.yellow("skipped")} ${i} \u2014 unpublished work belongs to ${s.blockedBy?Ju(s.blockedBy):"another editor"}; its findings stay pending`);continue}if(s.skipped==="unresolved_page_ref"){let c=[...new Set((o?.entries??[]).map(u=>u.kb_page_ref?.trim()).filter(u=>!!u))];r.push(`${w.yellow("skipped")} ${i} \u2014 `+(c.length>0?`no page matches ${c.map(u=>`"${u}"`).join(", ")}`:"the correction names no page")+"; nothing was written and its findings stay pending");continue}if(s.skipped){r.push(`${w.yellow("skipped")} ${i} \u2014 ${s.skipped.replace(/_/g," ")}`);continue}let a=s.created?w.green("created "):w.green("appended");r.push(`${a} ${i} \u2014 ${s.appliedEntryIds.length} finding(s) \u2192 page ${w.bold(s.documentId??"?")}`+(s.created?w.dim(" (unpublished)"):"")),s.confidence==="downgraded"?r.push(` ${w.red("withdrawn from readers:")} ${i}`):s.confidence==="already_withdrawn"?r.push(` ${w.dim("page was already unpublished \u2014 left as is")}`):s.confidence==="missing"&&r.push(` ${w.yellow("page vanished between plan and push \u2014 nothing withdrawn")}`)}return r}function Wu(t){if(t instanceof se){let e=t.body;t.status===403&&e?.reason==="admin_required"&&$("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&&$("this instance does not serve /v1/learnings \u2014 it predates the app-developer learning loop. Ask for an instance upgrade.")}ce(t,"extensions:deploy","learnings push-kb")}async function Zu(t,e=n=>new B(n)){t.section&&!ar.includes(t.section.trim())&&$(`unknown --section "${t.section}" \u2014 expected one of ${ar.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&$("--limit must be a positive integer.");let n=await V(t.baseUrl),r=e(n),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 ee("reading the pending queue",()=>r.learningsPending(s))}catch(c){Wu(c),$(`could not read the pending queue: ${c instanceof Error?c.message:String(c)}`)}if(o.items.length===0){Z(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(ab(o.items,{diff:nb(t)}).join(`
|
|
1734
|
+
`)),x(lb(o.items)),t.dryRun){Z(w.dim("dry run \u2014 nothing was written."));return}let i=o.items.filter(c=>!c.needsPageRef);if(i.length===0){Z(w.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((c,u)=>c+u.entries.length,0);if(!t.yes){if(!it()){Z(w.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes (or --dry-run to review the plan).")),process.exitCode=1;return}if(await at(`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"){Z("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{let c=await ee("writing pages",()=>r.learningsPushKb(o.planToken,s));x(cb(c.applied,o.items).join(`
|
|
1735
|
+
`))}catch(c){if(c instanceof se&&c.status===409){Z(w.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),Z(`re-run \`${ir} kb push\` to review the current plan.`),process.exitCode=2;return}Wu(c),Z(w.red(`turbobase: ${c instanceof Error?c.message:String(c)}`)),process.exitCode=2}}Qt();function ub(t){return t.diff??!!t.dryRun}function db(t,e){let n=[];return t.forEach((r,s)=>{let o=r.action==="new_rule"?w.green("new rule"):w.yellow("amend rule"),i=r.targetPublished?` ${w.yellow("[currently live]")}`:"";n.push(`${s+1}. ${o} ${w.bold(r.slug)}${i}`),n.push(` ${r.name}`),r.description&&n.push(` ${w.dim(r.description)}`);for(let a of r.entries)n.push(` ${w.dim("\xB7")} ${w.dim(a.app_slug)} ${a.title}`);if(e.diff){n.push("");for(let a of r.bodyMarkdown.split(`
|
|
1736
|
+
`))n.push(` ${w.dim("|")} ${a}`)}n.push("")}),n}function pb(t){let e=t.reduce((s,o)=>s+o.entries.length,0),n=t.filter(s=>s.targetPublished).length,r=[`${e} finding(s) \u2192 ${t.length} rule(s)`];return n>0&&r.push(w.yellow(`${n} amend a rule that is currently live`)),r.join(" \xB7 ")}async function Yu(t,e=n=>new B(n)){t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&$("--limit must be a positive integer.");let n=await V(t.baseUrl),r=e(n),s={...t.app?{app:t.app}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{}},o;try{o=await ee("reading the pending rules",()=>r.rulesPending(s))}catch(a){ce(a,"extensions:deploy","read the pending rules"),$(`could not read the pending queue: ${a instanceof Error?a.message:String(a)}`)}if(o.items.length===0){Z(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(db(o.items,{diff:ub(t)}).join(`
|
|
1737
|
+
`)),x(pb(o.items)),t.dryRun){Z(w.dim("dry run \u2014 nothing was written."));return}let i=o.items.reduce((a,c)=>a+c.entries.length,0);if(!t.yes){if(!it()){Z(w.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes (or --dry-run to review the plan).")),process.exitCode=1;return}if(await at(`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"){Z("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{await ee("writing the rules",()=>r.rulesPush(o.planToken,s))}catch(a){a instanceof se&&a.status===409&&$("the pending queue changed while you were reading the plan \u2014 nothing was written. Re-run to see the new plan."),$(`push failed: ${a instanceof Error?a.message:String(a)}`)}x(w.green(`wrote ${o.items.length} draft rule(s).`)),Z(w.dim("They are DRAFT and DISABLED \u2014 nothing is injected yet. An admin reviews and publishes them under Settings \u203A Skills."))}Qt();var _n=t=>new B(t);async function $n(t,e){let n=await V(t.baseUrl);return e(n)}async function ws(t,e,n,r){return r.yes?!0:it()?await at(t,[{value:"yes",label:e,description:n},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(Z("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(Z(w.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function fb(t){return t.visibility!=="published"?w.dim("draft"):t.enabled?t.in_current_release?w.green("live"):w.yellow("unreleased"):w.yellow("disabled")}function Qu(t,e){let n=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-n))}function hb(t){if(t.items.length===0)return["no skills on this instance."];let e=Math.max(4,...t.items.map(o=>o.slug.length)),n=[];for(let o of t.items)n.push(`${Qu(w.bold(o.slug),e)} ${Qu(fb(o),10)} ${o.surfaces.join(",")||w.dim("none")}`),o.description&&n.push(` ${w.dim(o.description)}`);n.push("");let r=t.items.filter(o=>o.visibility==="published"&&o.enabled&&o.in_current_release).length,s=t.items.filter(o=>o.visibility!=="published").length;return n.push(`${t.items.length} skill(s) \xB7 ${r} injected \xB7 ${s} draft`+(t.currentVersion==null?"":` \xB7 release v${t.currentVersion}`)),n}async function Xu(t,e=_n){let n={};t.status&&(t.status!=="draft"&&t.status!=="published"&&$(`--status must be 'draft' or 'published' (got '${t.status}').`),n.status=t.status);let r=await $n(t,e),s;try{s=await ee("reading the skills",()=>r.skillsList(n))}catch(o){ce(o,"skills:publish","read the instance skills"),$(`could not read the skills: ${o instanceof Error?o.message:String(o)}`)}x(hb(s).join(`
|
|
1738
|
+
`))}async function ed(t,e,n=_n){let r=[...new Set(t.map(a=>a.trim()).filter(Boolean))];r.length===0&&$("name at least one skill slug. `turbobase skills list` shows them.");let s=await $n(e,n);if(!await ws(`Publish ${r.length} skill(s)?`,"Yes \u2014 publish them","their text is injected into every matching turn from now on",e))return;let i;try{i=await ee("publishing",()=>s.skillsPublish(r))}catch(a){ce(a,"skills:publish","publish a skill"),$(`publish failed: ${a instanceof Error?a.message:String(a)}`)}x(w.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(Z(w.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),Z(w.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function td(t,e,n=_n){let r=[...new Set(t.map(a=>a.trim()).filter(Boolean))];r.length===0&&$("name at least one skill slug. `turbobase skills list` shows them.");let s=await $n(e,n);if(!await ws(`Move ${r.length} skill(s) back to draft?`,"Yes \u2014 unpublish them","they stop being injected immediately; the text and its history are kept",e))return;let i;try{i=await ee("unpublishing",()=>s.skillsUnpublish(r))}catch(a){ce(a,"skills:publish","unpublish a skill"),$(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}x(w.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),Z(w.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(Z(w.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function nd(t,e,n=_n){let r=Number(t);(!Number.isInteger(r)||r<1)&&$(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let s=await $n(e,n);if(await ws(`Roll the skills back to release v${r}?`,"Yes \u2014 restore that release","content only: a skill an operator has since disabled stays off",e))try{let i=await ee("rolling back",()=>s.skillsRollback(r));x(w.green(`rolled back to v${i.version.version_no}.`))}catch(i){ce(i,"skills:publish","roll back a skills release"),$(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function rd(t,e=_n){let n=await $n(t,e),r;try{r=await ee("reading the releases",()=>n.skillsReleases())}catch(s){ce(s,"skills:publish","read the skills releases"),$(`could not read the releases: ${s instanceof Error?s.message:String(s)}`)}if(r.items.length===0){Z("no releases yet.");return}for(let s of r.items){let o=s.is_current?w.green("*"):" ",i=s.release_note?` \u2014 ${s.release_note}`:"";x(`${o} v${s.version_no} ${s.skill_count} skill(s) ${w.dim(s.published_at)}${s.published_by?w.dim(` by ${s.published_by}`):""}${w.dim(i)}`)}}async function sd(t,e,n=_n){let r=[...new Set((t??[]).map(u=>u.trim()).filter(Boolean))];r.length===0&&$("name at least one skill to delete. `turbobase skills list` shows the slugs.");let s=await $n(e,n);if(!await ws(r.length===1?`Delete the skill '${r[0]}'?`:`Delete ${r.length} skills?
|
|
1739
|
+
${r.join(`
|
|
1740
|
+
`)}`,"Yes \u2014 delete them","permanent: the rows and their text are removed. Prior releases keep their own copy.",e))return;let i=[],a=[];for(let u of r)try{i.push(await ee(`deleting ${u}`,()=>s.skillsDelete(u)))}catch(p){if(p instanceof se&&p.status===404){a.push(u);continue}i.length>0&&Z(w.dim(`deleted before the error: ${i.map(h=>h.slug).join(", ")}`)),ce(p,"skills:publish","delete a skill"),$(`delete failed on '${u}': ${p instanceof Error?p.message:String(p)}`)}i.length>0&&x(w.green(`deleted ${i.length} skill(s).`));let c=i.filter(u=>u.wasPublished).map(u=>u.slug);c.length>0&&Z(w.yellow(`Published until now, so no longer injected: ${c.join(", ")}`)),a.length>0&&(Z(w.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as od}from"node:fs";import{join as mb,relative as gb,resolve as yb,sep as bb}from"node:path";var wb=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),vb=new Set([".mcp.json",".env"]);function Sb(t){return vb.has(t)||t.startsWith(".env.")&&t!==".env.example"}function kb(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function _b(t){return t.includes(0)}async function id(t){let e=yb(t),n={},r=[],s=[],o=[];async function i(a){let c=await od.readdir(a,{withFileTypes:!0});for(let u of c){let p=mb(a,u.name);if(u.isDirectory()){if(wb.has(u.name))continue;await i(p);continue}if(!u.isFile())continue;let h=gb(e,p).split(bb).join("/");if(Sb(u.name)){s.push(h);continue}let k=await od.readFile(p);if(!kb(k)){r.push(h);continue}_b(k)&&o.push(h),n[h]=k.toString("utf8")}}return await i(e),{files:n,skipped:r,secrets:s,unstorable:o}}import{randomBytes as $b}from"node:crypto";var xb="/_tb/app-assets",Tb=16,Rb=/^[0-9a-f]{32}$/;function ad(){return $b(Tb).toString("hex")}function Eb(t){return Rb.test(t)}function ld(t){if(!Eb(t))throw new Error(`not a build id: ${t}`);return`${xb}/${t}/`}var cd=7;import vs from"node:fs/promises";import lr from"node:path";var Ai={esbuild:"0.28.1","isolated-vm":"6.1.2"},Ii="@turbobase/isolated-vm-prebuilds";function Ci(t,e){return`${t}-${e}`}function Oi(t=process.versions){return`abi${t.modules}`}var ud=["darwin-x64","win32-arm64"];async function dd(t){let e=t.platform??process.platform,n=t.arch??process.arch,r=Ci(e,n),s=lr.join(t.home,"node_modules"),o=lr.join(s,...Ii.split("/"),"prebuilds",r),i=lr.join(s,"isolated-vm","prebuilds",r),a;try{a=await vs.readdir(o)}catch{return[]}let c=[];await vs.mkdir(i,{recursive:!0});for(let u of a){if(!u.endsWith(".node"))continue;let p=lr.join(i,u);try{await vs.copyFile(lr.join(o,u),p,vs.constants?.COPYFILE_EXCL??1),c.push(u)}catch{}}return c}import{homedir as Pb}from"node:os";import{join as pd}from"node:path";import{promises as Ni}from"node:fs";function hd(){let t=process.env.TURBOBASE_HOME??pd(Pb(),".turbobase");return{dir:t,file:pd(t,"sandboxes.json")}}var Ab={s:1e3,m:6e4,h:36e5,d:864e5};function Ib(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 n=Number(e[1]);if(!Number.isFinite(n)||n<=0)throw new Error(`invalid --ttl '${t}': duration must be a positive integer.`);return n*Ab[e[2]]}function Cb(t,e=Date.now()){return new Date(e+Ib(t)).toISOString()}function Ob(t,e=Date.now()){let n=Date.parse(t);return Number.isNaN(n)?!0:n<=e}function Nb(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 n=Number(e[1]);if(!Number.isFinite(n)||n<0||n>100)throw new Error(`invalid --sample '${t}': percent must be between 0 and 100.`);return n/100}function jb(t,e){if(e>=1)return[...t];if(e<=0||t.length===0)return[];let n=Math.max(1,Math.round(1/e)),r=[];for(let s=0;s<t.length;s+=n)r.push(t[s]);return r}var Lb="[REDACTED]",cr=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},ji=class extends Error{table;column;constructor(e,n,r){super(`Refusing to copy ${e}.${n} into a sandbox: ${r}. 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=n}};function zb(t,e,n){let r={};for(let[s,o]of Object.entries(e)){let i=n[s];if(i===void 0)throw new ji(t,s,"column has no PII classification (unknown = unsafe)");i==="pii"?r[s]=o==null?o:Lb:r[s]=o}return r}function Ub(t,e,n){return e.map(r=>zb(t,r,n))}var fd=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),Db=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function qb(t){let e=t.trim();try{let s=new URL(e);if(s.hostname)return s.hostname.toLowerCase()}catch{}let n=e.replace(/^[a-z]+:\/\//i,""),r=(n.split("/")[0]??n).split("@").pop()??n;return(r.split(":")[0]??r).toLowerCase()}function Li(t){if(!t||!t.trim())throw new Error("local-only guard: empty database target \u2014 refusing to proceed.");let e=t.toLowerCase();for(let r of Db)if(e.includes(r))throw new Error(`local-only guard: target '${t}' looks like a cloud/prod context (matched '${r}'). \`turbobase sandbox create\` is LOCAL-ONLY and will never touch a cloud database.`);let n=qb(t);if(!fd.has(n))throw new Error(`local-only guard: target host '${n}' is not a recognised local Postgres (${[...fd].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function Mb(t,e=Bb){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function Bb(){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 zi(){let{file:t}=hd();try{let e=await Ni.readFile(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function md(t){let{dir:e,file:n}=hd();await Ni.mkdir(e,{recursive:!0}),await Ni.writeFile(n,`${JSON.stringify(t,null,2)}
|
|
1741
|
+
`,{mode:384})}async function Kb(t){let e=await zi();e.push(t),await md(e)}async function gd(t){let e=await zi(),n=e.findIndex(s=>s.name===t);if(n===-1)return null;let[r]=e.splice(n,1);return await md(e),r??null}async function Ss(){return zi()}function Ui(t,e=Date.now()){let n=[],r=[];for(let s of t)Ob(s.expiresAt,e)?r.push(s):n.push(s);return{active:n,expired:r}}async function yd(t,e){Li(t.target());let n=t.dataCopyUnavailable?.();if(n)throw new cr(n);let r=Nb(e.sample),s=e.now??Date.now(),o=(e.nameGen??(u=>Mb(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=jb(u.rows,r),h=Ub(u.table,p,u.classification);h.length>0&&await t.copyRows(i,u.table,h)}let c={name:o,fromTenant:e.fromTenant,database:i,createdAt:new Date(s).toISOString(),expiresAt:Cb(e.ttl,s),sampleFraction:r,url:Hb(o,e.baseUrl)};return await Kb(c),c}async function bd(t,e){Li(t.target());let r=(await Ss()).find(s=>s.name===e);return r?(await t.dropDatabase(r.database),await gd(e),r):null}async function Di(t,e=Date.now()){Li(t.target());let n=await Ss(),{expired:r}=Ui(n,e),s=[];for(let o of r){try{await t.dropDatabase(o.database)}catch{continue}await gd(o.name),s.push(o)}return s}var ur={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","data:read"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},DE=Object.keys(ur).filter(t=>ur[t].mintable);var BE=ur.pat.prefix,Vb=Object.entries(ur).map(([t,e])=>[e.prefix,t]),Gb=/^[A-Za-z0-9_-]{20,}$/;function Wb(t){if(typeof t!="string")return null;for(let[e,n]of Vb)if(t.startsWith(e)&&Gb.test(t.slice(e.length)))return n;return null}function wd(t){return Wb(t)==="pat"}var dr="bundle.json",ks="turbobase";function Sd(t){let e;try{e=JSON.parse(t)}catch(c){throw new Error(`bundle.json is not valid JSON: ${c instanceof Error?c.message:String(c)}`)}if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("bundle.json must be a JSON object");let n=e,r=typeof n.version=="number"?n.version:0;if(r!==1)throw new Error(`bundle.json version ${r} is unsupported (expected 1)`);let s=c=>Array.isArray(c)?c:[],o=n.sync??{},i=n.guardrails??{},a={version:1,...typeof n.tenant=="string"?{tenant:n.tenant}:{},hooks:s(n.hooks),conduits:s(n.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(n.schedules)};return Jb(a)}function Jb(t){let e=n=>(r,s)=>n(r)<n(s)?-1:n(r)>n(s)?1:0;return{version:1,...t.tenant?{tenant:t.tenant}:{},hooks:[...t.hooks].sort(e(n=>n.id)),conduits:[...t.conduits].sort(e(n=>n.id)),sync:{fields:[...t.sync.fields].sort(e(vd)),tables:[...t.sync.tables].sort(e(n=>n.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(vd)),conduits:[...t.guardrails.conduits].sort(e(n=>n.conduitId))},schedules:[...t.schedules].sort(e(n=>n.name))}}function vd(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function kd(t,e){let n=(e??"").trim();if(!n)return{ok:!1,reason:"target instance slug is unknown \u2014 cannot confirm a promote"};let r=(t??"").trim();return r?r!==n?{ok:!1,reason:`--confirm "${r}" does not match the target instance "${n}" \u2014 refusing to apply`}:{ok:!0}:{ok:!1,reason:`--confirm <slug> is required for promote (expected "${n}")`}}async function pR(t,e){try{let n=await fetch(`${t.replace(/\/+$/,"")}/auth/pat-exchange`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!n.ok)return null;let r=await n.json();return typeof r.token=="string"&&r.token.length>0?r.token:null}catch{return null}}async function fR(t){let e=await Ct();e.length===0&&$("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),it()||$("this command needs an explicit <base-url> in a non-interactive shell.");try{return await at(t,e.map(n=>({value:n.baseUrl,label:n.baseUrl,description:`updated ${n.updatedAt}`})))}catch{$("cancelled.")}}async function hR(t,e){let n;try{n=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 r=(n.headers.get("content-type")??"").includes("application/json");return n.status===200||n.status===403?{ok:!0}:n.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${n.status}`}:r?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${n.status}`}}async function mR(t,e,n){let r=await uu({baseUrl:t,token:e}),s=(await Ct()).length-1;if(x(`signed in to ${r.baseUrl} \u2014 now the active instance`+(s>0?` (${s} other${s===1?"":"s"} stored; commands default here).`:".")),!n)return;let o=await hR(r.baseUrl,e);o.ok||(o.kind==="wrong-host"?(Z(`warning: ${r.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${o.detail}.`),Z(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),Z(" The token is stored, but commands will fail against this base-url until it points at the API.")):o.kind==="bad-token"?Z(`warning: ${r.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):Z(`warning: could not reach ${r.baseUrl} to verify the token (${o.detail}). Stored anyway.`))}async function gR(t){let e=await sr(t),n=c=>{let u=new RegExp(`${c}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(e);return u?u[2]:void 0},r=/\bdefineConduit\s*[<(]/.test(e),s=n("id");if(r){let c=n("on"),u=n("recordType"),p=n("source");return(!s||!u||!c||!p)&&$(`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`),{id:s,recordType:u,event:c,source:p,sourceCode:e,extensionKind:"conduit"}}let o=n("recordType"),i=n("event"),a=n("source")??"standalone";return(!s||!o||!i)&&$(`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 Yn(t,e,n,r){try{return await re.access(t),"skipped"}catch{}return await re.mkdir(Zn(t),{recursive:!0}),await re.writeFile(t,e,{mode:r??(n?493:420)}),r!==void 0&&await re.chmod(t,r),"wrote"}async function gg(t,e){if(yg(t)!==".gitignore")return Yn(t,e.content,e.executable,e.mode);let n=await re.readFile(t,"utf8").catch(()=>null);if(n===null)return Yn(t,e.content,e.executable,e.mode);let r=Fu(n);return r===null?"skipped":(await re.writeFile(t,r,"utf8"),"merged")}function Lc(t){if(t!==void 0){if(t==="junit"||t==="json")return t;$(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function yR(t){return{name:"turbobase ext test",cases:t.map(n=>{if(n.pass)return{name:n.name,status:"passed"};let r=n.error?"error":n.rejection?.code??"mismatch",s=n.error?`error: ${n.error}`:n.observed!==n.expected?`expected ${n.expected}, observed ${n.observed}`+(n.rejection?` (rejected: ${n.rejection.code??"rejected"}${n.rejection.message?` \u2014 ${n.rejection.message}`:""})`:""):`rejected: ${n.rejection?.code??"rejected"}${n.rejection?.message?` \u2014 ${n.rejection.message}`:""}`;return{name:n.name,status:"failed",detail:s,type:r}})}}function bR(t,e){let n=e.warnings.length===0?[{name:`${t} (${e.kind})`,status:"passed"}]:e.warnings.map(r=>({name:`${t}: ${r.rule}`,status:"failed",type:r.rule,detail:`${r.message} \u2192 fix: ${r.fix}`}));return{name:`turbobase ext lint ${t}`,cases:n}}function wR(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 n of t.guards)e.push(n.status==="failed"?{name:`guard: ${n.name}`,status:"failed",type:n.name,detail:n.detail}:{name:`guard: ${n.name}`,status:"passed",detail:n.status==="skipped-offline"?`skipped-offline: ${n.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 Bc({includeInternal:t=!0}={}){let e=new dR;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.1.16").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${ki()}
|
|
1742
|
+
`),e.hook("preAction",(d,f)=>{Ku(e.opts(),f.opts())});let n=e.command("auth").description("Sign in to an instance and manage stored credentials."),r=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.");n.command("login").description("Sign in to an instance by pasting a personal access token (PAT), stored in ~/.turbobase/credentials.").requiredOption("--base-url <url>","Instance base URL, e.g. https://acme.turbobase.app").option("--token <tb_pat_\u2026>","The PAT to store. Mint one in your app under Settings \u203A Access tokens.").option("--no-verify","Skip the post-login connectivity/token probe.").action(async d=>{let f=We(d.baseUrl);d.token||$(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
|
|
1743
|
+
${ir} auth login --base-url ${f} --token tb_pat_\u2026`),wd(d.token)||$("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await mR(f,d.token,d.verify)}),n.command("status").description("Show the active instance (the no-`--base-url` default) and every stored sign-in.").action(async()=>{let d=await Ct();if(d.length===0){x("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`.");return}let f=await gt(),g=y=>!!f&&y.baseUrl===f.baseUrl;if(qe())x(Xt(d.map(y=>[g(y)?w.green("*"):" ",w.bold(y.baseUrl),w.dim(y.updatedAt)]),{head:["","instance","updated"]}));else for(let y of d)x(`${g(y)?"* ":" "}${y.baseUrl} (updated ${y.updatedAt})`);f||Z("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}),n.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async d=>{let f=d??await fR("Pick the active instance:"),g=await us(f);if(!g){let y=await Ct();$(`no stored sign-in for ${We(f)}.`+(y.length?` Stored: ${y.map(_=>_.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${We(f)} --token tb_pat_\u2026\`.`)}x(`active instance \u2192 ${g.baseUrl}.`)}),n.command("logout").description("Remove a stored sign-in (defaults to the active instance).").option("--base-url <url>","Which instance to remove (defaults to the active/single one).").option("--all","Remove every stored sign-in.").action(async d=>{if(d.all){let y=await Ct();for(let _ of y)await di(_.baseUrl);x(`removed ${y.length} stored sign-in${y.length===1?"":"s"}.`);return}let f=await di(d.baseUrl);f||$(d.baseUrl?`no stored sign-in for ${We(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let g=await gt();x(`signed out of ${f}.`+(g?` Active instance \u2192 ${g.baseUrl}.`:""))}),r.command("types").description("Generate types.ts from the signed-in instance's catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("-o, --out <file>","Output file","types.ts").option("--records-only","Emit only record-shape interfaces (skip the OpenAPI half).").action(async d=>{let{baseUrl:f,token:g}=await V(d.baseUrl),y;try{y=await It({baseUrl:f,token:g,recordsOnly:d.recordsOnly})}catch(m){let S=m instanceof Error?m.message:String(m);if(!d.recordsOnly&&/openapi\.json failed \(401/.test(S)){let P=await pR(f,g);if(P)try{y=await It({baseUrl:f,token:P,recordsOnly:!1});let A=pe(process.cwd(),d.out);await re.writeFile(A,y,"utf8"),x(`wrote ${A} (${y.split(`
|
|
1744
|
+
`).length} lines).`);return}catch{}Z("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{y=await It({baseUrl:f,token:g,recordsOnly:!0})}catch(A){$(`types generation failed: ${A instanceof Error?A.message:String(A)}`)}}else $(`types generation failed: ${S}`)}let _=pe(process.cwd(),d.out);await re.writeFile(_,y,"utf8"),x(`wrote ${_} (${y.split(`
|
|
1745
|
+
`).length} lines).`)}),Gu(r),r.command("grounding").description("Write the instance's grounding brief (source primer + record anatomy + KB retrieval) to a file for agent sessions.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--records <list>","Comma-separated record types to focus, e.g. purchaseOrder,itemReceipt.").option("--query <text>","Retrieval question for the knowledge base (e.g. what the app is about).").option("-o, --out <file>","Output file","INSTANCE.md").action(async d=>{let{baseUrl:f,token:g}=await V(d.baseUrl),y=new URLSearchParams;d.records&&y.set("records",d.records),d.query&&y.set("query",d.query);let _=y.toString(),m=await fetch(`${f}/v1/catalog/grounding${_?`?${_}`:""}`,{headers:{Authorization:`Bearer ${g}`,Accept:"application/json"}});m.ok||$(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${m.status}`);let P=((await m.json()).markdown??"").trim(),A=pe(process.cwd(),d.out),C=d.records?` records=${d.records}`:"",O=`<!-- GENERATED by \`turbobase project grounding\` against ${f}${C} \u2014 do not edit; re-run to refresh. -->
|
|
1746
|
+
|
|
1747
|
+
`;await re.writeFile(A,O+(P?`${P}
|
|
1722
1748
|
`:`(no grounding available yet)
|
|
1723
|
-
`),"utf8"),x(`wrote ${A}${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 (${
|
|
1724
|
-
${P===0?T.green(A):T.yellow(A)}`),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 v=await Nc(),{baseUrl:P,token:A}=await G(f.baseUrl),C=new H({baseUrl:P,token:A});try{let O=await ue(`applying bundle to ${f.to}`,()=>C.configApply(v));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 ie&&O.status===403&&$("apply forbidden (403) \u2014 the stored PAT is not for an admin."),$(`bundle apply failed: ${O instanceof Error?O.message:String(O)}`)}return}p||$("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:g,token:y}=await G(f.baseUrl),_=await s0(ce(process.cwd(),p)),m=new H({baseUrl:g,token:y});try{let v=await ue(`deploying ${ag(p)}`,()=>m.deploy(_));qe()?x(Nt("Deployed",[`${T.bold(v.id)} ${vr(v.status)} ${T.dim(v.outcome)}`])):x(`deployed ${v.id} \u2192 status=${v.status} (${v.outcome}).`)}catch(v){v instanceof ie&&v.status===403&&$("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),$(`deploy failed: ${v instanceof Error?v.message:String(v)}`)}});let c=e.command("apps").description("Manage hosted apps served in your Turbobase app.");c.command("deploy").description("Build the app (if needed) and deploy it \u2014 cuts a new live version at /a/<slug>.").argument("<app>","App slug or id.").argument("[dir]","Source or built directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--no-build","Upload the directory as-is; it is already a built bundle.").option("--no-install","Skip `npm install` (assume deps are present).").option("--no-pull","Do not pull generated source even when the dir has no package.json.").option("--entry <file>","SPA entrypoint served for unknown routes.","index.html").option("--create","Create the app first if it does not exist yet.").option("--proposal <id>","Widget proposal this ship realizes (defaults to .turbobase/proposal.json).").option("--preview","Deploy to a preview URL instead of going live. Nothing about /a/<slug> changes until you `apps promote` it.").option("--label <text>","Label for the preview, so several open previews are tellable apart.").action(async(p,f,g)=>{let y=ce(process.cwd(),f??".");await te.mkdir(y,{recursive:!0});let _=g.proposal??await k(y),{baseUrl:m,token:v}=await G(g.baseUrl),P=new H({baseUrl:m,token:v}),A=!1;try{A=(await P.appsList()).some(Q=>Q.slug===p||Q.id===p)}catch(Q){he(Q,"extensions:deploy","deploy"),$(`could not reach ${m}: ${Q instanceof Error?Q.message:String(Q)}`)}if(!A){g.create||$(`no app "${p}" on ${m} \u2014 create it with \`turbobase apps create ${p}\`, or pass --create.`);let Q=await ue(`creating app ${p}`,()=>u(m,v,{slug:p},{tolerateExisting:!0}));Q.existed||x(`created ${Q.slug??p}.`)}let C=Q=>te.stat(Ve(y,Q)).then(()=>!0).catch(()=>!1),O=p,V=y,N=g.build!==!1;if(N&&!await C("package.json"))if(await C("index.html"))x("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),N=!1;else if(g.pull===!1)$(`${y} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let Q=await ue(`pulling ${p}`,()=>h(m,v,p));O=Q.slug??p,await S(y,Q.files,!0),x(`pulled generated source (rev ${Q.rev}).`)}let ee;if(N){let Q=Yd();if(ee={buildId:Q,assetBase:Qd(Q)},g.install!==!1&&!await C("node_modules")){x("installing dependencies\u2026");try{await E(["install"],y)}catch(Ge){$(`npm install failed: ${Ge instanceof Error?Ge.message:String(Ge)}`)}}x("building\u2026");try{await E(["run","build"],y,{TURBOBASE_ASSET_BASE:ee.assetBase})}catch(Ge){$(`build failed: ${Ge instanceof Error?Ge.message:String(Ge)}`)}await C("dist")||$(`no dist/ after build in ${y} \u2014 check the app's build script.`),V=Ve(y,"dist")}g.preview&&!ee&&$(`--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 W=await F(m,v,O,V,g.entry,_,ee,g.preview?{label:g.label}:void 0);if(g.preview){let Q=W.previewUrl??"(no url returned)",Ge=W.expiresAt?new Date(W.expiresAt).toLocaleDateString():`${Xd} days`;qe()?x(Nt("Preview deployed",[`${T.bold(O)} ${T.green(`v${W.version??"?"}`)} ${T.dim("not live")}`,`${T.bold(Q)}`,T.dim(`expires ${Ge}`)])):x(`preview ${O} v${W.version??"?"} \u2192 ${Q} (expires ${Ge}; /a/${O} unchanged).`),x(`next: turbobase apps promote ${O} ${W.previewId??"<preview-id>"} # make it live`),x(` turbobase apps preview discard ${W.previewId??"<preview-id>"}`);return}qe()?x(Nt("Deployed",[`${T.bold(O)} ${T.green(`v${W.version??"?"}`)} ${T.dim(W.url??`/a/${O}`)}`])):x(`deployed ${O} \u2192 v${W.version??"?"} (${W.url??`/a/${O}`}).`),await Ce(W,y)}),c.command("promote").description("Make a preview the live version at /a/<slug>. Promotes the exact reviewed bytes \u2014 no rebuild.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to promote (from `apps preview list`).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,f,g)=>{let{baseUrl:y,token:_}=await G(g.baseUrl),m=await ue(`promoting ${f}`,()=>L(y,_,p,"promote",{previewId:f}));qe()?x(Nt("Promoted",[`${T.bold(p)} ${T.green(`v${m.version??"?"}`)} ${T.dim(m.url??`/a/${p}`)}`])):x(`promoted ${p} \u2192 v${m.version??"?"} is now live at ${m.url??`/a/${p}`}.`),await Ce(m)});let d=c.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:g,token:y}=await G(f.baseUrl),_=await ne(g,y,p);if(_.previews.length===0){x(`no open previews for ${p}.`);return}for(let m of _.previews){let v=m.label?` ${m.label}`:"",P=m.expiresAt?new Date(m.expiresAt).toLocaleDateString():"?";x(`v${m.version} ${m.previewId}${v} ${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,g)=>{let{baseUrl:y,token:_}=await G(g.baseUrl);await ue(`discarding ${f}`,()=>L(y,_,p,"discard",{previewId:f})),x(`discarded ${f}.`)}),c.command("create").description("Create a new hosted app (a bare app row) so a build can be shipped to it.").argument("<slug>","URL slug the app is served under: /a/<slug>.").option("--name <name>","Display name (defaults to the slug).").option("--description <text>","Optional description.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,f)=>{let{baseUrl:g,token:y}=await G(f.baseUrl),_=await ue(`creating ${p}`,()=>u(g,y,{slug:p,name:f.name,description:f.description})),m=_.slug??p;qe()?x(Nt("Created",[`${T.bold(m)} ${T.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,g,y={}){let _=`${p.replace(/\/+$/,"")}/v1/apps`,m;try{m=await fetch(_,{method:"POST",headers:{Authorization:`Bearer ${f}`,"content-type":"application/json"},body:JSON.stringify({slug:g.slug,name:g.name??g.slug,description:g.description})})}catch(v){$(`create request failed: ${v instanceof Error?v.message:String(v)}`)}if(m.status===401&&$("create unauthorized (401) \u2014 re-run `turbobase auth login`."),m.status===403&&$("create forbidden (403) \u2014 the PAT is not for an admin."),m.status===409){if(y.tolerateExisting)return{slug:g.slug,existed:!0};$(`an app with slug "${g.slug}" already exists.`)}return m.ok||$(`create failed: HTTP ${m.status} ${(await m.text().catch(()=>"")).slice(0,200)}`),await m.json().catch(()=>({}))}async function h(p,f,g){let y=`${p.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(g)}/pull`,_;try{_=await fetch(y,{headers:{Authorization:`Bearer ${f}`}})}catch(m){$(`pull request failed: ${m instanceof Error?m.message:String(m)}`)}return _.status===401&&$("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),_.status===403&&$("pull forbidden (403) \u2014 the PAT is not for an admin."),_.status===404&&$(`no generated source for "${g}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),_.ok||$(`pull failed: HTTP ${_.status} ${(await _.text().catch(()=>"")).slice(0,200)}`),await _.json()}async function S(p,f,g){let y=ce(p),_=0;for(let[m,v]of Object.entries(f)){let P=ce(y,m);P!==y&&!P.startsWith(y+Lc)&&$(`refusing to write outside ${y}: ${m}`),g||await te.stat(P).then(()=>!0).catch(()=>!1)&&$(`${P} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await te.mkdir(Gr(P),{recursive:!0}),await te.writeFile(P,v,"utf8"),_+=1}return _}function b(p){let f=p.indexOf(","),g=p.startsWith("data:")?f>=0?p.slice(f+1):"":p;if(!g)return null;try{let y=Buffer.from(g,"base64");return y.length>0?new Uint8Array(y):null}catch{return null}}async function w(p,f,g){let y=ce(p),_=async(v,P)=>{let A=ce(y,v);A!==y&&!A.startsWith(y+Lc)&&$(`refusing to write outside ${y}: ${v}`),g||await te.stat(A).then(()=>!0).catch(()=>!1)&&$(`${A} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await te.mkdir(Gr(A),{recursive:!0}),await te.writeFile(A,P)},m=`# ${f.title||"App change request"}
|
|
1749
|
+
`),"utf8"),x(`wrote ${A}${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 (${ar.join(" | ")}).`).option("--limit <n>","Cap how many findings to act on.",d=>Number.parseInt(d,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each page\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--no-group","Plan every finding on its own instead of merging the ones that look related \u2014 N findings for one page become N sequential appends.").option("--yes","Skip the confirmation (for scripted runs).").action(d=>Zu(d)),i.command("push").description("Write pending `## Agent rules` findings as draft agent rules, grouped by their `###` heading. Shows the plan and asks first; rules land unpublished and disabled.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--limit <n>","Cap how many findings to act on.",d=>Number.parseInt(d,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each rule\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--no-group","Ignore `###` headings \u2014 write one rule per finding.").option("--yes","Skip the confirmation (for scripted runs).").action(d=>Yu(d)),i.command("list").description("List the instance\u2019s agent skills and whether each is actually injected.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only skills in this state.").action(d=>Xu(d)),i.command("publish").argument("<slug...>","Skill slugs to approve (see `turbobase skills list`).").description("Publish skills \u2014 live by the time this returns. Sets visibility and cuts a release scoped to these skills.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>ed(d,f)),i.command("unpublish").argument("<slug...>","Skill slugs to move back to draft.").description("Move skills back to draft. Retracts them from every prompt immediately \u2014 no release needed \u2014 and keeps the text.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>td(d,f)),i.command("releases").description("List the skill releases, newest first \u2014 the rollback targets.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>rd(d)),i.command("rollback").argument("<version>","Release number to restore (see `turbobase skills releases`).").description("Re-point the current skill release at an earlier one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>nd(d,f)),i.command("delete").argument("<slug...>","Skill slugs to delete (see `turbobase skills list`).").description("Delete skills. Permanent; prior releases keep their own copy of the text. Takes several slugs so cleaning up a bad push is one command.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>sd(d,f));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 d=>{let f;try{f=kn("hook",{recordType:d.record,event:d.event,template:d.template,field:d.field,regex:d.regex,source:d.source,id:d.id})}catch(_){$(_ instanceof Error?_.message:String(_))}let g=pe(process.cwd(),f.relativePath);await Yn(g,f.content)==="skipped"&&$(`refusing to overwrite existing file: ${g}`),x(`wrote ${g}`)}),a.command("conduit").description("Scaffold a conduit file under conduits/ (cross-source bridge).").requiredOption("--source <source>","Origin source the record arrives from, e.g. shopify").requiredOption("--record <type>","Canonical record type the conduit triggers on, e.g. order").requiredOption("--to <source>","Target source the conduit bridges into, e.g. netsuite").option("--to-record <type>","Target record type (defaults to the trigger record type)").option("--event <event>","Cross-source lifecycle event","after_canonicalize_inbound").option("--id <id>","Override the generated conduit id").action(async d=>{let f;try{f=kn("conduit",{recordType:d.record,source:d.source,to:d.to,toRecordType:d.toRecord,event:d.event,id:d.id})}catch(_){$(_ instanceof Error?_.message:String(_))}let g=pe(process.cwd(),f.relativePath);await Yn(g,f.content)==="skipped"&&$(`refusing to overwrite existing file: ${g}`),x(`wrote ${g}`)}),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(d,f)=>{let g=Lc(f.reporter),y=await sr(pe(process.cwd(),d)),_=pe(process.cwd(),f.samples),m=await rr(_);m.length===0&&!g&&x(`no samples found under ${_} \u2014 add JSON fixtures to dry-run against.`);let S;try{S=await hs(y,m.map(C=>C.fixture))}catch(C){$(`bundle failed: ${C instanceof Error?C.message:String(C)}`)}if(g){let C=yR(S);x(gs(C,g)),C.cases.some(O=>O.status==="failed")&&process.exit(1);return}let P=0;for(let C of S){let O=C.pass?w.green("PASS"):w.red("FAIL");C.pass||(P+=1);let G=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}${G}`)}let A=`${S.length-P}/${S.length} sample(s) passed.`;x(`
|
|
1750
|
+
${P===0?w.green(A):w.yellow(A)}`),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(d,f)=>{if(f.to){let S=await zc(),{baseUrl:P,token:A}=await V(f.baseUrl),C=new B({baseUrl:P,token:A});try{let O=await ee(`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 se&&O.status===403&&$("apply forbidden (403) \u2014 the stored PAT is not for an admin."),$(`bundle apply failed: ${O instanceof Error?O.message:String(O)}`)}return}d||$("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:g,token:y}=await V(f.baseUrl),_=await gR(pe(process.cwd(),d)),m=new B({baseUrl:g,token:y});try{let S=await ee(`deploying ${yg(d)}`,()=>m.deploy(_));qe()?x(Nt("Deployed",[`${w.bold(S.id)} ${Sn(S.status)} ${w.dim(S.outcome)}`])):x(`deployed ${S.id} \u2192 status=${S.status} (${S.outcome}).`)}catch(S){S instanceof se&&S.status===403&&$("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),$(`deploy failed: ${S instanceof Error?S.message:String(S)}`)}});let c=e.command("apps").description("Manage hosted apps served in your Turbobase app.");c.command("deploy").description("Build the app (if needed) and deploy it \u2014 cuts a new live version at /a/<slug>.").argument("<app>","App slug or id.").argument("[dir]","Source or built directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--no-build","Upload the directory as-is; it is already a built bundle.").option("--no-install","Skip `npm install` (assume deps are present).").option("--no-pull","Do not pull generated source even when the dir has no package.json.").option("--entry <file>","SPA entrypoint served for unknown routes.","index.html").option("--create","Create the app first if it does not exist yet.").option("--proposal <id>","Widget proposal this ship realizes (defaults to .turbobase/proposal.json).").option("--preview","Deploy to a preview URL instead of going live. Nothing about /a/<slug> changes until you `apps promote` it.").option("--label <text>","Label for the preview, so several open previews are tellable apart.").action(async(d,f,g)=>{let y=pe(process.cwd(),f??".");await re.mkdir(y,{recursive:!0});let _=g.proposal??await T(y),{baseUrl:m,token:S}=await V(g.baseUrl),P=new B({baseUrl:m,token:S}),A=!1;try{A=(await P.appsList()).some(X=>X.slug===d||X.id===d)}catch(X){ce(X,"extensions:deploy","deploy"),$(`could not reach ${m}: ${X instanceof Error?X.message:String(X)}`)}if(!A){g.create||$(`no app "${d}" on ${m} \u2014 create it with \`turbobase apps create ${d}\`, or pass --create.`);let X=await ee(`creating app ${d}`,()=>p(m,S,{slug:d},{tolerateExisting:!0}));X.existed||x(`created ${X.slug??d}.`)}let C=X=>re.stat(Ve(y,X)).then(()=>!0).catch(()=>!1),O=d,G=y,N=g.build!==!1;if(N&&!await C("package.json"))if(await C("index.html"))x("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),N=!1;else if(g.pull===!1)$(`${y} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let X=await ee(`pulling ${d}`,()=>h(m,S,d));O=X.slug??d,await k(y,X.files,!0),x(`pulled generated source (rev ${X.rev}).`)}let ne;if(N){let X=ad();if(ne={buildId:X,assetBase:ld(X)},g.install!==!1&&!await C("node_modules")){x("installing dependencies\u2026");try{await E(["install"],y)}catch(Ge){$(`npm install failed: ${Ge instanceof Error?Ge.message:String(Ge)}`)}}x("building\u2026");try{await E(["run","build"],y,{TURBOBASE_ASSET_BASE:ne.assetBase})}catch(Ge){$(`build failed: ${Ge instanceof Error?Ge.message:String(Ge)}`)}await C("dist")||$(`no dist/ after build in ${y} \u2014 check the app's build script.`),G=Ve(y,"dist")}g.preview&&!ne&&$(`--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 W=await H(m,S,O,G,g.entry,_,ne,g.preview?{label:g.label}:void 0);if(g.preview){let X=W.previewUrl??"(no url returned)",Ge=W.expiresAt?new Date(W.expiresAt).toLocaleDateString():`${cd} days`;qe()?x(Nt("Preview deployed",[`${w.bold(O)} ${w.green(`v${W.version??"?"}`)} ${w.dim("not live")}`,`${w.bold(X)}`,w.dim(`expires ${Ge}`)])):x(`preview ${O} v${W.version??"?"} \u2192 ${X} (expires ${Ge}; /a/${O} unchanged).`),x(`next: turbobase apps promote ${O} ${W.previewId??"<preview-id>"} # make it live`),x(` turbobase apps preview discard ${W.previewId??"<preview-id>"}`);return}qe()?x(Nt("Deployed",[`${w.bold(O)} ${w.green(`v${W.version??"?"}`)} ${w.dim(W.url??`/a/${O}`)}`])):x(`deployed ${O} \u2192 v${W.version??"?"} (${W.url??`/a/${O}`}).`),await Ce(W,y)}),c.command("promote").description("Make a preview the live version at /a/<slug>. Promotes the exact reviewed bytes \u2014 no rebuild.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to promote (from `apps preview list`).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f,g)=>{let{baseUrl:y,token:_}=await V(g.baseUrl),m=await ee(`promoting ${f}`,()=>z(y,_,d,"promote",{previewId:f}));qe()?x(Nt("Promoted",[`${w.bold(d)} ${w.green(`v${m.version??"?"}`)} ${w.dim(m.url??`/a/${d}`)}`])):x(`promoted ${d} \u2192 v${m.version??"?"} is now live at ${m.url??`/a/${d}`}.`),await Ce(m)});let u=c.command("preview").description("Inspect and manage an app's open previews.");u.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(d,f)=>{let{baseUrl:g,token:y}=await V(f.baseUrl),_=await ie(g,y,d);if(_.previews.length===0){x(`no open previews for ${d}.`);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})`)}}),u.command("discard").description("Close a preview. The URL stops resolving; the version stays in deploy history.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to discard.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f,g)=>{let{baseUrl:y,token:_}=await V(g.baseUrl);await ee(`discarding ${f}`,()=>z(y,_,d,"discard",{previewId:f})),x(`discarded ${f}.`)}),c.command("create").description("Create a new hosted app (a bare app row) so a build can be shipped to it.").argument("<slug>","URL slug the app is served under: /a/<slug>.").option("--name <name>","Display name (defaults to the slug).").option("--description <text>","Optional description.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:g,token:y}=await V(f.baseUrl),_=await ee(`creating ${d}`,()=>p(g,y,{slug:d,name:f.name,description:f.description})),m=_.slug??d;qe()?x(Nt("Created",[`${w.bold(m)} ${w.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 p(d,f,g,y={}){let _=`${d.replace(/\/+$/,"")}/v1/apps`,m;try{m=await fetch(_,{method:"POST",headers:{Authorization:`Bearer ${f}`,"content-type":"application/json"},body:JSON.stringify({slug:g.slug,name:g.name??g.slug,description:g.description})})}catch(S){$(`create request failed: ${S instanceof Error?S.message:String(S)}`)}if(m.status===401&&$("create unauthorized (401) \u2014 re-run `turbobase auth login`."),m.status===403&&$("create forbidden (403) \u2014 the PAT is not for an admin."),m.status===409){if(y.tolerateExisting)return{slug:g.slug,existed:!0};$(`an app with slug "${g.slug}" already exists.`)}return m.ok||$(`create failed: HTTP ${m.status} ${(await m.text().catch(()=>"")).slice(0,200)}`),await m.json().catch(()=>({}))}async function h(d,f,g){let y=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(g)}/pull`,_;try{_=await fetch(y,{headers:{Authorization:`Bearer ${f}`}})}catch(m){$(`pull request failed: ${m instanceof Error?m.message:String(m)}`)}return _.status===401&&$("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),_.status===403&&$("pull forbidden (403) \u2014 the PAT is not for an admin."),_.status===404&&$(`no generated source for "${g}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),_.ok||$(`pull failed: HTTP ${_.status} ${(await _.text().catch(()=>"")).slice(0,200)}`),await _.json()}async function k(d,f,g){let y=pe(d),_=0;for(let[m,S]of Object.entries(f)){let P=pe(y,m);P!==y&&!P.startsWith(y+qc)&&$(`refusing to write outside ${y}: ${m}`),g||await re.stat(P).then(()=>!0).catch(()=>!1)&&$(`${P} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await re.mkdir(Zn(P),{recursive:!0}),await re.writeFile(P,S,"utf8"),_+=1}return _}function b(d){let f=d.indexOf(","),g=d.startsWith("data:")?f>=0?d.slice(f+1):"":d;if(!g)return null;try{let y=Buffer.from(g,"base64");return y.length>0?new Uint8Array(y):null}catch{return null}}async function v(d,f,g){let y=pe(d),_=async(S,P)=>{let A=pe(y,S);A!==y&&!A.startsWith(y+qc)&&$(`refusing to write outside ${y}: ${S}`),g||await re.stat(A).then(()=>!0).catch(()=>!1)&&$(`${A} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await re.mkdir(Zn(A),{recursive:!0}),await re.writeFile(A,P)},m=`# ${f.title||"App change request"}
|
|
1725
1751
|
|
|
1726
1752
|
> Widget proposal \`${f.proposalId}\` \u2014 build this change, then ship it with
|
|
1727
1753
|
> \`turbobase apps deploy ${f.appSlug}\`. The deploy stamps this proposal complete.
|
|
@@ -1731,34 +1757,34 @@ ${f.bodyMarkdown||"_No description provided._"}
|
|
|
1731
1757
|
## Screen context
|
|
1732
1758
|
|
|
1733
1759
|
`+(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.
|
|
1734
|
-
`);if(await _("PROPOSAL.md",m),f.screenshot){let
|
|
1735
|
-
`)}async function k(p){try{let f=await te.readFile(Ve(p,".turbobase","proposal.json"),"utf8"),g=JSON.parse(f);return typeof g.proposalId=="string"&&g.proposalId?g.proposalId:void 0}catch{return}}async function R(p,f,g,y,_,m){let v=new H({baseUrl:p,token:f});try{return await v.appsPush(g,y,{note:_,proposalId:m})}catch(P){if(P instanceof ie){let A=P.body;if(P.status===401&&$("push unauthorized (401) \u2014 re-run `turbobase auth login`."),P.status===403&&A?.error==="admin_required"&&$("push forbidden (403) \u2014 the PAT is not for an admin."),P.status===403&&he(P,"extensions:deploy","push app source"),P.status===404&&$(`no app "${g}" on this instance \u2014 create it with \`turbobase apps create ${g}\`.`),P.status===413&&(A?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&$("push rejected: the request body exceeded the instance limit."),$(`push rejected: ${A?.error??"too large"} (limit ${A?.limit??"?"}).`)),P.status===400){let C=A?.path?` in ${A.path}`:"",O=A?.reason?` (${A.reason})`:"";$(`push rejected: ${A?.error??"bad request"}${O}${C}.`)}}$(`push failed: ${P instanceof Error?P.message:String(P)}`)}}function E(p,f,g){return new Promise((y,_)=>{let m=Uc("npm",p,{cwd:f,stdio:"inherit",...g?{env:{...process.env,...g}}:{}});m.on("error",_),m.on("exit",v=>v===0?y():_(new Error(`npm ${p.join(" ")} exited ${v??"?"}`)))})}async function I(p,f,g,y){let _=`${p.replace(/\/+$/,"")}${g}`,m;try{m=await fetch(_,{method:y.method,headers:{Authorization:`Bearer ${f}`,...y.body?{"content-type":"application/json"}:{}},...y.body?{body:JSON.stringify(y.body)}:{}})}catch(v){$(`request failed: ${v instanceof Error?v.message:String(v)}`)}if(m.status===401&&$("unauthorized (401) \u2014 re-run `turbobase auth login`."),m.status===403&&$("forbidden (403) \u2014 the PAT is not for an admin."),!m.ok){let v=await m.text().catch(()=>""),P=v.slice(0,300);try{let A=JSON.parse(v);P=A.message??A.error??P}catch{}$(`failed: HTTP ${m.status} ${P}`)}return await m.json().catch(()=>({}))}async function L(p,f,g,y,_){return await I(p,f,`/v1/apps/${encodeURIComponent(g)}/preview/${y}`,{method:"POST",body:_})}async function ne(p,f,g){return{previews:(await I(p,f,`/v1/apps/${encodeURIComponent(g)}/previews`,{method:"GET"})).previews??[]}}async function F(p,f,g,y,_,m,v,P){let A;try{A=await ue(`zipping ${y}`,()=>$d(y))}catch(N){$(`could not zip ${y}: ${N instanceof Error?N.message:String(N)}`)}A.fileCount===0&&$(`${y} 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),v&&(C["x-app-build-id"]=v.buildId,C["x-app-asset-base"]=v.assetBase),P&&(C["x-app-channel"]="preview",P.label&&(C["x-app-preview-label"]=encodeURIComponent(P.label)));let O=`${p.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(g)}/deploy`,V;try{V=await ue(`deploying ${g} (${A.fileCount} file${A.fileCount===1?"":"s"})`,()=>fetch(O,{method:"POST",headers:C,body:new Uint8Array(A.buffer)}))}catch(N){$(`deploy request failed: ${N instanceof Error?N.message:String(N)}`)}if(V.status===401&&$("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),V.status===403&&$("deploy forbidden (403) \u2014 the PAT is not for an admin."),V.status===404&&$(`no app "${g}" on ${p} \u2014 create it with \`turbobase apps create ${g}\`.`),!V.ok){let N=await V.text().catch(()=>""),ee=N.slice(0,300);try{let W=JSON.parse(N);ee=W.message??W.error??ee}catch{}$(`deploy failed: HTTP ${V.status} ${ee}`)}return await V.json().catch(()=>({}))}async function Ce(p,f){let g=zd(p,{localDocsModifiedAt:await Ue(f)});g&&x(g.level==="warn"?T.yellow(g.message):T.dim(g.message))}async function Ue(p){if(!p)return null;let f=null;for(let g of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let y=await te.stat(Ve(p,g));(f===null||y.mtimeMs>f)&&(f=y.mtimeMs)}catch{}return f===null?null:new Date(f)}c.command("pull").description("Write an app's generated source tree to disk (from the proposal that generated it).").argument("[app]","App slug or id. Omit when using --proposal (the app is derived from it).").argument("[dir]","Directory to write into (default ./<slug>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--force","Overwrite existing files.").option("--proposal <id>","Pull the app behind a widget proposal + its request context.").action(async(p,f,g)=>{let{baseUrl:y,token:_}=await G(g.baseUrl);if(g.proposal){let A=new H({baseUrl:y,token:_}),C;try{C=await ue(`fetching proposal ${g.proposal}`,()=>A.appPullContext(g.proposal))}catch(W){he(W,"extensions:deploy","pull proposal"),W instanceof ie&&W.status===404&&$(`no widget proposal "${g.proposal}" on ${y}.`),$(`could not fetch proposal ${g.proposal}: ${W instanceof Error?W.message:String(W)}`)}let O=await ue(`pulling ${C.appSlug}`,()=>h(y,_,C.appSlug)),V=f??p,N=ce(process.cwd(),V??C.appSlug);await te.mkdir(N,{recursive:!0});let ee=await S(N,O.files,!!g.force);await w(N,C,!!g.force),x(`pulled ${ee} file${ee===1?"":"s"} \u2192 ${N} (rev ${O.rev}), linked to proposal ${C.proposalId}.`),x(`next: cd ${Ho(process.cwd(),N)||"."} && turbobase apps deploy ${C.appSlug}`);return}p||$("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let m=await ue(`pulling ${p}`,()=>h(y,_,p)),v=ce(process.cwd(),f??m.slug??p);await te.mkdir(v,{recursive:!0});let P=await S(v,m.files,!!g.force);x(`pulled ${P} file${P===1?"":"s"} \u2192 ${v} (rev ${m.rev}).`),x(`next: cd ${Ho(process.cwd(),v)||"."} && turbobase apps deploy ${m.slug}`)}),c.command("init").description("Scaffold a new app project locally, wired to your instance and to Claude Code.").argument("<app>","App slug \u2014 also the /a/<slug> mount path the build is pinned to.").argument("[dir]","Directory to scaffold into (default ./<app>).").option("--title <text>","Display title used in index.html and the starter component.").option("--base-url <url>","Instance to wire the project to (defaults to the active instance).").option("--no-claude","Skip the Claude Code wiring (CLAUDE.md, .mcp.json, .claude/).").option("--force","Overwrite existing files.").action(async(p,f,g)=>{let y=ce(process.cwd(),f??p),_=await ht(g.baseUrl).catch(()=>null),{scaffoldAppFiles:m,starterApp:v}=await Promise.resolve().then(()=>(Ru(),Tu)),P=g.title??p,A=m({slug:p,title:P,appTsx:v(P),instanceOrigin:_?.baseUrl});await te.mkdir(y,{recursive:!0});let C=await S(y,A,!!g.force);if(x(`scaffolded ${C} file${C===1?"":"s"} \u2192 ${y}`),g.claude!==!1){let V=ki({baseUrl:_?.baseUrl,token:_?.token,appSlug:p}),N=0;for(let ee of V){let W=await ig(Ve(y,ee.path),ee);(W==="wrote"||W==="merged")&&(N+=1)}x(`wired Claude Code: ${N} file${N===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(),y)||".";x(`next: cd ${O} && npm install && npm run dev`),x(` turbobase apps create ${p}`),x(` turbobase apps push ${p} .`),x(` turbobase apps deploy ${p} .`)}),c.command("list").description("List the hosted apps on your instance.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async p=>{let{baseUrl:f,token:g}=await G(p.baseUrl),y=new H({baseUrl:f,token:g}),_;try{_=await y.appsList()}catch(m){he(m,"extensions:deploy","list apps"),$(`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"]}))}),c.command("push").description("Record the local source tree as the app's newest source revision (does NOT deploy).").argument("<app>","App slug or id.").argument("[dir]","Source directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--note <text>","Short note stored with the revision.").option("--proposal <id>","Widget proposal this rev works (defaults to .turbobase/proposal.json).").action(async(p,f,g)=>{let y=ce(process.cwd(),f??".");await te.stat(y).then(W=>W.isDirectory()).catch(()=>!1)||$(`${y} is not a directory.`);let{baseUrl:m,token:v}=await G(g.baseUrl),P=g.proposal??await k(y),{files:A,skipped:C,secrets:O,unstorable:V}=await Zd(y),N=Object.keys(A).length;if(N===0&&$(`no source files found under ${y} (build output and node_modules are skipped).`),V.length>0){for(let W of V)pe(`${W} contains a NUL byte (U+0000), which cannot be stored.`);$(`push aborted: ${V.length} ${V.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let W of C)pe(T.dim(`skipped binary file ${W}`));for(let W of O)pe(T.dim(`skipped ${W} (holds credentials \u2014 never pushed)`));let ee=await ue(`pushing ${N} file${N===1?"":"s"}`,()=>R(m,v,p,A,g.note,P));x(`pushed ${ee.files} file${ee.files===1?"":"s"} \u2192 ${ee.slug} rev ${ee.rev} (source only, nothing deployed).`),x(`next: turbobase apps deploy ${ee.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 Nc(),{baseUrl:g,token:y}=await G(p.baseUrl),_=new H({baseUrl:g,token:y}),m;try{m=await ue(`planning against ${p.to??g}`,()=>_.configPlan(f))}catch(v){$(`plan failed: ${v instanceof Error?v.message:String(v)}`)}c0(m,p.to??g)}),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 Nc(),{baseUrl:g,token:y}=await G(p.baseUrl),_=f.tenant??d0(g),m=pu(p.confirm,_);m.ok||$(`promote refused (fail-closed): ${m.reason}`);let v=new H({baseUrl:g,token:y});try{let P=await ue(`promoting ${p.from} \u2192 ${p.to} (${_})`,()=>v.configApply(f));if(qe()){let A=[`${T.bold(`${p.from} \u2192 ${p.to}`)} ${T.dim(_??"")}`,`${Ot.add(String(P.applied.add))} ${Ot.change(String(P.applied.change))} ${Ot.destroy(String(P.applied.destroy))}`];P.backfillsQueued.length&&A.push(T.dim(`${P.backfillsQueued.length} backfill(s) queued`)),x(Nt("Promoted",A))}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 ie&&P.status===403&&$("promote forbidden (403) \u2014 the stored PAT is not for an admin."),$(`promote failed: ${P instanceof Error?P.message:String(P)}`)}});let Jr=async(p,f)=>{let{baseUrl:g,token:y}=await G(f.baseUrl),_=new H({baseUrl:g,token:y}),m=f.limit?Number(f.limit):void 0;if(f.follow){try{await Od(_,p,{follow:!0,limit:m,intervalMs:f.intervalMs?Number(f.intervalMs):void 0,sink:x})}catch(v){$(`logs --follow failed: ${v instanceof Error?v.message:String(v)}`)}return}try{let v=await _.logs(p,m);v.length===0&&x(`no logs for ${p}.`);for(let P of v)x(` [${P.level}] ${P.ts??""} ${P.message}`)}catch(v){$(`logs failed: ${v instanceof Error?v.message:String(v)}`)}};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(Jr),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 g=Oc(f.reporter),y=ce(process.cwd(),p),_=await tn(y),m=Td(_);g?x(hs(i0(p,m),g)):x(Rd(p,m,{warn:T.yellow,ok:T.green,dim:T.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 g=Oc(f.reporter),y=await bd(ce(process.cwd(),p));if(f.against){f.against!=="sandbox"&&$(`unknown --against target '${f.against}' (only 'sandbox' is supported).`);try{await gd(mi(y))}catch(v){$(v instanceof Error?v.message:String(v))}return}f.fixture||$("replay needs a --fixture <file> (offline) or --against sandbox (online).");let _;try{_=await yd(ce(process.cwd(),f.fixture))}catch(v){$(`could not read fixture ${f.fixture}: ${v instanceof Error?v.message:String(v)}`)}let m=await md(y,_,f.fixture);if(g){let v=a0(m);x(hs(v,g)),v.cases.some(P=>P.status==="failed")&&process.exit(1);return}x(wd(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:g}=await G(p.baseUrl),y=new H({baseUrl:f,token:g});try{await Nd(y,{status:p.status,retry:p.retry,limit:p.limit?Number(p.limit):void 0,sink:x})}catch(_){_ instanceof ie&&_.status===403&&$("forbidden (403) \u2014 binding --retry requires an admin PAT."),_ instanceof ie&&_.status===409&&$("binding is not retryable (only divergent/blocked bindings can be retried)."),$(`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 g=p.lastIndexOf("@"),y=g>0?p.slice(0,g):p,_=g>0?p.slice(g+1):void 0,m=ci();m||$(`marketplace not configured \u2014 set ${gr} and ${ds}.
|
|
1736
|
-
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let
|
|
1737
|
-
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let y=
|
|
1738
|
-
project init: ${y} written, ${m} merged, ${_} skipped.`)}),
|
|
1760
|
+
`);if(await _("PROPOSAL.md",m),f.screenshot){let S=b(f.screenshot);S&&await _("proposal-screenshot.png",S)}await _(Ve(".turbobase","proposal.json"),`${JSON.stringify({proposalId:f.proposalId},null,2)}
|
|
1761
|
+
`)}async function T(d){try{let f=await re.readFile(Ve(d,".turbobase","proposal.json"),"utf8"),g=JSON.parse(f);return typeof g.proposalId=="string"&&g.proposalId?g.proposalId:void 0}catch{return}}async function R(d,f,g,y,_,m){let S=new B({baseUrl:d,token:f});try{return await S.appsPush(g,y,{note:_,proposalId:m})}catch(P){if(P instanceof se){let A=P.body;if(P.status===401&&$("push unauthorized (401) \u2014 re-run `turbobase auth login`."),P.status===403&&A?.error==="admin_required"&&$("push forbidden (403) \u2014 the PAT is not for an admin."),P.status===403&&ce(P,"extensions:deploy","push app source"),P.status===404&&$(`no app "${g}" on this instance \u2014 create it with \`turbobase apps create ${g}\`.`),P.status===413&&(A?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&$("push rejected: the request body exceeded the instance limit."),$(`push rejected: ${A?.error??"too large"} (limit ${A?.limit??"?"}).`)),P.status===400){let C=A?.path?` in ${A.path}`:"",O=A?.reason?` (${A.reason})`:"";$(`push rejected: ${A?.error??"bad request"}${O}${C}.`)}}$(`push failed: ${P instanceof Error?P.message:String(P)}`)}}function E(d,f,g){return new Promise((y,_)=>{let m=Mc("npm",d,{cwd:f,stdio:"inherit",...g?{env:{...process.env,...g}}:{}});m.on("error",_),m.on("exit",S=>S===0?y():_(new Error(`npm ${d.join(" ")} exited ${S??"?"}`)))})}async function I(d,f,g,y){let _=`${d.replace(/\/+$/,"")}${g}`,m;try{m=await fetch(_,{method:y.method,headers:{Authorization:`Bearer ${f}`,...y.body?{"content-type":"application/json"}:{}},...y.body?{body:JSON.stringify(y.body)}:{}})}catch(S){$(`request failed: ${S instanceof Error?S.message:String(S)}`)}if(m.status===401&&$("unauthorized (401) \u2014 re-run `turbobase auth login`."),m.status===403&&$("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 A=JSON.parse(S);P=A.message??A.error??P}catch{}$(`failed: HTTP ${m.status} ${P}`)}return await m.json().catch(()=>({}))}async function z(d,f,g,y,_){return await I(d,f,`/v1/apps/${encodeURIComponent(g)}/preview/${y}`,{method:"POST",body:_})}async function ie(d,f,g){return{previews:(await I(d,f,`/v1/apps/${encodeURIComponent(g)}/previews`,{method:"GET"})).previews??[]}}async function H(d,f,g,y,_,m,S,P){let A;try{A=await ee(`zipping ${y}`,()=>Ru(y))}catch(N){$(`could not zip ${y}: ${N instanceof Error?N.message:String(N)}`)}A.fileCount===0&&$(`${y} 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=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(g)}/deploy`,G;try{G=await ee(`deploying ${g} (${A.fileCount} file${A.fileCount===1?"":"s"})`,()=>fetch(O,{method:"POST",headers:C,body:new Uint8Array(A.buffer)}))}catch(N){$(`deploy request failed: ${N instanceof Error?N.message:String(N)}`)}if(G.status===401&&$("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),G.status===403&&$("deploy forbidden (403) \u2014 the PAT is not for an admin."),G.status===404&&$(`no app "${g}" on ${d} \u2014 create it with \`turbobase apps create ${g}\`.`),!G.ok){let N=await G.text().catch(()=>""),ne=N.slice(0,300);try{let W=JSON.parse(N);ne=W.message??W.error??ne}catch{}$(`deploy failed: HTTP ${G.status} ${ne}`)}return await G.json().catch(()=>({}))}async function Ce(d,f){let g=Du(d,{localDocsModifiedAt:await Ue(f)});g&&x(g.level==="warn"?w.yellow(g.message):w.dim(g.message))}async function Ue(d){if(!d)return null;let f=null;for(let g of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let y=await re.stat(Ve(d,g));(f===null||y.mtimeMs>f)&&(f=y.mtimeMs)}catch{}return f===null?null:new Date(f)}c.command("pull").description("Write an app's generated source tree to disk (from the proposal that generated it).").argument("[app]","App slug or id. Omit when using --proposal (the app is derived from it).").argument("[dir]","Directory to write into (default ./<slug>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--force","Overwrite existing files.").option("--proposal <id>","Pull the app behind a widget proposal + its request context.").action(async(d,f,g)=>{let{baseUrl:y,token:_}=await V(g.baseUrl);if(g.proposal){let A=new B({baseUrl:y,token:_}),C;try{C=await ee(`fetching proposal ${g.proposal}`,()=>A.appPullContext(g.proposal))}catch(W){ce(W,"extensions:deploy","pull proposal"),W instanceof se&&W.status===404&&$(`no widget proposal "${g.proposal}" on ${y}.`),$(`could not fetch proposal ${g.proposal}: ${W instanceof Error?W.message:String(W)}`)}let O=await ee(`pulling ${C.appSlug}`,()=>h(y,_,C.appSlug)),G=f??d,N=pe(process.cwd(),G??C.appSlug);await re.mkdir(N,{recursive:!0});let ne=await k(N,O.files,!!g.force);await v(N,C,!!g.force),x(`pulled ${ne} file${ne===1?"":"s"} \u2192 ${N} (rev ${O.rev}), linked to proposal ${C.proposalId}.`),x(`next: cd ${Go(process.cwd(),N)||"."} && turbobase apps deploy ${C.appSlug}`);return}d||$("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let m=await ee(`pulling ${d}`,()=>h(y,_,d)),S=pe(process.cwd(),f??m.slug??d);await re.mkdir(S,{recursive:!0});let P=await k(S,m.files,!!g.force);x(`pulled ${P} file${P===1?"":"s"} \u2192 ${S} (rev ${m.rev}).`),x(`next: cd ${Go(process.cwd(),S)||"."} && turbobase apps deploy ${m.slug}`)}),c.command("init").description("Scaffold a new app project locally, wired to your instance and to Claude Code.").argument("<app>","App slug \u2014 also the /a/<slug> mount path the build is pinned to.").argument("[dir]","Directory to scaffold into (default ./<app>).").option("--title <text>","Display title used in index.html and the starter component.").option("--base-url <url>","Instance to wire the project to (defaults to the active instance).").option("--no-claude","Skip the Claude Code wiring (CLAUDE.md, .mcp.json, .claude/).").option("--force","Overwrite existing files.").action(async(d,f,g)=>{let y=pe(process.cwd(),f??d),_=await gt(g.baseUrl).catch(()=>null),{scaffoldAppFiles:m,starterApp:S}=await Promise.resolve().then(()=>(zd(),Ld)),P=g.title??d,A=m({slug:d,title:P,appTsx:S(P),instanceOrigin:_?.baseUrl});await re.mkdir(y,{recursive:!0});let C=await k(y,A,!!g.force);if(x(`scaffolded ${C} file${C===1?"":"s"} \u2192 ${y}`),g.claude!==!1){let G=Ti({baseUrl:_?.baseUrl,token:_?.token,appSlug:d}),N=0;for(let ne of G){let W=await gg(Ve(y,ne.path),ne);(W==="wrote"||W==="merged")&&(N+=1)}x(`wired Claude Code: ${N} file${N===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),_||Z("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=Go(process.cwd(),y)||".";x(`next: cd ${O} && npm install && npm run dev`),x(` turbobase apps create ${d}`),x(` turbobase apps push ${d} .`),x(` turbobase apps deploy ${d} .`)}),c.command("list").description("List the hosted apps on your instance.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:f,token:g}=await V(d.baseUrl),y=new B({baseUrl:f,token:g}),_;try{_=await y.appsList()}catch(m){ce(m,"extensions:deploy","list apps"),$(`list apps failed: ${m instanceof Error?m.message:String(m)}`)}if(d.json)return x(JSON.stringify(_,null,2));if(_.length===0)return x("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");x(Xt(_.map(m=>[m.slug,m.name,m.deployed?"yes":"no",m.sourceRev===null?"\u2014":`rev ${m.sourceRev}`,m.audience]),{head:["SLUG","NAME","LIVE","SOURCE","AUDIENCE"]}))}),c.command("push").description("Record the local source tree as the app's newest source revision (does NOT deploy).").argument("<app>","App slug or id.").argument("[dir]","Source directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--note <text>","Short note stored with the revision.").option("--proposal <id>","Widget proposal this rev works (defaults to .turbobase/proposal.json).").action(async(d,f,g)=>{let y=pe(process.cwd(),f??".");await re.stat(y).then(W=>W.isDirectory()).catch(()=>!1)||$(`${y} is not a directory.`);let{baseUrl:m,token:S}=await V(g.baseUrl),P=g.proposal??await T(y),{files:A,skipped:C,secrets:O,unstorable:G}=await id(y),N=Object.keys(A).length;if(N===0&&$(`no source files found under ${y} (build output and node_modules are skipped).`),G.length>0){for(let W of G)Z(`${W} contains a NUL byte (U+0000), which cannot be stored.`);$(`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 W of C)Z(w.dim(`skipped binary file ${W}`));for(let W of O)Z(w.dim(`skipped ${W} (holds credentials \u2014 never pushed)`));let ne=await ee(`pushing ${N} file${N===1?"":"s"}`,()=>R(m,S,d,A,g.note,P));x(`pushed ${ne.files} file${ne.files===1?"":"s"} \u2192 ${ne.slug} rev ${ne.rev} (source only, nothing deployed).`),x(`next: turbobase apps deploy ${ne.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 d=>{let f=await zc(),{baseUrl:g,token:y}=await V(d.baseUrl),_=new B({baseUrl:g,token:y}),m;try{m=await ee(`planning against ${d.to??g}`,()=>_.configPlan(f))}catch(S){$(`plan failed: ${S instanceof Error?S.message:String(S)}`)}SR(m,d.to??g)}),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 d=>{let f=await zc(),{baseUrl:g,token:y}=await V(d.baseUrl),_=f.tenant??kR(g),m=kd(d.confirm,_);m.ok||$(`promote refused (fail-closed): ${m.reason}`);let S=new B({baseUrl:g,token:y});try{let P=await ee(`promoting ${d.from} \u2192 ${d.to} (${_})`,()=>S.configApply(f));if(qe()){let A=[`${w.bold(`${d.from} \u2192 ${d.to}`)} ${w.dim(_??"")}`,`${Ot.add(String(P.applied.add))} ${Ot.change(String(P.applied.change))} ${Ot.destroy(String(P.applied.destroy))}`];P.backfillsQueued.length&&A.push(w.dim(`${P.backfillsQueued.length} backfill(s) queued`)),x(Nt("Promoted",A))}else x(`promoted ${d.from} \u2192 ${d.to} (${_}): +${P.applied.add} ~${P.applied.change} -${P.applied.destroy}`+(P.backfillsQueued.length?` (${P.backfillsQueued.length} backfill(s) queued)`:""))}catch(P){P instanceof se&&P.status===403&&$("promote forbidden (403) \u2014 the stored PAT is not for an admin."),$(`promote failed: ${P instanceof Error?P.message:String(P)}`)}});let Qn=async(d,f)=>{let{baseUrl:g,token:y}=await V(f.baseUrl),_=new B({baseUrl:g,token:y}),m=f.limit?Number(f.limit):void 0;if(f.follow){try{await Lu(_,d,{follow:!0,limit:m,intervalMs:f.intervalMs?Number(f.intervalMs):void 0,sink:x})}catch(S){$(`logs --follow failed: ${S instanceof Error?S.message:String(S)}`)}return}try{let S=await _.logs(d,m);S.length===0&&x(`no logs for ${d}.`);for(let P of S)x(` [${P.level}] ${P.ts??""} ${P.message}`)}catch(S){$(`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(Qn),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(d,f)=>{let g=Lc(f.reporter),y=pe(process.cwd(),d),_=await sr(y),m=Pu(_);g?x(gs(bR(d,m),g)):x(Au(d,m,{warn:w.yellow,ok:w.green,dim:w.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(d,f)=>{let g=Lc(f.reporter),y=await Su(pe(process.cwd(),d));if(f.against){f.against!=="sandbox"&&$(`unknown --against target '${f.against}' (only 'sandbox' is supported).`);try{await wu(bi(y))}catch(S){$(S instanceof Error?S.message:String(S))}return}f.fixture||$("replay needs a --fixture <file> (offline) or --against sandbox (online).");let _;try{_=await vu(pe(process.cwd(),f.fixture))}catch(S){$(`could not read fixture ${f.fixture}: ${S instanceof Error?S.message:String(S)}`)}let m=await bu(y,_,f.fixture);if(g){let S=wR(m);x(gs(S,g)),S.cases.some(P=>P.status==="failed")&&process.exit(1);return}x(ku(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 d=>{let{baseUrl:f,token:g}=await V(d.baseUrl),y=new B({baseUrl:f,token:g});try{await zu(y,{status:d.status,retry:d.retry,limit:d.limit?Number(d.limit):void 0,sink:x})}catch(_){_ instanceof se&&_.status===403&&$("forbidden (403) \u2014 binding --retry requires an admin PAT."),_ instanceof se&&_.status===409&&$("binding is not retryable (only divergent/blocked bindings can be retried)."),$(`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(d,f)=>{let g=d.lastIndexOf("@"),y=g>0?d.slice(0,g):d,_=g>0?d.slice(g+1):void 0,m=pi();m||$(`marketplace not configured \u2014 set ${bn} and ${ps}.
|
|
1762
|
+
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let S=fi(m.registryUrl);S&&$(S);let{baseUrl:P,token:A}=await V(f.baseUrl),C=new tr(m),O;try{O=await ee(`fetching ${d}`,()=>C.fetchBundle(y,_))}catch(X){$(`marketplace fetch failed for ${d}: ${X instanceof Error?X.message:String(X)}`)}let G=os(O.manifest),N=null;if(G.length>0){if(!f.connection){let X=G.map(Ge=>Ge.source_system).join(", ");$(`${O.name}@${O.version} declares a connection input (source: ${X}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}N=f.connection}let ne=vR(O.bundle,O.name,O.kind),W=new B({baseUrl:P,token:A});try{let X=await ee(`installing ${O.name}@${O.version}`,()=>W.deploy({...ne,provenance:"marketplace",...N?{connectionId:N}:{}}));x(`installed ${O.name}@${O.version} \u2192 ${X.id} (status=${X.status}, ${X.outcome})`+(N?` bound to connection ${N}.`:"."))}catch(X){X instanceof se&&X.status===403&&$("install forbidden (403) \u2014 the stored PAT is not for an admin."),$(`install failed: ${X instanceof Error?X.message:String(X)}`)}}),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(d,f)=>{let g=pi();g||$(`marketplace not configured \u2014 set ${bn} and ${ps}.
|
|
1763
|
+
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let y=fi(g.registryUrl);y&&$(y);let _=pe(process.cwd(),d),m=await sr(_),S=/\bdefineConduit\s*[<(]/.test(m)?"conduit":"hook",P={};if(f.manifest){let O=pe(process.cwd(),f.manifest),G;try{G=await re.readFile(O,"utf8")}catch{$(`manifest not found at ${f.manifest}.`)}let N;try{N=JSON.parse(G)}catch{$(`manifest is not valid JSON: ${f.manifest}.`)}(typeof N!="object"||N===null||Array.isArray(N))&&$("manifest must be a JSON object."),P=N}try{Yo(P,m)}catch(O){O instanceof At&&$(O.message),$(`manifest validation failed: ${O instanceof Error?O.message:String(O)}`)}let A=new tr(g);try{await ee(`publishing ${f.name}@${f.pkgVersion}`,()=>A.publish({name:f.name,version:f.pkgVersion,kind:S,bundle:m,manifest:P}))}catch(O){O instanceof se&&O.status===403&&$("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),O instanceof se&&O.status===409&&$(`version already published \u2014 ${f.name}@${f.pkgVersion} exists. Bump the version.`),$(`publish failed: ${O instanceof Error?O.message:String(O)}`)}let C=os(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.`)}),r.command("init").description("Scaffold a Claude-Code extension project in the current dir.").option("--base-url <url>","Instance to wire .mcp.json to (defaults to the active instance).").action(async d=>{let f=await gt(d.baseUrl).catch(()=>null),g=Ti({baseUrl:f?.baseUrl,token:f?.token}),y=0,_=0,m=0;for(let S of g){let P=pe(process.cwd(),S.path),A=await gg(P,S);A==="wrote"?(y+=1,x(` wrote ${S.path}`)):A==="merged"?(m+=1,x(` merged ${S.path} (added the .mcp.json rule)`)):(_+=1,x(` skipped ${S.path} (exists)`))}x(`
|
|
1764
|
+
project init: ${y} written, ${m} merged, ${_} skipped.`)}),r.command("ci").description(`Write the reusable release-deploy GitHub Action to ${xi} (non-destructive).`).action(async()=>{let d=qu(),f=0,g=0;for(let y of d){let _=pe(process.cwd(),y.path);await Yn(_,y.content,y.executable)==="wrote"?(f+=1,x(` wrote ${y.path}`)):(g+=1,x(` skipped ${y.path} (exists)`))}x(`
|
|
1739
1765
|
project ci: ${f} written, ${g} skipped.`),f>0&&(x(`
|
|
1740
|
-
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."))}),
|
|
1741
|
-
`;
|
|
1742
|
-
samples init: ${P} written, ${A} skipped.`)});let
|
|
1743
|
-
`+T.dim("create one with `turbobase guardrails create <name> --source <s> --when '\u2026'`"));x(Qt(_.map(Zt),{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:g,token:y}=await G(f.baseUrl),_=new H({baseUrl:g,token:y}),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(v){he(v,"extensions:deploy","create a guardrail"),$(`create guardrail failed: ${v instanceof Error?v.message:String(v)}`)}x(`${T.green("\u2713")} guardrail ${T.bold(m.name)} created${m.enabled?"":T.dim(" (parked \u2014 enable it to take effect)")}`),x(T.dim(` denies ${m.source}/${m.record}${m.when?` where ${m.when}`:" (always)"}`)),x(T.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&&$("edit: nothing to change \u2014 pass --when, --message or --note.");let{baseUrl:g,token:y}=await G(f.baseUrl),_=new H({baseUrl:g,token:y}),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(v){he(v,"extensions:deploy","edit a guardrail"),$(`edit guardrail failed: ${v instanceof Error?v.message:String(v)}`)}x(`${T.green("\u2713")} guardrail ${T.bold(m.name)} updated`),x(T.dim(` denies ${m.source}/${m.record}${m.when?` where ${m.when}`:" (always)"}`))});for(let[p,f,g]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(y,_)=>{let{baseUrl:m,token:v}=await G(_.baseUrl),P=new H({baseUrl:m,token:v});try{await P.guardrailUpdate(y,{enabled:f})}catch(A){he(A,"extensions:deploy",`${p} a guardrail`),$(`${p} guardrail failed: ${A instanceof Error?A.message:String(A)}`)}x(`${T.green("\u2713")} guardrail ${T.bold(y)} ${g}`),f||x(T.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:g,token:y}=await G(f.baseUrl),_=new H({baseUrl:g,token:y});try{await _.guardrailDelete(p)}catch(m){he(m,"extensions:deploy","delete a guardrail"),$(`delete guardrail failed: ${m instanceof Error?m.message:String(m)}`)}x(`${T.green("\u2713")} guardrail ${T.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(v){$(`--fields must be valid JSON: ${v instanceof Error?v.message:String(v)}`)}let{baseUrl:g,token:y}=await G(p.baseUrl),_=new H({baseUrl:g,token:y}),m;try{m=await _.guardrailTest({source:p.source,record:p.record,...p.origin?{origin:p.origin}:{},...f?{fields:f}:{}})}catch(v){he(v,"extensions:deploy","test guardrails"),$(`guardrails test failed: ${v instanceof Error?v.message:String(v)}`)}if(p.json)return x(JSON.stringify(m,null,2));m.allowed?x(`${T.green("\u2713")} ${p.source}/${p.record} \u2014 no guardrail blocks this write`):(x(`${T.red("\u2717")} ${p.source}/${p.record} \u2014 blocked by ${T.bold(m.blockedBy??"?")}`),m.message&&x(T.dim(` ${m.message}`))),m.undecided.length>0&&(x(T.yellow(` ${m.undecided.length} rule(s) need a row to decide: ${m.undecided.join(", ")}`)),x(T.dim(` re-run with --fields '{"\u2026":"\u2026"}' to evaluate them.`))),m.allowed||(process.exitCode=1)});let St=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),fr=(p,f={})=>{let g=`${T.bold(p.table)} ${T.dim(p.displayName)}`;x(p.exists===!1?`${g} ${T.dim("(new)")}`:g);for(let y of p.fields){let _=[y.required?"required":null].filter(Boolean).join(", "),m=f.showClaimants&&y.claimedBy?.length?` ${T.dim(`\u2190 ${y.claimedBy.join(", ")}`)}`:"";x(` ${y.column.padEnd(28)} ${y.type}${_?` (${_})`:""}${m}`)}f.showClaimants&&p.claimants.length>1&&x(T.dim(` claimed by ${p.claimants.join(", ")}`))};function hr(p){if(p instanceof ie&&p.status===409){let f=p.body;f?.error==="table_conflict"&&f.message&&(pe(f.message),process.exit(1))}$(`tables: ${p instanceof Error?p.message:String(p)}`)}let es=async p=>{let f=Ve(ce(process.cwd(),p),"public","turbobase.json"),g=await te.readFile(f,"utf8").catch(()=>null);if(g===null)return null;let y;try{y=JSON.parse(g)}catch(m){$(`${f} is not valid JSON: ${m instanceof Error?m.message:String(m)}`)}let _=y.tables;return _===void 0?{tables:[],manifestPath:f}:(Array.isArray(_)||$(`${f}: "tables" must be an array.`),{tables:_,manifestPath:f})};St.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:g}=await G(p.baseUrl),y=new H({baseUrl:f,token:g}),_;try{_=await y.tablesList()}catch(m){he(m,"extensions:deploy","list tables"),$(`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"]}))}),St.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 g=await es(p??".");if(g||$(`no public/turbobase.json under ${ce(process.cwd(),p??".")}.`),g.tables.length===0)return x(`${g.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:y,token:_}=await G(f.baseUrl),m=new H({baseUrl:y,token:_}),v;try{v=await ue("planning tables",()=>m.tablesPlan({claimedBy:f.as,tables:g.tables}))}catch(P){he(P,"extensions:deploy","plan tables"),hr(P)}x(`claiming as ${T.bold(v.claimedBy)}`);for(let P of v.tables)fr(P,{showClaimants:!0});x(""),x(T.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),St.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 g=await es(p??".");if(g||$(`no public/turbobase.json under ${ce(process.cwd(),p??".")}.`),g.tables.length===0)return x(`${g.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:y,token:_}=await G(f.baseUrl),m=new H({baseUrl:y,token:_}),v;try{v=await ue("applying tables",()=>m.tablesApply({claimedBy:f.as,tables:g.tables}))}catch(P){he(P,"extensions:deploy","apply tables"),hr(P)}for(let P of v.tables)fr(P,{showClaimants:!0});x(`applied ${v.tables.length} table${v.tables.length===1?"":"s"} as ${v.claimedBy}.`)}),St.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 g=f.field.map(P=>{let[A,C,O]=P.split(":");return(!A||!C)&&$(`--field "${P}" must be name:type[:required] (e.g. title:text:required).`),O!==void 0&&O!=="required"&&$(`--field "${P}": the third part may only be "required".`),{name:A,type:C,...O==="required"?{required:!0}:{}}}),{baseUrl:y,token:_}=await G(f.baseUrl),m=new H({baseUrl:y,token:_}),v;try{v=await ue(`creating cr_${p}`,()=>m.tablesApply({tables:[{slug:p,displayName:f.name??p,fields:g,...f.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(P){he(P,"extensions:deploy","create a table"),hr(P)}for(let P of v.tables)fr(P);x(""),x(T.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),St.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&&$(`drop refused: --confirm "${f.confirm}" does not match "${p}".`);let{baseUrl:g,token:y}=await G(f.baseUrl),_=new H({baseUrl:g,token:y}),m;try{m=await ue(`dropping cr_${p}`,()=>_.tablesDrop(p,f.confirm))}catch(v){he(v,"extensions:deploy","drop a table"),$(`drop failed: ${v instanceof Error?v.message:String(v)}`)}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 Ko=e.command("sandbox").description("Ephemeral local authoring sandboxes.");Ko.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=jc(),g;try{g=await au(f,{fromTenant:p.from,ttl:p.ttl,sample:p.sample,baseUrl:p.baseUrl})}catch(y){y instanceof an&&$(y.message),$(`sandbox create failed: ${y instanceof Error?y.message:String(y)}`)}x(`sandbox ${g.name} ready.`),x(` source: ${g.fromTenant} (sampled ${Math.round(g.sampleFraction*100)}%, redacted)`),x(` url: ${g.url}`),x(` expires: ${g.expiresAt}`)}),Ko.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=jc();await zi(f).catch(()=>[]);let g;try{g=await lu(f,p)}catch(y){$(`sandbox destroy failed: ${y instanceof Error?y.message:String(y)}`)}g||$(`no sandbox named '${p}'.`),x(`destroyed sandbox ${g.name} (dropped ${g.database}).`)}),Ko.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let p=jc(),f=await zi(p).catch(()=>[]),g=await bs(),{active:y}=ji(g);if(y.length===0)x("no active sandboxes.");else{for(let _ of y)x(` ${_.name} from=${_.fromTenant} expires=${_.expiresAt} ${_.url}`);x(`
|
|
1744
|
-
${y.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.",
|
|
1745
|
-
`,
|
|
1746
|
-
`).length} lines).`)});let
|
|
1747
|
-
run \`${
|
|
1748
|
-
${
|
|
1749
|
-
These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},m=g.filter(A=>A!=="isolated-vm");if(m.length>0){let A=m.map(C=>`${C}@${
|
|
1766
|
+
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."))}),r.command("samples").description("Generate samples/<recordType>.json fixtures from the live instance catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Output directory for the fixtures","samples").option("--event <event>","Lifecycle event to stamp on each fixture","before_save").option("--force","Overwrite existing fixture files (default: skip files that exist).").action(async d=>{let{baseUrl:f,token:g}=await V(d.baseUrl),y=new B({baseUrl:f,token:g}),_;try{_=await y.catalogRecords()}catch(C){C instanceof se&&(C.status===401||C.status===403)&&$("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),$(`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=pe(process.cwd(),d.out),S=$u(_,{event:d.event}),P=0,A=0;for(let{recordType:C,fixture:O}of S){let G=Ve(m,`${C}.json`),N=`${JSON.stringify(O,null,2)}
|
|
1767
|
+
`;d.force?(await re.mkdir(Zn(G),{recursive:!0}),await re.writeFile(G,N,{mode:420}),P+=1,x(` wrote ${d.out}/${C}.json`)):await Yn(G,N)==="wrote"?(P+=1,x(` wrote ${d.out}/${C}.json`)):(A+=1,x(` skipped ${d.out}/${C}.json (exists \u2014 use --force to overwrite)`))}x(`
|
|
1768
|
+
samples init: ${P} written, ${A} skipped.`)});let mt=e.command("guardrails").description("Control PG\u2192source write-back with DENY rules (staged write rollout)."),Zt=d=>[d.name,d.enabled?w.green("on"):w.dim("off"),d.source,d.record,d.when||w.dim("(always)"),d.note??""];mt.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 d=>{let{baseUrl:f,token:g}=await V(d.baseUrl),y=new B({baseUrl:f,token:g}),_;try{_=await y.guardrailsList()}catch(m){ce(m,"extensions:deploy","list guardrails"),$(`list guardrails failed: ${m instanceof Error?m.message:String(m)}`)}if(d.json)return x(JSON.stringify(_,null,2));if(_.length===0)return x(`no write guardrails \u2014 every record the admin entitlement allows is writable.
|
|
1769
|
+
`+w.dim("create one with `turbobase guardrails create <name> --source <s> --when '\u2026'`"));x(Xt(_.map(Zt),{head:["NAME","STATE","SOURCE","RECORD","WHEN","NOTE"]}))}),mt.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(d,f)=>{let{baseUrl:g,token:y}=await V(f.baseUrl),_=new B({baseUrl:g,token:y}),m;try{m=await _.guardrailCreate({name:d,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){ce(S,"extensions:deploy","create a guardrail"),$(`create guardrail failed: ${S instanceof Error?S.message:String(S)}`)}x(`${w.green("\u2713")} guardrail ${w.bold(m.name)} created${m.enabled?"":w.dim(" (parked \u2014 enable it to take effect)")}`),x(w.dim(` denies ${m.source}/${m.record}${m.when?` where ${m.when}`:" (always)"}`)),x(w.dim(` verify with: turbobase guardrails test --source ${m.source==="*"?"<source>":m.source} --record <record>`))}),mt.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(d,f)=>{f.when===void 0&&f.message===void 0&&f.note===void 0&&$("edit: nothing to change \u2014 pass --when, --message or --note.");let{baseUrl:g,token:y}=await V(f.baseUrl),_=new B({baseUrl:g,token:y}),m;try{m=await _.guardrailUpdate(d,{...f.when!==void 0?{when:f.when}:{},...f.message!==void 0?{message:f.message}:{},...f.note!==void 0?{note:f.note}:{}})}catch(S){ce(S,"extensions:deploy","edit a guardrail"),$(`edit guardrail failed: ${S instanceof Error?S.message:String(S)}`)}x(`${w.green("\u2713")} guardrail ${w.bold(m.name)} updated`),x(w.dim(` denies ${m.source}/${m.record}${m.when?` where ${m.when}`:" (always)"}`))});for(let[d,f,g]of[["enable",!0,"enabled"],["disable",!1,"disabled"]])mt.command(`${d} <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(y,_)=>{let{baseUrl:m,token:S}=await V(_.baseUrl),P=new B({baseUrl:m,token:S});try{await P.guardrailUpdate(y,{enabled:f})}catch(A){ce(A,"extensions:deploy",`${d} a guardrail`),$(`${d} guardrail failed: ${A instanceof Error?A.message:String(A)}`)}x(`${w.green("\u2713")} guardrail ${w.bold(y)} ${g}`),f||x(w.dim(" writes it was blocking are now permitted (subject to the other rules)."))});mt.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(d,f)=>{let{baseUrl:g,token:y}=await V(f.baseUrl),_=new B({baseUrl:g,token:y});try{await _.guardrailDelete(d)}catch(m){ce(m,"extensions:deploy","delete a guardrail"),$(`delete guardrail failed: ${m instanceof Error?m.message:String(m)}`)}x(`${w.green("\u2713")} guardrail ${w.bold(d)} deleted`)}),mt.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 d=>{let f;if(d.fields)try{f=JSON.parse(d.fields)}catch(S){$(`--fields must be valid JSON: ${S instanceof Error?S.message:String(S)}`)}let{baseUrl:g,token:y}=await V(d.baseUrl),_=new B({baseUrl:g,token:y}),m;try{m=await _.guardrailTest({source:d.source,record:d.record,...d.origin?{origin:d.origin}:{},...f?{fields:f}:{}})}catch(S){ce(S,"extensions:deploy","test guardrails"),$(`guardrails test failed: ${S instanceof Error?S.message:String(S)}`)}if(d.json)return x(JSON.stringify(m,null,2));m.allowed?x(`${w.green("\u2713")} ${d.source}/${d.record} \u2014 no guardrail blocks this write`):(x(`${w.red("\u2717")} ${d.source}/${d.record} \u2014 blocked by ${w.bold(m.blockedBy??"?")}`),m.message&&x(w.dim(` ${m.message}`))),m.undecided.length>0&&(x(w.yellow(` ${m.undecided.length} rule(s) need a row to decide: ${m.undecided.join(", ")}`)),x(w.dim(` re-run with --fields '{"\u2026":"\u2026"}' to evaluate them.`))),m.allowed||(process.exitCode=1)});let _t=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),mn=(d,f={})=>{let g=`${w.bold(d.table)} ${w.dim(d.displayName)}`;x(d.exists===!1?`${g} ${w.dim("(new)")}`:g);for(let y of d.fields){let _=[y.required?"required":null].filter(Boolean).join(", "),m=f.showClaimants&&y.claimedBy?.length?` ${w.dim(`\u2190 ${y.claimedBy.join(", ")}`)}`:"";x(` ${y.column.padEnd(28)} ${y.type}${_?` (${_})`:""}${m}`)}f.showClaimants&&d.claimants.length>1&&x(w.dim(` claimed by ${d.claimants.join(", ")}`))};function gn(d){if(d instanceof se&&d.status===409){let f=d.body;f?.error==="table_conflict"&&f.message&&(Z(f.message),process.exit(1))}$(`tables: ${d instanceof Error?d.message:String(d)}`)}let ns=async d=>{let f=Ve(pe(process.cwd(),d),"public","turbobase.json"),g=await re.readFile(f,"utf8").catch(()=>null);if(g===null)return null;let y;try{y=JSON.parse(g)}catch(m){$(`${f} is not valid JSON: ${m instanceof Error?m.message:String(m)}`)}let _=y.tables;return _===void 0?{tables:[],manifestPath:f}:(Array.isArray(_)||$(`${f}: "tables" must be an array.`),{tables:_,manifestPath:f})};_t.command("list").description("List the custom tables on your instance and who claims each one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:f,token:g}=await V(d.baseUrl),y=new B({baseUrl:f,token:g}),_;try{_=await y.tablesList()}catch(m){ce(m,"extensions:deploy","list tables"),$(`list tables failed: ${m instanceof Error?m.message:String(m)}`)}if(d.json)return x(JSON.stringify(_,null,2));if(_.length===0)return x("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");x(Xt(_.map(m=>[m.table,m.displayName,String(m.fields.length),m.status,m.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),_t.command("plan").description("Preview what this project's declared tables would do. Writes nothing; exits 1 on a conflict.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: the app slug in .turbobase, else cli).").action(async(d,f)=>{let g=await ns(d??".");if(g||$(`no public/turbobase.json under ${pe(process.cwd(),d??".")}.`),g.tables.length===0)return x(`${g.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:y,token:_}=await V(f.baseUrl),m=new B({baseUrl:y,token:_}),S;try{S=await ee("planning tables",()=>m.tablesPlan({claimedBy:f.as,tables:g.tables}))}catch(P){ce(P,"extensions:deploy","plan tables"),gn(P)}x(`claiming as ${w.bold(S.claimedBy)}`);for(let P of S.tables)mn(P,{showClaimants:!0});x(""),x(w.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),_t.command("apply").description("Apply this project's declared tables to the instance.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: cli).").action(async(d,f)=>{let g=await ns(d??".");if(g||$(`no public/turbobase.json under ${pe(process.cwd(),d??".")}.`),g.tables.length===0)return x(`${g.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:y,token:_}=await V(f.baseUrl),m=new B({baseUrl:y,token:_}),S;try{S=await ee("applying tables",()=>m.tablesApply({claimedBy:f.as,tables:g.tables}))}catch(P){ce(P,"extensions:deploy","apply tables"),gn(P)}for(let P of S.tables)mn(P,{showClaimants:!0});x(`applied ${S.tables.length} table${S.tables.length===1?"":"s"} as ${S.claimedBy}.`)}),_t.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(d,f)=>[...f??[],d],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let g=f.field.map(P=>{let[A,C,O]=P.split(":");return(!A||!C)&&$(`--field "${P}" must be name:type[:required] (e.g. title:text:required).`),O!==void 0&&O!=="required"&&$(`--field "${P}": the third part may only be "required".`),{name:A,type:C,...O==="required"?{required:!0}:{}}}),{baseUrl:y,token:_}=await V(f.baseUrl),m=new B({baseUrl:y,token:_}),S;try{S=await ee(`creating cr_${d}`,()=>m.tablesApply({tables:[{slug:d,displayName:f.name??d,fields:g,...f.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(P){ce(P,"extensions:deploy","create a table"),gn(P)}for(let P of S.tables)mn(P);x(""),x(w.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),_t.command("drop").description("Drop a table and everything in it. Irreversible.").argument("<slug>","Table slug (without the cr_ prefix).").requiredOption("--confirm <slug>","Type the EXACT slug to confirm (fail-closed).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{f.confirm!==d&&$(`drop refused: --confirm "${f.confirm}" does not match "${d}".`);let{baseUrl:g,token:y}=await V(f.baseUrl),_=new B({baseUrl:g,token:y}),m;try{m=await ee(`dropping cr_${d}`,()=>_.tablesDrop(d,f.confirm))}catch(S){ce(S,"extensions:deploy","drop a table"),$(`drop failed: ${S instanceof Error?S.message:String(S)}`)}if(!m.removed)return x(`no table named "${d}" on this instance \u2014 nothing dropped.`);x(`dropped ${m.table} and every row in it.`)});let Wo=e.command("sandbox").description("Ephemeral local authoring sandboxes.");Wo.command("create").description("Stand up a fresh local sandbox seeded with a sampled+redacted slice of an instance.").requiredOption("--from <instance>","Source instance to clone the data slice from.").option("--ttl <duration>","Time-to-live before reaping (e.g. 72h, 30m, 7d).","72h").option("--sample <pct>","Percent of each table to copy (e.g. 2%).","2%").option("--base-url <url>","Local base URL the sandbox is reachable at.").action(async d=>{process.env.TURBOBASE_SANDBOX="1";let f=Uc(),g;try{g=await yd(f,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(y){y instanceof cr&&$(y.message),$(`sandbox create failed: ${y instanceof Error?y.message:String(y)}`)}x(`sandbox ${g.name} ready.`),x(` source: ${g.fromTenant} (sampled ${Math.round(g.sampleFraction*100)}%, redacted)`),x(` url: ${g.url}`),x(` expires: ${g.expiresAt}`)}),Wo.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async d=>{let f=Uc();await Di(f).catch(()=>[]);let g;try{g=await bd(f,d)}catch(y){$(`sandbox destroy failed: ${y instanceof Error?y.message:String(y)}`)}g||$(`no sandbox named '${d}'.`),x(`destroyed sandbox ${g.name} (dropped ${g.database}).`)}),Wo.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=Uc(),f=await Di(d).catch(()=>[]),g=await Ss(),{active:y}=Ui(g);if(y.length===0)x("no active sandboxes.");else{for(let _ of y)x(` ${_.name} from=${_.fromTenant} expires=${_.expiresAt} ${_.url}`);x(`
|
|
1770
|
+
${y.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.",ks).action(async d=>{let{baseUrl:f,token:g}=await V(d.baseUrl),y=new B({baseUrl:f,token:g}),_;try{_=await ee("exporting instance config",()=>y.configExport())}catch(P){P instanceof se&&(P.status===401||P.status===403)&&$("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),$(`ext export failed: ${P instanceof Error?P.message:String(P)}`)}let m=typeof _.serialized=="string"?_.serialized:`${JSON.stringify(_.manifest??_,null,2)}
|
|
1771
|
+
`,S=pe(process.cwd(),d.out,dr);await re.mkdir(Zn(S),{recursive:!0}),await re.writeFile(S,m,"utf8"),x(`wrote ${d.out}/${dr} (${m.split(`
|
|
1772
|
+
`).length} lines).`)});let Fc=s.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),bg=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Hc=()=>process.env.TURBOBASE_HOME?.trim()||Ve(uR(),".turbobase"),wg=()=>"1.1.16",rs=async()=>Promise.all(bg.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));Fc.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await rs();for(let f of d)x(`${f.present?Ne.success("installed"):Ne.warn("missing")} ${w.bold(f.name)} \u2014 ${f.needs}`);d.some(f=>!f.present)&&x(`
|
|
1773
|
+
run \`${ir} ext extras install\` to fetch them into ${Hc()}.`)}),Fc.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await rs();if(d.every(A=>A.present)){x(Ne.success("extras already installed \u2014 nothing to do."));return}let f=Hc();await re.mkdir(f,{recursive:!0});let g=d.filter(A=>!A.present).map(A=>A.name),y=Ci(process.platform,process.arch),_=async(A,C)=>{let{code:O,stderr:G}=await ts("npm",["install","--prefix",f,"--no-audit","--no-fund",...A]);O!==0&&$(`extras install failed while installing ${C} (npm exited ${O}).
|
|
1774
|
+
${G.trim()}
|
|
1775
|
+
These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},m=g.filter(A=>A!=="isolated-vm");if(m.length>0){let A=m.map(C=>`${C}@${Ai[C]??"latest"}`);x(`installing ${A.join(", ")} \u2192 ${f}/node_modules \u2026`),await _(A,m.join(", "))}if(g.includes("isolated-vm")){let A=`isolated-vm@${Ai["isolated-vm"]}`;if(x(`installing ${A} \u2192 ${f}/node_modules \u2026`),await _(["--ignore-scripts",A],"isolated-vm"),ud.includes(y)){let O=`${Ii}@${wg()}`;x(`fetching ${O} (no upstream binary for ${y}) \u2026`);let{code:G}=await ts("npm",["install","--prefix",f,"--no-audit","--no-fund","--ignore-scripts",O]);G!==0&&x(Ne.warn(`could not fetch ${O} \u2014 falling back to a source build.`))}let C=await dd({home:f});C.length>0&&x(` ${Ne.success("prebuilt")} ${C.join(", ")} \u2192 isolated-vm/prebuilds/${y}`)}let S=await rs(),P=S.filter(A=>!A.present).map(A=>A.name);if(P.includes("isolated-vm")){x(Ne.warn(`no prebuilt isolated-vm for ${y} / Node ${process.versions.node} (${Oi()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:A}=await ts("npm",["rebuild","--prefix",f,"isolated-vm"]);A===0&&(S=await rs(),P=S.filter(C=>!C.present).map(C=>C.name))}P.length>0&&$(`npm succeeded but ${P.join(", ")} still will not load \u2014 no prebuilt binary for ${y} / Node ${process.versions.node} (${Oi()}), 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 yn=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return yn.command("deploy").description("Enqueue a server-side release deploy. UPLOADS the SDF project src/ from the checkout (the producer swap) when present; else a solution-only live-fetch deploy. An approved target requires --approved-by.").requiredOption("--target <mode>","Deploy posture: auto (apply now) | approved (needs a recorded approval).").option("--solution <id>","The solution id the release delivers (omit for an upload-only deploy).").option("--project <dir>","SDF project dir whose src/ is uploaded (default: cwd).").option("--git-repo <repo>","Git provenance LINK: source repo (default $GITHUB_REPOSITORY or `git remote get-url origin`).").option("--git-ref <ref>","Git provenance LINK: ref/branch/tag (default $GITHUB_REF).").option("--ref <committish>","Git provenance: the ref/branch/tag/sha the upload was built from; resolved to a commit sha via `git rev-parse` (default $GITHUB_SHA or HEAD).").option("--pr-url <url>","Git provenance LINK: the PR this deploy came from (default $PR_URL).").option("--approved-by <email>","Record the approval (REQUIRED for --target approved).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async d=>{let f=d.target==="approved"?"approved":d.target==="auto"?"auto":null;f||$(`--target must be 'auto' or 'approved' (got '${d.target}').`);let g=await _R(pe(process.cwd(),d.project??".")),y=Object.keys(g).length;!d.solution&&y===0&&$("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let m=(d.ref?await Dc(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await Dc(["rev-parse","HEAD"]),S=d.gitRepo??process.env.GITHUB_REPOSITORY??await Dc(["remote","get-url","origin"]),P=d.gitRef??process.env.GITHUB_REF??null,A=d.prUrl??process.env.PR_URL??null,{baseUrl:C,token:O}=await V(d.baseUrl),G=new B({baseUrl:C,token:O}),N;try{N=await G.releaseDeploy({solutionId:d.solution??null,target:f,approvedBy:d.approvedBy??null,files:y>0?g:null,gitRepo:S,gitRef:P,gitSha:m,prUrl:A})}catch(ne){ce(ne,"releases:write","release deploy"),ne instanceof se&&ne.status===404&&$("solution_not_found \u2014 no solution with that id."),$(`release deploy failed: ${ne instanceof Error?ne.message:String(ne)}`)}x(`release ${N.releaseId} enqueued \u2192 taskId=${N.taskId} (target=${f}`+(y>0?`, uploaded ${y} bundle file(s)`:", live-fetch")+")."),d.follow&&await Ei(()=>G.releaseStatus(N.releaseId),`release ${N.releaseId}`,d.intervalMs)}),yn.command("pull").argument("<id>","The release id").description("Write the SDF project a FAILED release built into <dir>: owned/ (yours, editable) and context/ (the rest of the bundle, read-only). Edit owned/, then `release push`.").requiredOption("--dir <path>","Directory to write the project into (created if absent).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:g,token:y}=await V(f.baseUrl),_=new B({baseUrl:g,token:y}),m;try{m=await _.releaseFiles(d)}catch(A){A instanceof se&&A.status===404&&$(`release ${d} not found.`),A instanceof se&&A.status===409&&$(`no built project was retained for release ${d}. Files are kept for a FAILED attempt only \u2014 a shipped bundle is recoverable from the account.`),ce(A,"releases:write","pull a release"),$(`release pull failed: ${A instanceof Error?A.message:String(A)}`)}let S=pe(process.cwd(),f.dir),P=0;for(let[A,C]of[["owned",m.owned],["context",m.context]])for(let[O,G]of Object.entries(C)){let N=Ve(S,A,O);await re.mkdir(Zn(N),{recursive:!0}),await re.writeFile(N,G,"utf8"),P++}await re.writeFile(Ve(S,".turbobase-release.json"),JSON.stringify({releaseId:m.releaseId,version:m.version,contentDigest:m.contentDigest},null,2),"utf8"),x(`pulled release ${m.releaseId} (${m.status}) \u2192 ${S}
|
|
1750
1776
|
${Object.keys(m.owned).length} owned file(s), ${Object.keys(m.context).length} context file(s), ${P} total
|
|
1751
1777
|
`+(m.logTail?`
|
|
1752
1778
|
the failure these bytes produced:
|
|
1753
1779
|
${m.logTail.trim()}
|
|
1754
1780
|
`:"")+`
|
|
1755
1781
|
edit the files under owned/, then:
|
|
1756
|
-
turbobase release push ${m.releaseId} --dir ${f.dir}`)}),
|
|
1782
|
+
turbobase release push ${m.releaseId} --dir ${f.dir}`)}),yn.command("push").argument("<id>","The release id the project was pulled from").description("Ship the edited project as a NEW release delivering the same solution. Refuses if a context/ file changed \u2014 those belong to other solutions.").requiredOption("--dir <path>","The directory `release pull` wrote.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--target <target>","'auto' (default) or 'approved'.","auto").option("--approved-by <who>","Required for an approved target (fails closed without it).").action(async(d,f)=>{let{baseUrl:g,token:y}=await V(f.baseUrl),_=new B({baseUrl:g,token:y}),m=pe(process.cwd(),f.dir),S;try{S=await _.releaseFiles(d)}catch(N){N instanceof se&&N.status===404&&$(`release ${d} not found.`),ce(N,"releases:write","push a release"),$(`release push failed: ${N instanceof Error?N.message:String(N)}`)}let P=async(N,ne)=>{try{return await re.readFile(Ve(m,N,ne),"utf8")}catch{return null}},A=[];for(let[N,ne]of Object.entries(S.context)){let W=await P("context",N);W!==null&&W!==ne&&A.push(N)}A.length>0&&$(`refusing to push \u2014 these context/ files were modified, and they belong to other solutions in the same bundle:
|
|
1757
1783
|
`+A.map(N=>` context/${N}`).join(`
|
|
1758
|
-
`)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let C={...
|
|
1784
|
+
`)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let C={...S.context},O=0;for(let[N,ne]of Object.entries(S.owned)){let W=await P("owned",N);C[N]=W??ne,W!==null&&W!==ne&&O++}O===0&&x("nothing changed under owned/ \u2014 pushing the same bytes the release already built.");let G=f.target==="approved"?"approved":"auto";try{let N=await _.releasePush(d,{files:C,target:G,...f.approvedBy?{approvedBy:f.approvedBy}:{}});x(`pushed ${Object.keys(C).length} file(s) (${O} edited) \u2192 release ${N.releaseId} (task ${N.taskId}).
|
|
1759
1785
|
follow it with:
|
|
1760
|
-
turbobase release status ${N.releaseId} --follow`)}catch(N){N instanceof
|
|
1761
|
-
${_.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
|
|
1762
|
-
`)),t&&void 0,e}function
|
|
1763
|
-
${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
|
|
1786
|
+
turbobase release status ${N.releaseId} --follow`)}catch(N){N instanceof se&&N.status===403&&$("an approved target needs --approved-by (the deploy gate fails closed)."),N instanceof se&&N.status===409&&$("that solution already has an active release \u2014 roll it back or wait for it."),ce(N,"releases:write","push a release"),$(`release push failed: ${N instanceof Error?N.message:String(N)}`)}}),yn.command("status").argument("<id>","The release id").description("Show a release deploy job's status; with --follow, poll to completion.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async(d,f)=>{let{baseUrl:g,token:y}=await V(f.baseUrl),_=new B({baseUrl:g,token:y});if(f.follow){await Ei(()=>_.releaseStatus(d),`release ${d}`,f.intervalMs);return}let m;try{m=await _.releaseStatus(d)}catch(S){ce(S,"releases:write","release status"),S instanceof se&&S.status===404&&$(`release ${d} not found.`),$(`release status failed: ${S instanceof Error?S.message:String(S)}`)}x(`release ${d}: status=${m.releaseStatus??"?"} stage=${m.stage} ${m.percent}%`+(m.runStatus?` (${m.runStatus})`:"")),m.outputTail&&x(m.outputTail.replace(/\n+$/,""))}),yn.command("rollback").argument("<id>","The release id to roll back").description("Roll back a live release (LIFO-guarded; server-side reverse deploy).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:g,token:y}=await V(f.baseUrl),_=new B({baseUrl:g,token:y}),m;try{m=await _.releaseRollback(d)}catch(S){ce(S,"releases:write","release rollback"),S instanceof se&&S.status===404&&$(`release ${d} not found.`),S instanceof se&&S.status===409&&$(`release ${d} cannot be rolled back (not live, or a newer release advanced past it).`),$(`release rollback failed: ${S instanceof Error?S.message:String(S)}`)}x(`release ${m.releaseId} rolled back \u2192 status=${m.release?.status??"rolled_back"}.`)}),yn.command("list").description("List releases, newest-first, with delivered titles + latest status.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async d=>{let{baseUrl:f,token:g}=await V(d.baseUrl),y=new B({baseUrl:f,token:g}),_;try{_=await y.releaseList()}catch(m){ce(m,"releases:write","release list"),$(`release list failed: ${m instanceof Error?m.message:String(m)}`)}if(_.length===0){x("no releases.");return}if(qe())x(Xt(_.map(m=>[m.id,Sn(m.status),m.target,m.backend,m.solutionTitles?.length?m.solutionTitles.map(S=>`"${S}"`).join(", "):w.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(`
|
|
1787
|
+
${_.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 d=>{let{runAuthoringMcpServer:f}=await Promise.resolve().then(()=>(mg(),hg));await f({baseUrl:d.baseUrl})}),e.addHelpText("after",["","Common flows:"," turbobase auth login --base-url https://acme.turbobase.app --token tb_pat_\u2026"," turbobase project init && turbobase project types"," turbobase ext new hook --record salesOrder && turbobase ext test hooks/\u2026"," turbobase ext deploy --to prod"," turbobase apps deploy my-app ./app","","Run `turbobase <group> --help` for a group (auth, project, ext, apps, kb, sandbox, mcp).","Docs: https://docs.turbobase.io/cli/overview/"].join(`
|
|
1788
|
+
`)),t&&void 0,e}function vR(t,e,n){let r=s=>{let o=new RegExp(`${s}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return o?o[2]:void 0};return{id:r("id")??`marketplace:${e}`,recordType:r("recordType")??"*",event:r("event")??"before_save",source:r("source")??"standalone",sourceCode:t,extensionKind:n||"hook"}}async function zc(){let t=pe(process.cwd(),ks,dr),e;try{e=await re.readFile(t,"utf8")}catch{$(`no bundle found at ${ks}/${dr} \u2014 run \`turbobase ext export\` first.`)}try{return Sd(e)}catch(n){$(`bundle is invalid: ${n instanceof Error?n.message:String(n)}`)}}function SR(t,e){x(`plan against ${e}:`);for(let n of t.add)x(` ${Ot.add(`${n.kind} ${n.id}`)}`);for(let n of t.change)x(` ${Ot.change(`${n.kind} ${n.id}`)}`);for(let n of t.destroy)x(` ${Ot.destroy(`${n.kind} ${n.id}`)}`);x(`
|
|
1789
|
+
${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 kR(t){try{let n=new URL(t).hostname.split(".")[0];return n&&n!=="localhost"?n:void 0}catch{return}}function ts(t,e,n){return new Promise(r=>{let s=Mc(t,e,{stdio:["ignore","inherit","pipe"],env:{...process.env,...n}}),o="";s.stderr?.on("data",i=>{let a=i.toString();o+=a,process.stderr.write(a)}),s.on("error",i=>r({code:-1,stderr:i.message})),s.on("exit",i=>r({code:i??-1,stderr:o}))})}function Uc(){let t=process.env.SANDBOX_LOCAL_DATABASE_URL??"postgres://postgres:postgres@127.0.0.1:54322/postgres",e=async(n,r)=>{let s=r?t.replace(/\/[^/]*$/,`/${r}`):t,o=await ts("psql",[s,"-v","ON_ERROR_STOP=1","-c",n]);if(o.code!==0)throw new Error(`psql failed (exit ${o.code}): ${o.stderr.trim()}`)};return{target:()=>t,createDatabase:async n=>{await e(`CREATE DATABASE ${n};`)},replayMigrations:async n=>{let r=t.replace(/\/[^/]*$/,`/${n}`),s=await ts("supabase",["migration","up","--db-url",r]);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 n=>{throw new Error("sandbox data copy is not implemented.")},copyRows:async(n,r,s)=>{let o=Object.keys(s[0]??{});if(o.length===0)return;let i=s.map(a=>`(${o.map(c=>a[c]===null||a[c]===void 0?"NULL":`'${String(a[c]).replace(/'/g,"''")}'`).join(", ")})`).join(", ");await e(`INSERT INTO turbobase.${r} (${o.join(", ")}) VALUES ${i};`,n)},dropDatabase:async n=>{await e(`DROP DATABASE IF EXISTS ${n} WITH (FORCE);`)}}}async function _R(t){let e=pe(t,"src"),n={},r=async s=>{let o;try{o=await re.readdir(s,{withFileTypes:!0})}catch{return}for(let i of o){let a=Ve(s,i.name);if(i.isDirectory())await r(a);else if(i.isFile()){let c=Go(e,a).split(qc).join("/");n[c]=await re.readFile(a,"utf8")}}};return await r(e),n}function Dc(t){return new Promise(e=>{let n=Mc("git",t,{stdio:["ignore","pipe","ignore"]}),r="";n.stdout?.on("data",s=>{r+=s.toString()}),n.on("error",()=>e(null)),n.on("exit",s=>e(s===0&&r.trim()?r.trim():null))})}var $R=!1;$R&&Bc().parseAsync(process.argv).catch(t=>$(t instanceof Error?t.message:String(t)));Bc().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
|
|
1764
1790
|
`),process.exit(1)});
|