@turbobase/cli 1.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +48 -0
- package/README.md +119 -0
- package/dist/turbobase-standalone.mjs +1635 -0
- package/dist/turbobase.js +1588 -0
- package/package.json +37 -0
|
@@ -0,0 +1,1588 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __tbCreateRequire } from 'node:module';
|
|
3
|
+
const require = __tbCreateRequire(import.meta.url);
|
|
4
|
+
var Fm=Object.create;var Ls=Object.defineProperty;var Hm=Object.getOwnPropertyDescriptor;var Km=Object.getOwnPropertyNames;var Vm=Object.getPrototypeOf,Gm=Object.prototype.hasOwnProperty;var O=(t,e)=>()=>(t&&(e=t(t=0)),e);var j=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),xl=(t,e)=>{for(var r in e)Ls(t,r,{get:e[r],enumerable:!0})},Wm=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Km(e))!Gm.call(t,o)&&o!==r&&Ls(t,o,{get:()=>e[o],enumerable:!(n=Hm(e,o))||n.enumerable});return t};var Tl=(t,e,r)=>(r=t!=null?Fm(Vm(t)):{},Wm(e||!t||!t.__esModule?Ls(r,"default",{value:t,enumerable:!0}):r,t));function Fr(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var Zn=O(()=>{});import{z as Ht}from"zod";function Yn(t){let e=Ds.safeParse(t);return e.success?(e.data.inputs??[]).filter(r=>r.type==="connection"):[]}function Ms(t,e){let r=Ds.safeParse(t);if(!r.success)throw new $t(`invalid manifest: ${r.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}`);if(El.test(e))throw new $t('a literal connection_id is baked into the bundle source \u2014 connection binding is an install-time input, not a published value. Declare an inputs[] entry { type: "connection", source_system } instead.');let n=JSON.stringify(r.data);if(El.test(n))throw new $t("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var Rl,Pl,Ds,$t,El,Al=O(()=>{Rl=Ht.object({type:Ht.literal("connection"),source_system:Ht.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:Ht.string().min(1).max(200).optional()}),Pl=Ht.discriminatedUnion("type",[Rl]),Ds=Ht.object({inputs:Ht.array(Pl).optional()}).passthrough(),$t=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};El=/\bconnection[_-]?id\b["']?\s*[:=]/i});var Qn,qs=O(()=>{Qn=["before_read","before_save","after_save","before_sync","after_sync","on_sync_failure"]});import{z as Ce}from"zod";var Us,Cl,Il=O(()=>{Zn();qs();Us=Ce.object({id:Ce.string().min(1,"hook id must be non-empty"),recordType:Ce.union([Ce.string().min(1),Ce.array(Ce.string().min(1)).min(1),Ce.literal("*")]),event:Ce.enum(Qn),source:Ce.string().min(1).optional(),when:Ce.unknown().optional(),run:Ce.unknown(),failClosed:Ce.boolean().optional(),timeoutMs:Ce.number().int().positive().optional(),description:Ce.string().optional(),systemReserved:Ce.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"})}),Cl=Fr({kind:"hook",schema:Us,factoryName:"defineHook"})});var Ol=O(()=>{Il();qs()});var Xn,Bs=O(()=>{Xn=["after_canonicalize_inbound","after_sync_success_outbound"]});import{z as _e}from"zod";var Fs,Nl,jl=O(()=>{Zn();Bs();Fs=_e.object({id:_e.string().min(1,"conduit id must be non-empty"),on:_e.enum(Xn),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 r=t.from?.when;r!==void 0&&typeof r!="function"&&e.addIssue({code:"custom",path:["from","when"],message:"from.when, when present, must be a function"});let n=t.idempotencyKey;n!==void 0&&typeof n!="function"&&e.addIssue({code:"custom",path:["idempotencyKey"],message:"idempotencyKey, when present, must be a function"});let o=t.from,s=t.to;o?.source&&s?.source&&o.source===s.source&&e.addIssue({code:"custom",path:["to","source"],message:"a conduit must bridge two DIFFERENT sources (from.source === to.source) \u2014 use a hook for an intra-source transform"})}),Nl=Fr({kind:"conduit",schema:Fs,factoryName:"defineConduit"})});var zl=O(()=>{jl();Bs()});async function Xm(t){let e;try{e=await import("openapi-typescript")}catch{throw new Error("types-gen: 'openapi-typescript' is not installed. Add it to the environment running `turbobase project types`, or pass a `transform` override to generateTypes().")}let r=await e.default(t,{defaultNonNullable:!1});return e.astToString(r)}async function eo(t,e={}){return(e.transform??Xm)(t)}var Hs=O(()=>{});function Ks(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 Ll(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Vs(t){return`${Ll(t.source)}${Ll(t.recordType)}`}function eg(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function tg(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 Gs(t){let e=Vs(t),r=[`${t.source}:${t.recordType}`+(t.table?` \u2192 turbobase.${t.table}`:" (no backing table)")+`${t.listOnly?" (list-only)":""} \u2014 origin: ${t.origin}.`];t.description&&r.push(t.description);let n=r.length===1?`/** ${r[0]} */`:`/**
|
|
5
|
+
* ${r.join(`
|
|
6
|
+
* `)}
|
|
7
|
+
*/`;if(t.columns.length===0)return`${n}
|
|
8
|
+
export interface ${e} {
|
|
9
|
+
// no columns introspected
|
|
10
|
+
[key: string]: unknown;
|
|
11
|
+
}`;let o=t.columns.map(s=>{let i=Ks(s.pgType),a=s.nullable?"?":"",l=s.nullable?" | null":"";return` /** ${tg(s)} */
|
|
12
|
+
${eg(s.name)}${a}: ${i}${l};`});return`${n}
|
|
13
|
+
export interface ${e} {
|
|
14
|
+
${o.join(`
|
|
15
|
+
`)}
|
|
16
|
+
}`}function to(t){return[...t.records].sort((n,o)=>`${n.source}:${n.recordType}`.localeCompare(`${o.source}:${o.recordType}`)).map(Gs).join(`
|
|
17
|
+
|
|
18
|
+
`)}var Ws=O(()=>{});function rg(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function Dl(t,e,r){let n=await r(t,{headers:{Accept:"application/json",Authorization:`Bearer ${e}`}});if(!n.ok)throw new Error(`types-gen: GET ${t} failed (${n.status} ${n.statusText})`);return n.json()}async function kt(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let r=rg(t.baseUrl),n=await Dl(r.records,t.token,e);if(!n||!Array.isArray(n.records))throw new Error("types-gen: /v1/catalog/records did not return a { records: [...] } envelope");let o=to(n),s=[ng,"// ----- Record shapes (from /v1/catalog/records) -----",o];if(!t.recordsOnly){let i=await Dl(r.openapi,t.token,e),a=await eo(i,t.openApi);s.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return s.join(`
|
|
19
|
+
|
|
20
|
+
`)+`
|
|
21
|
+
`}var ng,Ml=O(()=>{Hs();Ws();Ws();Hs();ng=["/**"," * GENERATED by `turbobase project types` (@turbobase/extensions). DO NOT EDIT."," *"," * Record shapes from /v1/catalog/records + PostgREST operations from"," * /v1/catalog/openapi.json, RLS-scoped to the token used to generate this."," */","","/* eslint-disable */"].join(`
|
|
22
|
+
`)});var Js=O(()=>{Zn();Al();Ol();zl();Ml()});import{homedir as og}from"node:os";import{join as ql}from"node:path";import{promises as Zs}from"node:fs";function Ve(t){return t.trim().replace(/\/+$/,"")}function Bl(){let t=process.env.TURBOBASE_HOME??ql(og(),".turbobase");return{dir:t,file:ql(t,"credentials")}}function Ul(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function Hr(){let{file:t}=Bl(),e;try{let s=await Zs.readFile(t,"utf8");e=JSON.parse(s)}catch(s){if(s.code==="ENOENT")return{tenants:{}};throw s}if(!e||typeof e!="object")return{tenants:{}};let r=e;if(r.tenants&&typeof r.tenants=="object"){let s={};for(let[a,l]of Object.entries(r.tenants))Ul(l)&&(s[a]={token:l.token,updatedAt:l.updatedAt});return{active:typeof r.active=="string"&&s[r.active]?r.active:void 0,tenants:s}}let n={};for(let[s,i]of Object.entries(r))Ul(i)&&(n[s]={token:i.token,updatedAt:i.updatedAt});return{active:sg(n),tenants:n}}function sg(t){let e,r="";for(let[n,o]of Object.entries(t))(!e||String(o.updatedAt)>r)&&(e=n,r=String(o.updatedAt));return e}async function Ys(t){let{dir:e,file:r}=Bl();await Zs.mkdir(e,{recursive:!0,mode:448}),await Zs.writeFile(r,JSON.stringify(t,null,2)+`
|
|
23
|
+
`,{mode:384})}async function Fl(t){let e=Ve(t.baseUrl),r=await Hr(),n=new Date().toISOString();return r.tenants[e]={token:t.token,updatedAt:n},r.active=e,await Ys(r),{baseUrl:e,token:t.token,updatedAt:n}}async function dt(t){let e=await Hr();if(t){let s=Ve(t),i=e.tenants[s];return i?{baseUrl:s,token:i.token,updatedAt:i.updatedAt}:null}let r=Object.keys(e.tenants),n=e.active&&e.tenants[e.active]?e.active:r.length===1?r[0]:void 0;if(!n)return null;let o=e.tenants[n];return{baseUrl:n,token:o.token,updatedAt:o.updatedAt}}async function ro(t){let e=Ve(t),r=await Hr(),n=r.tenants[e];return n?(r.active=e,await Ys(r),{baseUrl:e,token:n.token,updatedAt:n.updatedAt}):null}async function Qs(t){let e=await Hr(),r=t?Ve(t):e.active&&e.tenants[e.active]?e.active:Object.keys(e.tenants).length===1?Object.keys(e.tenants)[0]:void 0;if(!r||!e.tenants[r])return null;if(delete e.tenants[r],e.active===r){let n=Object.keys(e.tenants);e.active=n.length===1?n[0]:void 0}return await Ys(e),r}async function xt(){let t=await Hr();return Object.entries(t.tenants).map(([e,r])=>({baseUrl:e,token:r.token,updatedAt:r.updatedAt}))}var no=O(()=>{});function Hl(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 Kl(t){return t.replace(/\/+$/,"")}function Xs(t=process.env){let e=(t[dr]??"").trim(),r=(t[oo]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function ei(t){let e;try{e=new URL(t)}catch{return`${dr} 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:`${dr} must be https:// (got ${e.protocol}//${e.hostname}). The registry bearer is sent as an Authorization header and must not cross a plaintext connection.`}var ge,le,dr,oo,Kr,Vr=O(()=>{ge=class extends Error{constructor(r,n,o){super(r);this.status=n;this.body=o;this.name="ApiError"}status;body};le=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=Kl(e.baseUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("ExtensionsApi: no fetch implementation available");this.fetchImpl=r}async request(e,r,n,o){let s=await this.fetchImpl(`${this.baseUrl}${r}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/json",...n!==void 0?{"Content-Type":"application/json"}:{},...o??{}},...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await s.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!s.ok){let l=Hl(a);throw new ge(`${e} ${r} \u2192 ${s.status}${l?`: ${l}`:""}`,s.status,a)}return a}deploy(e){return this.request("POST","/v1/extensions",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli",...e.connectionId?{connectionId:e.connectionId}:{}})}async list(e){let r=e?`?kind=${encodeURIComponent(e)}`:"";return(await this.request("GET",`/v1/extensions${r}`)).extensions??[]}test(e){return this.request("POST","/v1/extensions/test",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli"})}async logs(e,r){let n=r&&r>0?`?limit=${Math.floor(r)}`:"";return(await this.request("GET",`/v1/extensions/${encodeURIComponent(e)}/logs${n}`)).logs??[]}async catalogRecords(){return(await this.request("GET","/v1/catalog/records")).records??[]}async conduitEvents(e,r={}){let n=new URLSearchParams;r.since&&n.set("since",r.since),r.limit&&r.limit>0&&n.set("limit",String(Math.floor(r.limit)));let o=n.toString()?`?${n.toString()}`:"";return(await this.request("GET",`/v1/conduits/${encodeURIComponent(e)}/events${o}`)).events??[]}async bindings(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/bindings${n}`)).bindings??[]}async appsList(){return(await this.request("GET","/v1/apps")).apps??[]}appsCreate(e){return this.request("POST","/v1/apps",{slug:e.slug,name:e.name??e.slug,description:e.description})}appsPull(e){return this.request("GET",`/v1/apps/${encodeURIComponent(e)}/pull`)}appPullContext(e){return this.request("GET",`/v1/apps/proposals/${encodeURIComponent(e)}/pull-context`)}appsPush(e,r,n={}){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/push`,{files:r,...n.note?{note:n.note}:{},...n.meta?{meta:n.meta}:{}},n.proposalId?{"x-proposal-id":n.proposalId}:void 0)}learningsPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.section&&r.set("section",e.section),e.limit!==void 0&&r.set("limit",String(e.limit));let n=r.toString();return this.request("GET",`/v1/learnings/pending${n?`?${n}`:""}`)}learningsPushKb(e,r={}){return this.request("POST","/v1/learnings/push-kb",{planToken:e,...r.app?{app:r.app}:{},...r.section?{section:r.section}:{},...r.limit!==void 0?{limit:r.limit}:{}})}retryBinding(e){return this.request("POST",`/v1/bindings/${encodeURIComponent(e)}/retry`)}configExport(){return this.request("GET","/v1/config/export")}configPlan(e){return this.request("POST","/v1/config/plan",{bundle:e})}configApply(e){return this.request("POST","/v1/config/apply",{bundle:e})}},dr="TURBOBASE_REGISTRY_URL",oo="TURBOBASE_REGISTRY_TOKEN";Kr=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=Kl(e.registryUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("RegistryApi: no fetch implementation available");this.fetchImpl=r}async request(e,r,n){let o={Authorization:`Bearer ${this.token}`,Accept:"application/json"};n!==void 0&&(o["Content-Type"]="application/json");let s=await this.fetchImpl(`${this.registryUrl}${r}`,{method:e,headers:o,...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await s.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!s.ok){let l=Hl(a);throw new ge(`${e} ${r} \u2192 ${s.status}${l?`: ${l}`:""}`,s.status,a)}return a}async list(){return(await this.request("GET","/extensions")).extensions??[]}fetchBundle(e,r){let n=r?`?version=${encodeURIComponent(r)}`:"";return this.request("GET",`/extensions/${encodeURIComponent(e)}${n}`)}publish(e){return this.request("POST","/extensions",{name:e.name,version:e.version,kind:e.kind,bundle:e.bundle,...e.manifest?{manifest:e.manifest}:{}})}}});function ag(t){if(ig.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function lg(){return{name:"extension-self-contained-fence",setup(t){t.onResolve({filter:/.*/},e=>e.kind==="entry-point"?null:ag(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:")||ug(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:cg,loader:"js"}))}}}function ug(t){let e=t.startsWith("node:")?t.slice(5):t;return dg.has(e.split("/")[0])}function Vl(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 pg(){try{return(await import("esbuild")).build}catch(t){throw Vl("esbuild",t)}}async function fg(){try{return(await import("isolated-vm")).default}catch(t){throw Vl("isolated-vm",t)}}async function so(t){let e=await pg(),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:[lg()]})}catch(n){let s=n.errors?.map(i=>i.text).filter(Boolean).join("; ");throw new ti(s||`extension bundle failed: ${String(n)}`)}return r.outputFiles?.[0]?.text??""}async function Gr(t,e,r={}){let n=r.timeoutMs??200,o=r.memoryLimitMb??16,s=r.member??"run",i={patches:[],logs:[]},a=await fg(),l=new a.Isolate({memoryLimit:o});try{let p=await l.createContext(),u=p.global,d=new a.Callback(N=>{let D=JSON.parse(String(N));i.rejection||(i.rejection=D)}),f=new a.Callback(N=>{i.patches.push(JSON.parse(String(N)))}),g=new a.Callback(N=>{let D=JSON.parse(String(N));i.logs.push(D)}),b=new a.Callback(N=>{i.result=JSON.parse(String(N))});await u.set("__tb_reject",d),await u.set("__tb_patch",f),await u.set("__tb_log",g),await u.set("__tb_result",b),await u.set("__tb_ctx_json",JSON.stringify(hg(e)));let v=mg(t,s),P=await(await l.compileScript(v)).run(p,{timeout:n,promise:!0});return s==="when"?{effects:i,whenResult:!!P}:{effects:i}}finally{l.isDisposed||l.dispose()}}function hg(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 mg(t,e){return`
|
|
24
|
+
"use strict";
|
|
25
|
+
(async () => {
|
|
26
|
+
const __tb_ctx = JSON.parse(__tb_ctx_json);
|
|
27
|
+
// Rebuild the documented HookContext. reject/patch/log marshal their
|
|
28
|
+
// argument to JSON and call the bridged host callback. No other host
|
|
29
|
+
// surface is reachable.
|
|
30
|
+
//
|
|
31
|
+
// Conduit (#572): a conduit's ctx also carries read-only \`bindings\` +
|
|
32
|
+
// \`atlas.resolve\` + \`canonicalStatus\`. These are pure over the
|
|
33
|
+
// copied-in snapshot (no live host call) \u2014 bindings + a pre-resolved
|
|
34
|
+
// atlasLinks map. A hook never reads them, so the extra fields are inert
|
|
35
|
+
// for the hook path. \`atlas.resolve\` returns null on a miss (untrusted
|
|
36
|
+
// conduits get pre-resolved atlas only \u2014 the documented v1 limit).
|
|
37
|
+
const __tb_atlasLinks = __tb_ctx.atlasLinks || {};
|
|
38
|
+
const ctx = {
|
|
39
|
+
recordType: __tb_ctx.recordType,
|
|
40
|
+
event: __tb_ctx.event,
|
|
41
|
+
direction: __tb_ctx.direction,
|
|
42
|
+
origin: __tb_ctx.origin,
|
|
43
|
+
source: __tb_ctx.source,
|
|
44
|
+
// A conduit authors against \`ctx.fromSource\`; \`ctx.source\` carries the
|
|
45
|
+
// same value, so expose both off the one serialized field.
|
|
46
|
+
fromSource: __tb_ctx.source,
|
|
47
|
+
externalId: __tb_ctx.metadata && __tb_ctx.metadata.externalId,
|
|
48
|
+
payload: __tb_ctx.payload,
|
|
49
|
+
prior: __tb_ctx.prior == null ? undefined : __tb_ctx.prior,
|
|
50
|
+
user: __tb_ctx.user == null ? undefined : __tb_ctx.user,
|
|
51
|
+
tenantConfig: __tb_ctx.tenantConfig,
|
|
52
|
+
metadata: __tb_ctx.metadata == null ? undefined : __tb_ctx.metadata,
|
|
53
|
+
lines: (__tb_ctx.metadata && __tb_ctx.metadata.lines) || [],
|
|
54
|
+
bindings: __tb_ctx.bindings || [],
|
|
55
|
+
atlas: {
|
|
56
|
+
resolve(args) {
|
|
57
|
+
const k = (args.entityType || '') + '|' + (args.targetSource || '') + '|' + (args.sourceExternalId || '');
|
|
58
|
+
return Object.prototype.hasOwnProperty.call(__tb_atlasLinks, k) ? __tb_atlasLinks[k] : null;
|
|
59
|
+
},
|
|
60
|
+
},
|
|
61
|
+
canonicalStatus(args) {
|
|
62
|
+
return String((args && args.raw) || '').trim().toLowerCase();
|
|
63
|
+
},
|
|
64
|
+
reject(envelope) { __tb_reject(JSON.stringify(envelope)); },
|
|
65
|
+
patch(updates) { __tb_patch(JSON.stringify(updates)); },
|
|
66
|
+
log(level, message, meta) {
|
|
67
|
+
__tb_log(JSON.stringify({ level, message, meta }));
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
// ---- bundled extension module (IIFE assigns __tb_extension_module) ----
|
|
72
|
+
${t}
|
|
73
|
+
|
|
74
|
+
const def = (typeof __tb_extension_module !== 'undefined' && __tb_extension_module)
|
|
75
|
+
? __tb_extension_module.default
|
|
76
|
+
: undefined;
|
|
77
|
+
if (!def || typeof def !== 'object') {
|
|
78
|
+
throw new Error('extension bundle has no default export (use export default defineHook({...}))');
|
|
79
|
+
}
|
|
80
|
+
// 'when' resolves the kind's gate: a hook's is top-level \`def.when\`; a
|
|
81
|
+
// conduit's is the nested \`def.from.when\` (#572). A conduit has no
|
|
82
|
+
// top-level \`when\` (and a hook has no \`from\`), so the \`??\` picks the
|
|
83
|
+
// right one without a kind discriminator. 'run'/'transform' are the body.
|
|
84
|
+
const fn = ${e==="when"?"(def.when || (def.from && def.from.when))":`def[${JSON.stringify(e)}]`};
|
|
85
|
+
if (typeof fn !== 'function') {
|
|
86
|
+
${e==="when"?"return true;":e==="transform"?"throw new Error('conduit default export has no transform() function');":"throw new Error('extension default export has no run() function');"}
|
|
87
|
+
}
|
|
88
|
+
const out = await fn(ctx);
|
|
89
|
+
${e==="transform"?"__tb_result(JSON.stringify(out == null ? null : out));":""}
|
|
90
|
+
return ${e==="when"?"out":"undefined"};
|
|
91
|
+
})()
|
|
92
|
+
`}var ig,cg,ti,dg,ri=O(()=>{ig=new Set(["@/sync/hooks","@/sync/hooks/index.js","@/sync/conduits","@/sync/conduits/index.js","@turbobase/extensions","@turbobase/extensions/hook","@turbobase/extensions/conduit"]);cg=`
|
|
93
|
+
export const defineHook = (def) => def;
|
|
94
|
+
export const defineConduit = (def) => def;
|
|
95
|
+
export default defineHook;
|
|
96
|
+
`,ti=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};dg=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 ni}from"node:fs";import{join as gg}from"node:path";function yg(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 bg(t,e,r){let n=e.name??r,o=e.expect??"pass";try{let{effects:s}=await Gr(t,yg(e.context)),i=s.rejection?"reject":"pass";return{name:n,expected:o,observed:i,pass:i===o,rejection:s.rejection,patchCount:s.patches.length}}catch(s){return{name:n,expected:o,observed:"pass",pass:!1,patchCount:0,error:s instanceof Error?s.message:String(s)}}}async function io(t,e){let r=await so(t),n=[];for(let o=0;o<e.length;o+=1)n.push(await bg(r,e[o],`sample[${o}]`));return n}async function Wr(t){let e;try{e=await ni.readdir(t)}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of e.sort()){if(!n.endsWith(".json"))continue;let o=await ni.readFile(gg(t,n),"utf8"),s=JSON.parse(o),i=Array.isArray(s)?s:[s];for(let a=0;a<i.length;a+=1){let l=i[a];r.push({file:n,fixture:{...l,name:l.name??`${n}${i.length>1?`#${a}`:""}`}})}}return r}function Jr(t){return ni.readFile(t,"utf8")}var oi=O(()=>{ri()});function Rt(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function Jg(t){let e=t.recordType;if(!e)throw new Je("record type is required (e.g. --record=salesOrder)");let r=t.event??"before_save",n=t.template??"require-field",o=t.source,s=o?`
|
|
97
|
+
source: ${JSON.stringify(o)},`:"",i,a;if(n==="blank")i=`
|
|
98
|
+
run: (ctx) => {
|
|
99
|
+
// Validate or mutate ctx.payload here. Reject with ctx.reject({...}); mutate
|
|
100
|
+
// with ctx.patch({...}); observe with ctx.log('info', '...').
|
|
101
|
+
},`,a="custom";else if(n==="require-field"){let f=t.field;if(!f)throw new Je("require-field template needs --field=<name>");i=`
|
|
102
|
+
run: (ctx) => {
|
|
103
|
+
const v = ctx.payload[${JSON.stringify(f)}];
|
|
104
|
+
if (v === undefined || v === null || v === '') {
|
|
105
|
+
ctx.reject({
|
|
106
|
+
code: 'MANDATORY_FIELD_MISSING',
|
|
107
|
+
field: ${JSON.stringify(f)},
|
|
108
|
+
message: ${JSON.stringify(`${f} is required`)},
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
},`,a=`require-field-${f}`}else if(n==="enforce-format"){let f=t.field;if(!f)throw new Je("enforce-format template needs --field=<name>");if(!t.regex)throw new Je("enforce-format template needs --regex=<pattern>");i=`
|
|
112
|
+
run: (ctx) => {
|
|
113
|
+
const v = ctx.payload[${JSON.stringify(f)}];
|
|
114
|
+
if (typeof v === 'string' && v && !/${t.regex}/.test(v)) {
|
|
115
|
+
ctx.reject({
|
|
116
|
+
code: 'INVALID_FORMAT',
|
|
117
|
+
field: ${JSON.stringify(f)},
|
|
118
|
+
message: ${JSON.stringify(`${f} does not match expected format`)},
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
},`,a=`enforce-format-${f}`}else throw new Je(`unsupported template: ${n}. Supported: require-field | enforce-format | blank.`);let l=t.id??`custom:${e}:${a}${t.regex?`-${Rt(t.regex).slice(0,24)}`:""}`,u=`/**
|
|
122
|
+
* ${t.description??`${a} on ${e}.${r}`}
|
|
123
|
+
*
|
|
124
|
+
* Scaffolded by \`turbobase ext new hook\`. Edit freely, then \`turbobase ext test\` and
|
|
125
|
+
* \`turbobase ext deploy\`.
|
|
126
|
+
*/
|
|
127
|
+
import { defineHook } from '@turbobase/extensions';
|
|
128
|
+
|
|
129
|
+
export default defineHook<Record<string, unknown>>({
|
|
130
|
+
id: ${JSON.stringify(l)},
|
|
131
|
+
recordType: ${JSON.stringify(e)},
|
|
132
|
+
event: ${JSON.stringify(r)},${s}${i}
|
|
133
|
+
});
|
|
134
|
+
`;return{relativePath:`hooks/${e}/${r}.${a}.ts`,content:u}}function Zg(t){let e=t.recordType;if(!e)throw new Je("record type is required (e.g. --record=order)");let r=t.source;if(!r)throw new Je("--source is required (the origin source, e.g. --source=shopify)");let n=t.to;if(!n)throw new Je("--to is required (the target source, e.g. --to=netsuite)");if(r===n)throw new Je(`a conduit must bridge two DIFFERENT sources (got --source=${r} --to=${n}); use \`turbobase ext new hook\` for an intra-source transform`);let o=t.toRecordType??e,s=t.event??"after_canonicalize_inbound",i=t.id??`${Rt(r)}2${Rt(n)}:${Rt(e)}`,l=`/**
|
|
135
|
+
* ${t.description??`Bridge ${r} ${e} \u2192 ${n} ${o} (${s}).`}
|
|
136
|
+
*
|
|
137
|
+
* Scaffolded by \`turbobase ext new conduit\`. A conduit is a PURE canonical\u2192canonical
|
|
138
|
+
* transform: read ctx, RETURN a { patch, createdFrom } \u2014 never call a source API
|
|
139
|
+
* and never hold credentials. The engine writes the canonical master row and the
|
|
140
|
+
* writeback worker fans it out to the target. Keep this file self-contained:
|
|
141
|
+
* inline any shared mapping logic; the ONLY allowed import is the SDK factory.
|
|
142
|
+
*
|
|
143
|
+
* Edit freely, then \`turbobase ext test\` and \`turbobase ext deploy\`.
|
|
144
|
+
*/
|
|
145
|
+
import { defineConduit } from '@turbobase/extensions';
|
|
146
|
+
|
|
147
|
+
export default defineConduit<Record<string, unknown>>({
|
|
148
|
+
id: ${JSON.stringify(i)},
|
|
149
|
+
on: ${JSON.stringify(s)},
|
|
150
|
+
from: {
|
|
151
|
+
source: ${JSON.stringify(r)},
|
|
152
|
+
recordType: ${JSON.stringify(e)},
|
|
153
|
+
// when: (ctx) => true, // optional gate on the inbound payload
|
|
154
|
+
},
|
|
155
|
+
to: {
|
|
156
|
+
source: ${JSON.stringify(n)},
|
|
157
|
+
recordType: ${JSON.stringify(o)},
|
|
158
|
+
},
|
|
159
|
+
mode: 'dual-bind',
|
|
160
|
+
conflictStrategy: 'merge',
|
|
161
|
+
cycleBudget: 4,
|
|
162
|
+
transform: async (ctx) => {
|
|
163
|
+
// Map ctx.payload / ctx.lines into the target's canonical shape here.
|
|
164
|
+
return {
|
|
165
|
+
patch: {
|
|
166
|
+
// ...mapped canonical fields...
|
|
167
|
+
},
|
|
168
|
+
createdFrom: {
|
|
169
|
+
source: ${JSON.stringify(r)},
|
|
170
|
+
recordType: ${JSON.stringify(e)},
|
|
171
|
+
externalId: ctx.externalId,
|
|
172
|
+
},
|
|
173
|
+
};
|
|
174
|
+
},
|
|
175
|
+
idempotencyKey: (ctx) => ${JSON.stringify(`${i}:`)} + ctx.externalId,
|
|
176
|
+
});
|
|
177
|
+
`;return{relativePath:`conduits/${Rt(r)}-${Rt(e)}-to-${Rt(n)}-${Rt(o)}.ts`,content:l}}function pr(t,e){let r=Yg[t];if(!r)throw new Je(`unknown extension kind '${t}'. Scaffoldable kinds: ${gd.join(", ")}.`);return r(e)}var gd,Je,Yg,ui=O(()=>{gd=["hook","conduit"];Je=class extends Error{};Yg={hook:Jg,conduit:Zg}});function lb(t){let e=2166136261;for(let r=0;r<t.length;r+=1)e^=t.charCodeAt(r),e=Math.imul(e,16777619)>>>0;return e>>>0}function db(t){return Kd[lb(t)%Kd.length]}function ub(t){let e=t.trim().split(/[\s\-_.]+/).filter(r=>/[a-z0-9]/i.test(r));return e.length===0?t.trim().slice(0,1).toUpperCase()||"\u2022":e.length===1?e[0].slice(0,2).toUpperCase():(e[0][0]+e[1][0]).toUpperCase()}function Vd(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Gd(t,e){let[r,n]=db(t),o=Vd(ub(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${Vd(e)}">
|
|
178
|
+
<defs>
|
|
179
|
+
<linearGradient id="tile" x1="0" y1="0" x2="1" y2="1">
|
|
180
|
+
<stop offset="0" stop-color="${r}"/>
|
|
181
|
+
<stop offset="1" stop-color="${n}"/>
|
|
182
|
+
</linearGradient>
|
|
183
|
+
</defs>
|
|
184
|
+
<rect width="64" height="64" rx="14" fill="url(#tile)"/>
|
|
185
|
+
<text x="32" y="34" text-anchor="middle" dominant-baseline="central" font-family="system-ui, -apple-system, Segoe UI, sans-serif" font-size="26" font-weight="600" fill="#ffffff">${o}</text>
|
|
186
|
+
</svg>
|
|
187
|
+
`}var Kd,Wd=O(()=>{Kd=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var Jd,Zd=O(()=>{Jd=Object.freeze({instance:!0,platform:!0,share:"inherit"})});var ou={};xl(ou,{MAIN_TSX:()=>ru,STYLES_CSS:()=>nu,TSCONFIG:()=>eu,TURBOBASE_CLIENT:()=>Yd,indexHtml:()=>tu,instanceOriginFromEnv:()=>yb,packageJson:()=>Qd,scaffoldAppFiles:()=>wb,starterApp:()=>vb,viteConfig:()=>Xd});function fb(t){let e={name:t.title},r=(t.description??"").trim().slice(0,pb);return r&&(e.description=r),e.icon="favicon.svg",e.learnings={...Jd},JSON.stringify(e,null,2)+`
|
|
188
|
+
`}function Qd(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview"},dependencies:{react:"^18.3.1","react-dom":"^18.3.1"},devDependencies:{"@types/react":"^18.3.3","@types/react-dom":"^18.3.0","@vitejs/plugin-react":"^4.3.1",typescript:"^5.5.3",vite:"^5.4.0"}},null,2)}
|
|
189
|
+
`}function gb(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 yb(t=process.env){let e=(t.TENANT_SLUG??"").trim(),r=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!r))return`https://${e}.${r}`}function Xd(t,e={}){let r=gb(e.instanceOrigin);return`import { defineConfig } from 'vite';
|
|
190
|
+
import react from '@vitejs/plugin-react';
|
|
191
|
+
|
|
192
|
+
// A same-origin static SPA served at /a/${t}. \`base\` MUST match that mount
|
|
193
|
+
// path \u2014 assets are requested absolutely, so a wrong base 404s every chunk and
|
|
194
|
+
// renders a blank page.
|
|
195
|
+
//
|
|
196
|
+
// DEV ONLY, below: the dev server is its own origin, so the instance's session
|
|
197
|
+
// cookie is not same-origin with it. Proxying every instance path the client
|
|
198
|
+
// touches makes http://localhost:3000 behave exactly like /a/${t} does in
|
|
199
|
+
// production \u2014 an unauthenticated load is forwarded to the instance's /login,
|
|
200
|
+
// you sign in, and the cookies land on localhost:3000. Override the targets
|
|
201
|
+
// with SUPABASE_URL / TURBOBASE_API_URL without editing this file (Vite reads
|
|
202
|
+
// them at boot; restart the dev server after changing one).
|
|
203
|
+
const TENANT = process.env.SUPABASE_URL || '${r??hb}'; // /rest + the Realtime WS
|
|
204
|
+
const API = process.env.TURBOBASE_API_URL || '${r??mb}'; // /v1, /auth, /login, /_app
|
|
205
|
+
|
|
206
|
+
// Where this bundle's assets are requested from. \`turbobase apps deploy\` sets
|
|
207
|
+
// this to /_tb/app-assets/<build-id>/ so the asset URLs name the BUILD, not the
|
|
208
|
+
// page URL \u2014 that is what lets the same bytes serve at /a/${t}/ and at a
|
|
209
|
+
// preview URL, and be promoted from one to the other without a rebuild.
|
|
210
|
+
// Unset (a hand-run \`npm run build\`) falls back to the production mount path.
|
|
211
|
+
const ASSET_BASE = process.env.TURBOBASE_ASSET_BASE || '/a/${t}/';
|
|
212
|
+
|
|
213
|
+
export default defineConfig({
|
|
214
|
+
base: ASSET_BASE,
|
|
215
|
+
plugins: [react()],
|
|
216
|
+
server: {
|
|
217
|
+
port: 3000,
|
|
218
|
+
proxy: {
|
|
219
|
+
'/rest': { target: TENANT, changeOrigin: true },
|
|
220
|
+
'/realtime': { target: TENANT, changeOrigin: true, ws: true },
|
|
221
|
+
'/v1': { target: API, changeOrigin: true },
|
|
222
|
+
'/auth': { target: API, changeOrigin: true },
|
|
223
|
+
'/login': { target: API, changeOrigin: true },
|
|
224
|
+
// The sign-in page is the instance's own SvelteKit app, and it loads its
|
|
225
|
+
// JS + CSS from /_app/immutable/*. Without this entry those 404 through
|
|
226
|
+
// the proxy: the login HTML arrives, never hydrates, and the form is
|
|
227
|
+
// inert with NOTHING in the console. The app then loads unauthenticated
|
|
228
|
+
// and PostgREST answers as the anonymous role \u2014 which surfaces as
|
|
229
|
+
// "permission denied for table <x>" and reads like an RLS problem rather
|
|
230
|
+
// than "you were never signed in". Do not remove this line.
|
|
231
|
+
'/_app': { target: API, changeOrigin: true },
|
|
232
|
+
},
|
|
233
|
+
},
|
|
234
|
+
build: { outDir: 'dist' },
|
|
235
|
+
});
|
|
236
|
+
`}function tu(t){return`<!doctype html>
|
|
237
|
+
<html lang="en">
|
|
238
|
+
<head>
|
|
239
|
+
<meta charset="UTF-8" />
|
|
240
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
241
|
+
<link rel="icon" type="image/svg+xml" href="favicon.svg" />
|
|
242
|
+
<title>${t}</title>
|
|
243
|
+
</head>
|
|
244
|
+
<body>
|
|
245
|
+
<div id="root"></div>
|
|
246
|
+
<script type="module" src="/src/main.tsx"></script>
|
|
247
|
+
</body>
|
|
248
|
+
</html>
|
|
249
|
+
`}function wb(t){return{"package.json":Qd(t.slug),"vite.config.ts":Xd(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":bb,"tsconfig.json":eu,"index.html":tu(t.title),"public/turbobase.json":fb(t),"public/favicon.svg":Gd(t.slug,t.title),"src/main.tsx":ru,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":Yd,"src/styles.css":nu,"README.md":`# ${t.title}
|
|
250
|
+
|
|
251
|
+
\`\`\`sh
|
|
252
|
+
npm install
|
|
253
|
+
npm run dev # http://localhost:3000/a/${t.slug}/ (NOT /, Vite serves under \`base\`)
|
|
254
|
+
|
|
255
|
+
turbobase apps push ${t.slug} . # store the source on your instance
|
|
256
|
+
turbobase apps deploy ${t.slug} # build + go live at /a/${t.slug}
|
|
257
|
+
\`\`\`
|
|
258
|
+
|
|
259
|
+
The dev server proxies \`/rest\`, \`/realtime\`, \`/v1\`, \`/auth\`, \`/login\` and \`/_app\`
|
|
260
|
+
to your instance so localhost behaves same-origin \u2014 sign in on first load and the
|
|
261
|
+
session cookie applies exactly as it will in production. Point it elsewhere with
|
|
262
|
+
\`SUPABASE_URL\` / \`TURBOBASE_API_URL\` (Vite reads them at boot; restart after).
|
|
263
|
+
|
|
264
|
+
\`/_app\` is not optional: the sign-in page loads its JS/CSS from there, and
|
|
265
|
+
without it the login form renders but never hydrates \u2014 you stay signed out and
|
|
266
|
+
every read comes back "permission denied", which looks like an RLS problem.
|
|
267
|
+
|
|
268
|
+
\`CLAUDE.md\` + \`.mcp.json\` wire Claude Code to this instance. \`.mcp.json\` holds a
|
|
269
|
+
live access token and is gitignored \u2014 keep it that way.
|
|
270
|
+
`}}function vb(t){return`import React from 'react';
|
|
271
|
+
import { select } from './lib/turbobase';
|
|
272
|
+
|
|
273
|
+
/** Swap for any record type \u2014 GET /v1/catalog/records lists what this instance has. */
|
|
274
|
+
const RECORD_TYPE = 'customer';
|
|
275
|
+
|
|
276
|
+
export default function App() {
|
|
277
|
+
const [rows, setRows] = React.useState<Record<string, unknown>[]>([]);
|
|
278
|
+
const [error, setError] = React.useState<string | null>(null);
|
|
279
|
+
|
|
280
|
+
React.useEffect(() => {
|
|
281
|
+
// Reads are RLS-scoped to the signed-in user \u2014 no key, no token handling.
|
|
282
|
+
select<Record<string, unknown>>(\`\${RECORD_TYPE}?select=*&limit=25\`)
|
|
283
|
+
.then(setRows)
|
|
284
|
+
.catch((e: unknown) => setError(e instanceof Error ? e.message : String(e)));
|
|
285
|
+
}, []);
|
|
286
|
+
|
|
287
|
+
return (
|
|
288
|
+
<main style={{ padding: 24 }}>
|
|
289
|
+
<h1>${t}</h1>
|
|
290
|
+
{error && <p style={{ color: 'crimson' }}>{error}</p>}
|
|
291
|
+
<p>{rows.length} {RECORD_TYPE} row(s), scoped to you.</p>
|
|
292
|
+
<pre>{JSON.stringify(rows.slice(0, 3), null, 2)}</pre>
|
|
293
|
+
</main>
|
|
294
|
+
);
|
|
295
|
+
}
|
|
296
|
+
`}var pb,Yd,hb,mb,bb,eu,ru,nu,su=O(()=>{Wd();Zd();pb=200;Yd=`// Same-origin TurboBase client \u2014 the one file you copy (build-apps/auth).
|
|
297
|
+
// Reads go through PostgREST (RLS-scoped); writes go through POST /v1/data/<recordType>.
|
|
298
|
+
// A cold first paint that fans out many reads should use batch() \u2014 ONE request
|
|
299
|
+
// that multiplexes them, sidestepping the per-request rate limiter.
|
|
300
|
+
// The signed-in session cookie is the only credential \u2014 no app-owned keys.
|
|
301
|
+
|
|
302
|
+
const jwt = (): string =>
|
|
303
|
+
document.cookie.split('; ').find((c) => c.startsWith('tb_jwt='))?.slice('tb_jwt='.length) ?? '';
|
|
304
|
+
|
|
305
|
+
async function req(path: string, init: RequestInit = {}): Promise<Response> {
|
|
306
|
+
const headers = new Headers(init.headers);
|
|
307
|
+
const token = jwt();
|
|
308
|
+
// supabase-js convention: the JWT rides in the apikey position for PostgREST.
|
|
309
|
+
if (token) {
|
|
310
|
+
headers.set('apikey', token);
|
|
311
|
+
headers.set('Authorization', \`Bearer \${token}\`);
|
|
312
|
+
}
|
|
313
|
+
return fetch(path, { ...init, headers, credentials: 'same-origin' });
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** PostgREST's server-side row cap (supabase config \`max_rows\`). A read with no
|
|
317
|
+
* explicit \`limit\` is silently truncated at this many rows \u2014 see select(). */
|
|
318
|
+
const SERVER_MAX_ROWS = 1000;
|
|
319
|
+
/** selectPage() defaults: page 100 rows at a time, never probe for more than the
|
|
320
|
+
* server would return in one shot anyway. */
|
|
321
|
+
const DEFAULT_PAGE_SIZE = 100;
|
|
322
|
+
const MAX_PAGE_SIZE = 1000;
|
|
323
|
+
|
|
324
|
+
/** Thrown (by name) when a read is silently capped by the server row limit \u2014 or,
|
|
325
|
+
* when \`embedAlias\` is given, when an EMBEDDED result came back short. select()
|
|
326
|
+
* WARNS with this message by default so existing callers keep working; throw it
|
|
327
|
+
* yourself if you'd rather fail hard than page. */
|
|
328
|
+
export class TurbobaseTruncationError extends Error {
|
|
329
|
+
constructor(
|
|
330
|
+
readonly pathAndQuery: string,
|
|
331
|
+
readonly cap: number,
|
|
332
|
+
readonly embedAlias?: string,
|
|
333
|
+
) {
|
|
334
|
+
super(
|
|
335
|
+
embedAlias
|
|
336
|
+
? \`select("\${pathAndQuery}") embedded "\${embedAlias}" hit a server-side bound \u2014 \` +
|
|
337
|
+
\`some related rows were dropped. Narrow the parent page (selectPage with a \` +
|
|
338
|
+
\`smaller pageSize) or filter the parent so fewer related rows are pulled.\`
|
|
339
|
+
: \`select("\${pathAndQuery}") returned exactly \${cap} rows \u2014 the PostgREST row cap. \` +
|
|
340
|
+
\`Rows beyond the first \${cap} were dropped. Page the full result set with \` +
|
|
341
|
+
\`selectPage("\${pathAndQuery}", { pageSize }) instead.\`,
|
|
342
|
+
);
|
|
343
|
+
this.name = 'TurbobaseTruncationError';
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** Thrown when a keyset cursor is malformed, or is replayed against a different
|
|
348
|
+
* table / query than the one that minted it. */
|
|
349
|
+
export class TurbobaseCursorError extends Error {
|
|
350
|
+
constructor(message: string) {
|
|
351
|
+
super(message);
|
|
352
|
+
this.name = 'TurbobaseCursorError';
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** Does this path already carry an explicit \`limit=\`? Such a caller opted into a
|
|
357
|
+
* bounded read, so the truncation warning below stays quiet for it. */
|
|
358
|
+
function hasExplicitLimit(pathAndQuery: string): boolean {
|
|
359
|
+
const q = pathAndQuery.indexOf('?');
|
|
360
|
+
if (q === -1) return false;
|
|
361
|
+
return new URLSearchParams(pathAndQuery.slice(q + 1)).has('limit');
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// ---------------------------------------------------------------------------
|
|
365
|
+
// Embeds \u2014 write ONE thing, get the right path automatically.
|
|
366
|
+
//
|
|
367
|
+
// A relationship declared in your app's public/turbobase.json:
|
|
368
|
+
//
|
|
369
|
+
// { "relationships": [
|
|
370
|
+
// { "name": "inbound_shipment", "sourceTable": "item_receipt",
|
|
371
|
+
// "sourceJsonbKey": "custbody_inbound_shipment",
|
|
372
|
+
// "targetTable": "cr_inbound_shipment" } ] }
|
|
373
|
+
//
|
|
374
|
+
// is read as \`select('item_receipt?select=*,inbound_shipment(*)')\` \u2014 the same
|
|
375
|
+
// call whether or not the instance has finished creating the SQL resolver for it.
|
|
376
|
+
// Once the relationship is ARMED, PostgREST does the embedding in one request
|
|
377
|
+
// (the fast path, straight to /rest/v1). Until then the instance resolves it
|
|
378
|
+
// server-side through POST /v1/batch \u2014 a parent read plus one keyed read of the
|
|
379
|
+
// target, joined for you, RLS-scoped exactly the same way. Same call, same rows.
|
|
380
|
+
//
|
|
381
|
+
// The client discovers which path applies the only way a browser can: it tries
|
|
382
|
+
// the native embed first and, if PostgREST answers "no such relationship",
|
|
383
|
+
// remembers that alias for the rest of the session and goes through /v1/batch.
|
|
384
|
+
// One cheap 400 per alias per page-load, then never again.
|
|
385
|
+
// ---------------------------------------------------------------------------
|
|
386
|
+
|
|
387
|
+
/** Split on top-level commas only \u2014 commas inside \`rel(a,b)\` belong to the embed. */
|
|
388
|
+
function splitTopLevel(s: string): string[] {
|
|
389
|
+
const out: string[] = [];
|
|
390
|
+
let depth = 0;
|
|
391
|
+
let start = 0;
|
|
392
|
+
for (let i = 0; i < s.length; i++) {
|
|
393
|
+
const c = s[i];
|
|
394
|
+
if (c === '(') depth++;
|
|
395
|
+
else if (c === ')') depth = Math.max(0, depth - 1);
|
|
396
|
+
else if (c === ',' && depth === 0) {
|
|
397
|
+
out.push(s.slice(start, i));
|
|
398
|
+
start = i + 1;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
out.push(s.slice(start));
|
|
402
|
+
return out.map((p) => p.trim()).filter((p) => p.length > 0);
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/** The embed aliases a query asks for (\`[]\` when it asks for none). */
|
|
406
|
+
function embedAliases(pathAndQuery: string): string[] {
|
|
407
|
+
const q = pathAndQuery.indexOf('?');
|
|
408
|
+
if (q === -1) return [];
|
|
409
|
+
const select = new URLSearchParams(pathAndQuery.slice(q + 1)).get('select');
|
|
410
|
+
if (!select || !select.includes('(')) return [];
|
|
411
|
+
return splitTopLevel(select)
|
|
412
|
+
.filter((t) => t.includes('('))
|
|
413
|
+
.map((t) => {
|
|
414
|
+
const head = t.slice(0, t.indexOf('('));
|
|
415
|
+
const colon = head.indexOf(':');
|
|
416
|
+
return (colon === -1 ? head : head.slice(colon + 1)).replace(/!.*$/, '').trim();
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** Aliases whose native embed PostgREST could not resolve \u2014 read through the
|
|
421
|
+
* instance for the rest of this session instead of re-failing every time. */
|
|
422
|
+
const stitchedAliases = new Set<string>();
|
|
423
|
+
|
|
424
|
+
/** PostgREST's code for "could not find a relationship \u2026 in the schema cache" \u2014
|
|
425
|
+
* i.e. this embed has no resolver yet, which is the whole reason /v1/batch has
|
|
426
|
+
* a fallback. Anything else (permission, syntax, a real 500) is a genuine error
|
|
427
|
+
* and is thrown, never retried. */
|
|
428
|
+
function isMissingRelationship(status: number, body: string): boolean {
|
|
429
|
+
return status === 400 && (body.includes('PGRST200') || /find a relationship/i.test(body));
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** What one read produced: the rows, plus whatever the instance reported about
|
|
433
|
+
* resolving embeds server-side. */
|
|
434
|
+
interface ReadResult<T> {
|
|
435
|
+
rows: T[];
|
|
436
|
+
/** Present only when the instance stitched one or more embeds for this read. */
|
|
437
|
+
stitched?: { aliases: string[]; truncated: string[] };
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/** Read one path+query through POST /v1/batch (the server-resolved embed path). */
|
|
441
|
+
async function readThroughInstance<T>(pathAndQuery: string): Promise<ReadResult<T>> {
|
|
442
|
+
const res = await req('/v1/batch', {
|
|
443
|
+
method: 'POST',
|
|
444
|
+
headers: { 'content-type': 'application/json', Accept: 'application/json' },
|
|
445
|
+
body: JSON.stringify({ queries: [pathAndQuery] }),
|
|
446
|
+
});
|
|
447
|
+
if (!res.ok) throw new Error(await readError(res));
|
|
448
|
+
const json = (await res.json()) as {
|
|
449
|
+
results: {
|
|
450
|
+
ok: boolean;
|
|
451
|
+
status: number;
|
|
452
|
+
body: unknown;
|
|
453
|
+
stitched?: { aliases: string[]; truncated: string[] };
|
|
454
|
+
}[];
|
|
455
|
+
};
|
|
456
|
+
const r = json.results[0];
|
|
457
|
+
if (!r) throw new Error('read failed: the instance returned no result for this query');
|
|
458
|
+
if (!r.ok) {
|
|
459
|
+
throw new Error(
|
|
460
|
+
\`read failed (\${r.status}): \${typeof r.body === 'string' ? r.body : JSON.stringify(r.body)}\`,
|
|
461
|
+
);
|
|
462
|
+
}
|
|
463
|
+
return { rows: (r.body ?? []) as T[], stitched: r.stitched };
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* The one read primitive. Embed-free queries go straight to PostgREST, exactly as
|
|
468
|
+
* before. An embed-bearing query takes the native path unless this session has
|
|
469
|
+
* already learned the relationship has no resolver yet, in which case it goes
|
|
470
|
+
* through the instance.
|
|
471
|
+
*/
|
|
472
|
+
async function readRows<T>(pathAndQuery: string): Promise<ReadResult<T>> {
|
|
473
|
+
const aliases = embedAliases(pathAndQuery);
|
|
474
|
+
const table = pathAndQuery.split('?')[0]!;
|
|
475
|
+
const known = aliases.map((a) => \`\${table}.\${a}\`);
|
|
476
|
+
const mustStitch = known.some((k) => stitchedAliases.has(k));
|
|
477
|
+
|
|
478
|
+
if (!mustStitch) {
|
|
479
|
+
const res = await req(\`/rest/v1/\${pathAndQuery}\`, { headers: { Accept: 'application/json' } });
|
|
480
|
+
if (res.ok) return { rows: (await res.json()) as T[] };
|
|
481
|
+
const body = await res.text();
|
|
482
|
+
if (aliases.length === 0 || !isMissingRelationship(res.status, body)) {
|
|
483
|
+
throw new Error(await readErrorFromBody(res.status, body));
|
|
484
|
+
}
|
|
485
|
+
// Declared but not armed yet \u2014 remember, and fall through to the instance.
|
|
486
|
+
for (const k of known) stitchedAliases.add(k);
|
|
487
|
+
}
|
|
488
|
+
return readThroughInstance<T>(pathAndQuery);
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/** Warn (loudly, by name) about anything the server silently shortened. */
|
|
492
|
+
function warnTruncation(pathAndQuery: string, result: ReadResult<unknown>): void {
|
|
493
|
+
if (
|
|
494
|
+
Array.isArray(result.rows) &&
|
|
495
|
+
result.rows.length === SERVER_MAX_ROWS &&
|
|
496
|
+
!hasExplicitLimit(pathAndQuery)
|
|
497
|
+
) {
|
|
498
|
+
console.warn(new TurbobaseTruncationError(pathAndQuery, SERVER_MAX_ROWS).message);
|
|
499
|
+
}
|
|
500
|
+
for (const alias of result.stitched?.truncated ?? []) {
|
|
501
|
+
console.warn(new TurbobaseTruncationError(pathAndQuery, SERVER_MAX_ROWS, alias).message);
|
|
502
|
+
}
|
|
503
|
+
// Native path: an embedded array at the server row cap was cut short the same
|
|
504
|
+
// way a top-level read is, and is just as invisible without this.
|
|
505
|
+
const first = result.rows?.[0] as Record<string, unknown> | undefined;
|
|
506
|
+
if (first) {
|
|
507
|
+
for (const alias of embedAliases(pathAndQuery)) {
|
|
508
|
+
if (Array.isArray(first[alias]) && (first[alias] as unknown[]).length >= SERVER_MAX_ROWS) {
|
|
509
|
+
console.warn(new TurbobaseTruncationError(pathAndQuery, SERVER_MAX_ROWS, alias).message);
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* Read rows from a PostgREST view/table (RLS-scoped).
|
|
517
|
+
*
|
|
518
|
+
* EMBEDS: \`select('item_receipt?select=*,inbound_shipment(*)')\` returns each
|
|
519
|
+
* receipt with its related rows attached under \`inbound_shipment\` \u2014 resolved by
|
|
520
|
+
* the instance in one round-trip either way, so you never fan out a lookup per
|
|
521
|
+
* row. A DECLARED-RELATIONSHIP embed is ALWAYS an array, including for a to-one
|
|
522
|
+
* link \u2014 the generated resolvers carry no \`ROWS 1\`, so PostgREST treats every
|
|
523
|
+
* one as to-many (it will even reject an order-by on the embed with PGRST118).
|
|
524
|
+
* A plain FOREIGN-KEY embed is different: it follows the FK's own cardinality,
|
|
525
|
+
* so \`item_receipt_line(*)\` is an array but \`subsidiary(name)\` is an object.
|
|
526
|
+
* Verified against PostgREST v12 and v14 in e2e/specs/108.
|
|
527
|
+
*
|
|
528
|
+
* LOUD TRUNCATION: an unbounded read (no \`limit=\`) that comes back at EXACTLY the
|
|
529
|
+
* server row cap was almost certainly cut short \u2014 a table with 1000+ rows returns
|
|
530
|
+
* a partial page indistinguishable from a complete one. When that happens we
|
|
531
|
+
* console.warn and tell you to paginate with selectPage(). The same warning fires
|
|
532
|
+
* when an EMBEDDED result was shortened. A caller that passed its own \`limit\`
|
|
533
|
+
* opted into a bounded read and is left alone.
|
|
534
|
+
*/
|
|
535
|
+
export async function select<T = unknown>(pathAndQuery: string): Promise<T[]> {
|
|
536
|
+
const result = await readRows<T>(pathAndQuery);
|
|
537
|
+
warnTruncation(pathAndQuery, result);
|
|
538
|
+
return result.rows;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* Turn a failed PostgREST response into a message that names the ACTUAL
|
|
543
|
+
* problem.
|
|
544
|
+
*
|
|
545
|
+
* "permission denied for table X" is the same error whether your role is denied
|
|
546
|
+
* that table or you are not signed in at all \u2014 in the second case PostgREST is
|
|
547
|
+
* answering as the anonymous role, and the fix is a sign-in, not a grant. That
|
|
548
|
+
* ambiguity is the single most expensive one to debug from inside an app, so we
|
|
549
|
+
* disambiguate it here rather than making every caller learn it: no session
|
|
550
|
+
* cookie means not signed in, whatever the SQLSTATE says.
|
|
551
|
+
*/
|
|
552
|
+
async function readError(res: Response): Promise<string> {
|
|
553
|
+
return readErrorFromBody(res.status, await res.text());
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
/** Same disambiguation, for a body that has already been read (the embed path
|
|
557
|
+
* has to inspect the body before deciding whether the failure is retryable). */
|
|
558
|
+
function readErrorFromBody(status: number, body: string): string {
|
|
559
|
+
const signedIn = jwt() !== '';
|
|
560
|
+
// 42501 = insufficient_privilege. With no token we were the anon role.
|
|
561
|
+
if (!signedIn && (status === 401 || status === 403 || body.includes('42501'))) {
|
|
562
|
+
return (
|
|
563
|
+
\`not signed in (\${status}) \u2014 the request went to PostgREST as the anonymous \` +
|
|
564
|
+
'role, so every table denies it. In dev, sign in at http://localhost:3000/login ' +
|
|
565
|
+
'(proxied to the instance); in production the instance signs you in before the ' +
|
|
566
|
+
\`app loads. Underlying error: \${body}\`
|
|
567
|
+
);
|
|
568
|
+
}
|
|
569
|
+
return \`read failed (\${status}): \${body}\`;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
/** Write through the canonical boundary POST /v1/data/<recordType>. Never write a
|
|
573
|
+
* table directly. \`body\` is { parent, lines?, idempotencyKey?, externalId?, pgRowId?,
|
|
574
|
+
* expectedSyncVersion? } \u2014 the record-type goes in the PATH, not the body. */
|
|
575
|
+
export async function write<T = unknown>(recordType: string, body: unknown): Promise<T> {
|
|
576
|
+
const res = await req(\`/v1/data/\${recordType}\`, {
|
|
577
|
+
method: 'POST',
|
|
578
|
+
headers: { 'content-type': 'application/json' },
|
|
579
|
+
body: JSON.stringify(body),
|
|
580
|
+
});
|
|
581
|
+
if (!res.ok) throw new Error(await readError(res));
|
|
582
|
+
return (await res.json()) as T;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/** One sub-result from batch(): its own status, so a 429/5xx on one query does
|
|
586
|
+
* not fail the others. \`ok\` is status 2xx; \`rows\` is the parsed body on
|
|
587
|
+
* success (undefined on failure \u2014 read \`status\`/\`error\`). */
|
|
588
|
+
export interface BatchResult<T = unknown> {
|
|
589
|
+
ok: boolean;
|
|
590
|
+
status: number;
|
|
591
|
+
rows?: T[];
|
|
592
|
+
error?: string;
|
|
593
|
+
/** Present when the instance resolved one or more embeds server-side for this
|
|
594
|
+
* query: the aliases it served, and any whose related rows were shortened by a
|
|
595
|
+
* server-side bound. */
|
|
596
|
+
stitched?: { aliases: string[]; truncated: string[] };
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/** How many sub-queries ride in ONE /v1/batch request. The instance holds every
|
|
600
|
+
* result in a chunk in memory at once, so this bounds its peak footprint as well
|
|
601
|
+
* as ours. Chunks are sent one after another, not in parallel \u2014 firing them
|
|
602
|
+
* together would rebuild the very fan-out batch() exists to collapse. */
|
|
603
|
+
const BATCH_CHUNK = 8;
|
|
604
|
+
|
|
605
|
+
/**
|
|
606
|
+
* Multiplex many reads into ONE request (POST /v1/batch). Pass the SAME
|
|
607
|
+
* path+query strings you would give select(); get back results in the SAME
|
|
608
|
+
* order, each with its own status (partial success). Use this for first-paint
|
|
609
|
+
* fan-out instead of many select() calls \u2014 one request never trips the
|
|
610
|
+
* per-request rate limiter.
|
|
611
|
+
*
|
|
612
|
+
* const [orders, invoices] = await batch(['order?select=*&limit=100', 'invoice?select=*&limit=100']);
|
|
613
|
+
* if (orders.ok) render(orders.rows);
|
|
614
|
+
*
|
|
615
|
+
* ASK FOR LESS THAN YOU THINK. The instance caps each sub-query's response and
|
|
616
|
+
* the batch's total; a sub-query over the ceiling comes back as its OWN
|
|
617
|
+
* \`{ ok: false, status: 413 }\` slot (the siblings still return) with a message
|
|
618
|
+
* naming the limit. Two habits cause almost every 413:
|
|
619
|
+
* - \`select=*\` on a synced table \u2014 it drags the whole \`raw\` JSONB blob per
|
|
620
|
+
* row. List the columns you actually render.
|
|
621
|
+
* - a \`limit\` sized for a table scan rather than a screen. Page instead;
|
|
622
|
+
* \`contentRange\` on each result tells you the total.
|
|
623
|
+
*
|
|
624
|
+
* Long query lists are chunked automatically, so passing 40 queries is safe \u2014
|
|
625
|
+
* but 40 narrow queries is a very different request from 40 wide ones, and only
|
|
626
|
+
* the second kind 413s.
|
|
627
|
+
*/
|
|
628
|
+
export async function batch<T = unknown>(queries: string[]): Promise<BatchResult<T>[]> {
|
|
629
|
+
const out: BatchResult<T>[] = [];
|
|
630
|
+
for (let i = 0; i < queries.length; i += BATCH_CHUNK) {
|
|
631
|
+
out.push(...(await batchChunk<T>(queries.slice(i, i + BATCH_CHUNK))));
|
|
632
|
+
}
|
|
633
|
+
return out;
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/** One wire request. Order in === order out, so the caller's slice reassembles. */
|
|
637
|
+
async function batchChunk<T>(queries: string[]): Promise<BatchResult<T>[]> {
|
|
638
|
+
if (queries.length === 0) return [];
|
|
639
|
+
const res = await req('/v1/batch', {
|
|
640
|
+
method: 'POST',
|
|
641
|
+
headers: { 'content-type': 'application/json', Accept: 'application/json' },
|
|
642
|
+
body: JSON.stringify({ queries }),
|
|
643
|
+
});
|
|
644
|
+
if (!res.ok) throw new Error(await readError(res));
|
|
645
|
+
const json = (await res.json()) as {
|
|
646
|
+
results: {
|
|
647
|
+
ok: boolean;
|
|
648
|
+
status: number;
|
|
649
|
+
body: unknown;
|
|
650
|
+
stitched?: { aliases: string[]; truncated: string[] };
|
|
651
|
+
}[];
|
|
652
|
+
};
|
|
653
|
+
return json.results.map((r) =>
|
|
654
|
+
r.ok
|
|
655
|
+
? { ok: true, status: r.status, rows: r.body as T[], stitched: r.stitched }
|
|
656
|
+
: {
|
|
657
|
+
ok: false,
|
|
658
|
+
status: r.status,
|
|
659
|
+
error:
|
|
660
|
+
typeof r.body === 'object' && r.body && 'error' in r.body
|
|
661
|
+
? String((r.body as { error: unknown }).error)
|
|
662
|
+
: typeof r.body === 'object' && r.body && 'message' in r.body
|
|
663
|
+
? String((r.body as { message: unknown }).message)
|
|
664
|
+
: JSON.stringify(r.body),
|
|
665
|
+
},
|
|
666
|
+
);
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
// ---------------------------------------------------------------------------
|
|
670
|
+
// Keyset pagination \u2014 page a table without draining it.
|
|
671
|
+
//
|
|
672
|
+
// select() is capped by the server at \${SERVER_MAX_ROWS} rows and warns when it
|
|
673
|
+
// truncates. selectPage() pages the FULL result set with a PostgREST-native
|
|
674
|
+
// keyset seek: order by the mirror sort key (\`pg_row_id\` when present, else
|
|
675
|
+
// \`external_id\` \u2014 pass { sortKey } for read-only masters), request one probe row
|
|
676
|
+
// beyond the page to detect a next page without a count, and seek the next page
|
|
677
|
+
// with \`<sortKey>=gt.<lastValue>\`. The opaque cursor pins itself to the exact
|
|
678
|
+
// query (table + filters + select) that minted it, so replaying it against a
|
|
679
|
+
// changed query throws instead of silently mixing two result sets.
|
|
680
|
+
// ---------------------------------------------------------------------------
|
|
681
|
+
|
|
682
|
+
/** One page of a keyset read: the trimmed rows, plus the token to fetch the next
|
|
683
|
+
* page (null when this was the last page). */
|
|
684
|
+
export interface Page<T = unknown> {
|
|
685
|
+
rows: T[];
|
|
686
|
+
nextCursor: string | null;
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/** Opaque cursor payload \u2014 the same compact { t, k, v, h } shape TurboBase's
|
|
690
|
+
* server-side cursors use (table, sort key, last value, query hash). */
|
|
691
|
+
interface CursorToken {
|
|
692
|
+
t: string;
|
|
693
|
+
k: string;
|
|
694
|
+
v: string;
|
|
695
|
+
h: string;
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
/** base64url-encode a UTF-8 string (no padding). */
|
|
699
|
+
function b64urlEncode(s: string): string {
|
|
700
|
+
const bytes = new TextEncoder().encode(s);
|
|
701
|
+
let bin = '';
|
|
702
|
+
for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]!);
|
|
703
|
+
return btoa(bin).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
/** base64url-decode back to a UTF-8 string. */
|
|
707
|
+
function b64urlDecode(s: string): string {
|
|
708
|
+
const b64 = s.replace(/-/g, '+').replace(/_/g, '/');
|
|
709
|
+
const pad = b64.length % 4 === 0 ? '' : '='.repeat(4 - (b64.length % 4));
|
|
710
|
+
const bytes = Uint8Array.from(atob(b64 + pad), (c) => c.charCodeAt(0));
|
|
711
|
+
return new TextDecoder().decode(bytes);
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
/** Mint an opaque next-page cursor. */
|
|
715
|
+
function encodeCursor(p: CursorToken): string {
|
|
716
|
+
return b64urlEncode(JSON.stringify({ t: p.t, k: p.k, v: p.v, h: p.h }));
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
/** Decode a cursor token; throws TurbobaseCursorError on a malformed one. */
|
|
720
|
+
function decodeCursor(token: string): CursorToken {
|
|
721
|
+
let parsed: unknown;
|
|
722
|
+
try {
|
|
723
|
+
parsed = JSON.parse(b64urlDecode(token));
|
|
724
|
+
} catch {
|
|
725
|
+
throw new TurbobaseCursorError('cursor is malformed (not a valid token)');
|
|
726
|
+
}
|
|
727
|
+
const o = parsed as Record<string, unknown> | null;
|
|
728
|
+
if (
|
|
729
|
+
!o ||
|
|
730
|
+
typeof o.t !== 'string' ||
|
|
731
|
+
typeof o.k !== 'string' ||
|
|
732
|
+
typeof o.v !== 'string' ||
|
|
733
|
+
typeof o.h !== 'string'
|
|
734
|
+
) {
|
|
735
|
+
throw new TurbobaseCursorError('cursor is malformed (missing fields)');
|
|
736
|
+
}
|
|
737
|
+
return { t: o.t, k: o.k, v: o.v, h: o.h };
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
/** FNV-1a 32-bit hex \u2014 a tiny, dependency-free hash. Not cryptographic: it only
|
|
741
|
+
* pins a cursor to the query that minted it, so a stale cursor is rejected. */
|
|
742
|
+
function fnv1a(s: string): string {
|
|
743
|
+
let h = 0x811c9dc5;
|
|
744
|
+
for (let i = 0; i < s.length; i++) {
|
|
745
|
+
h ^= s.charCodeAt(i);
|
|
746
|
+
h = (h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24))) >>> 0;
|
|
747
|
+
}
|
|
748
|
+
return h.toString(16).padStart(8, '0');
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
/** Hash the row-set-defining part of a query (table + sort key + every param
|
|
752
|
+
* except paging: order/limit/offset). Two pages of the same query hash equal;
|
|
753
|
+
* a changed filter/select hashes different and invalidates an old cursor. */
|
|
754
|
+
function queryHash(table: string, params: URLSearchParams, sortKey: string): string {
|
|
755
|
+
const parts: string[] = [];
|
|
756
|
+
for (const [k, v] of params) {
|
|
757
|
+
if (k === 'order' || k === 'limit' || k === 'offset') continue;
|
|
758
|
+
parts.push(\`\${k}=\${v}\`);
|
|
759
|
+
}
|
|
760
|
+
parts.sort();
|
|
761
|
+
return fnv1a(JSON.stringify([table, sortKey, parts]));
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
/**
|
|
765
|
+
* Read ONE keyset page from a PostgREST view/table (RLS-scoped), and return the
|
|
766
|
+
* cursor for the next page. Pass the SAME \`pathAndQuery\` you would give select()
|
|
767
|
+
* (filters, select, etc.) \u2014 selectPage() supplies the order + limit + seek.
|
|
768
|
+
*
|
|
769
|
+
* let { rows, nextCursor } = await selectPage('item_receipt?select=*', { pageSize: 50 });
|
|
770
|
+
* // \u2026later, load more:
|
|
771
|
+
* ({ rows, nextCursor } = await selectPage('item_receipt?select=*', { pageSize: 50, cursor: nextCursor }));
|
|
772
|
+
*
|
|
773
|
+
* \`sortKey\` defaults to \`pg_row_id\`; pass { sortKey: 'external_id' } for a
|
|
774
|
+
* read-only master table that has no \`pg_row_id\`.
|
|
775
|
+
*
|
|
776
|
+
* EMBEDS PAGE TOO: \`selectPage('purchase_order?select=*,receipt_lines(*)')\` keysets
|
|
777
|
+
* the PARENT (purchase_order) and carries the embed with each parent row, so a
|
|
778
|
+
* page is one request no matter how many related rows it pulls. If the instance
|
|
779
|
+
* had to shorten an embedded result it says so, and you get the same loud
|
|
780
|
+
* TurbobaseTruncationError warning select() gives \u2014 an embed that came back short
|
|
781
|
+
* is otherwise invisible, because the page's own row count is exactly what you
|
|
782
|
+
* asked for.
|
|
783
|
+
*/
|
|
784
|
+
export async function selectPage<T = unknown>(
|
|
785
|
+
pathAndQuery: string,
|
|
786
|
+
opts: { pageSize?: number; cursor?: string; sortKey?: string } = {},
|
|
787
|
+
): Promise<Page<T>> {
|
|
788
|
+
const pageSize = Math.max(1, Math.min(opts.pageSize ?? DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE));
|
|
789
|
+
const qIndex = pathAndQuery.indexOf('?');
|
|
790
|
+
const table = qIndex === -1 ? pathAndQuery : pathAndQuery.slice(0, qIndex);
|
|
791
|
+
const params = new URLSearchParams(qIndex === -1 ? '' : pathAndQuery.slice(qIndex + 1));
|
|
792
|
+
const sortKey = opts.sortKey ?? 'pg_row_id';
|
|
793
|
+
|
|
794
|
+
// Guarantee the sort key is projected so nextCursor can always be minted from
|
|
795
|
+
// the last row (mirrors the server's buildSelect). Split on TOP-LEVEL commas
|
|
796
|
+
// only: \`select=*,rel(a,b)\` must not be torn into \`rel(a\` + \`b)\`.
|
|
797
|
+
const sel = params.get('select');
|
|
798
|
+
if (sel && sel !== '*') {
|
|
799
|
+
const cols = splitTopLevel(sel);
|
|
800
|
+
if (!cols.includes(sortKey)) params.set('select', [...cols, sortKey].join(','));
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
// Pin the cursor to the row-set-defining query BEFORE paging params are added.
|
|
804
|
+
const filterHash = queryHash(table, params, sortKey);
|
|
805
|
+
|
|
806
|
+
// Keyset order + one probe row beyond the page \u2192 has-more without a count.
|
|
807
|
+
params.set('order', \`\${sortKey}.asc\`);
|
|
808
|
+
params.set('limit', String(pageSize + 1));
|
|
809
|
+
params.delete('offset');
|
|
810
|
+
|
|
811
|
+
if (opts.cursor) {
|
|
812
|
+
const c = decodeCursor(opts.cursor);
|
|
813
|
+
if (c.t !== table) {
|
|
814
|
+
throw new TurbobaseCursorError(\`cursor is for table "\${c.t}", not "\${table}"\`);
|
|
815
|
+
}
|
|
816
|
+
if (c.h !== filterHash) {
|
|
817
|
+
throw new TurbobaseCursorError(
|
|
818
|
+
'cursor does not match this query (filters/select/sort key changed since it was minted)',
|
|
819
|
+
);
|
|
820
|
+
}
|
|
821
|
+
// Strict total-order seek past the last row of the previous page.
|
|
822
|
+
params.set(sortKey, \`gt.\${c.v}\`);
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
// Same read primitive as select(), so a page whose \`select\` carries an embed
|
|
826
|
+
// takes the native path when the relationship is armed and the instance-resolved
|
|
827
|
+
// path when it is not \u2014 the keyset is over the PARENT either way, and the embed
|
|
828
|
+
// rides along with each parent row.
|
|
829
|
+
const pageQuery = \`\${table}?\${params.toString()}\`;
|
|
830
|
+
const result = await readRows<T>(pageQuery);
|
|
831
|
+
const probe = result.rows;
|
|
832
|
+
// Truncation on an embedded result is invisible without this \u2014 the page itself
|
|
833
|
+
// looks complete because the PARENT row count is whatever you asked for.
|
|
834
|
+
for (const alias of result.stitched?.truncated ?? []) {
|
|
835
|
+
console.warn(new TurbobaseTruncationError(pageQuery, SERVER_MAX_ROWS, alias).message);
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
// Trim the probe row; a next page exists iff the extra row came back.
|
|
839
|
+
const hasMore = probe.length > pageSize;
|
|
840
|
+
const rows = hasMore ? probe.slice(0, pageSize) : probe;
|
|
841
|
+
|
|
842
|
+
let nextCursor: string | null = null;
|
|
843
|
+
if (hasMore && rows.length > 0) {
|
|
844
|
+
const last = rows[rows.length - 1] as Record<string, unknown>;
|
|
845
|
+
const lastValue = last[sortKey];
|
|
846
|
+
if (lastValue != null) {
|
|
847
|
+
nextCursor = encodeCursor({ t: table, k: sortKey, v: String(lastValue), h: filterHash });
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
return { rows, nextCursor };
|
|
851
|
+
}
|
|
852
|
+
`;hb="http://localhost:54331",mb="http://localhost:4100";bb=`node_modules/
|
|
853
|
+
dist/
|
|
854
|
+
build/
|
|
855
|
+
|
|
856
|
+
# Holds a live personal access token (written by \`turbobase apps init\`).
|
|
857
|
+
.mcp.json
|
|
858
|
+
|
|
859
|
+
.env
|
|
860
|
+
.env.*
|
|
861
|
+
!.env.example
|
|
862
|
+
|
|
863
|
+
.DS_Store
|
|
864
|
+
`,eu=`${JSON.stringify({compilerOptions:{target:"ES2022",lib:["ES2022","DOM","DOM.Iterable"],module:"ESNext",moduleResolution:"bundler",jsx:"react-jsx",strict:!0,skipLibCheck:!0,noEmit:!0},include:["src"]},null,2)}
|
|
865
|
+
`;ru=`import React from 'react';
|
|
866
|
+
import { createRoot } from 'react-dom/client';
|
|
867
|
+
import App from './App';
|
|
868
|
+
import './styles.css';
|
|
869
|
+
|
|
870
|
+
createRoot(document.getElementById('root')!).render(
|
|
871
|
+
<React.StrictMode>
|
|
872
|
+
<App />
|
|
873
|
+
</React.StrictMode>,
|
|
874
|
+
);
|
|
875
|
+
`,nu=`:root { color-scheme: light; font-family: ui-sans-serif, system-ui, sans-serif; }
|
|
876
|
+
* { box-sizing: border-box; }
|
|
877
|
+
body { margin: 0; background: #f8fafc; color: #0f172a; }
|
|
878
|
+
`});import*as iu from"zod/v3";import*as Jt from"zod/v4-mini";function ut(t){return!!t._zod}function Zt(t){let e=Object.values(t);if(e.length===0)return Jt.object({});let r=e.every(ut),n=e.every(o=>!ut(o));if(r)return Jt.object(t);if(n)return iu.object(t);throw new Error("Mixed Zod versions detected in object shape.")}function Pt(t,e){return ut(t)?Jt.safeParse(t,e):t.safeParse(e)}async function go(t,e){return ut(t)?await Jt.safeParseAsync(t,e):await t.safeParseAsync(e)}function At(t){if(!t)return;let e;if(ut(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function hr(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Zt(t)}}if(ut(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function _b(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function yo(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 ${_b(e.path)}`:e.message).join(`
|
|
879
|
+
`);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function au(t){return t.description}function cu(t){if(ut(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function mr(t){if(ut(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var on=O(()=>{});import*as c from"zod/v4";function xu(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Tu(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var xi,lu,Ct,wo,ve,du,uu,rR,Sb,$b,Ti,He,sn,pu,$e,Ze,Ye,ke,vo,fu,Ei,hu,mu,Ri,an,M,Pi,gu,yu,nR,_o,kb,So,xb,cn,gr,bu,Tb,Eb,Rb,Pb,Ab,Cb,Ai,Ib,Ob,Ci,$o,Nb,jb,ko,zb,ln,dn,Lb,un,yr,Db,pn,xo,To,Eo,oR,Ro,Po,Ao,wu,vu,_u,Ii,Su,fn,br,$u,Mb,Co,qb,Io,Ub,Oi,Bb,Oo,Fb,Hb,Kb,Vb,Gb,Wb,Jb,Zb,Yb,Qb,No,Xb,ew,jo,Ni,ji,zi,tw,rw,nw,Li,ow,sw,iw,aw,cw,ku,zo,lw,Lo,sR,dw,wr,uw,iR,hn,pw,Di,fw,hw,mw,gw,yw,bw,ww,bo,vw,_w,Sw,mn,Mi,$w,kw,xw,Tw,Ew,Rw,Pw,Aw,Cw,Iw,Ow,Nw,jw,zw,Lw,Dw,Mw,qw,vr,Uw,Bw,Fw,Do,Hw,Kw,Vw,qi,Gw,aR,cR,lR,dR,uR,pR,z,ki,_r=O(()=>{xi="2025-11-25",lu=[xi,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ct="io.modelcontextprotocol/related-task",wo="2.0",ve=c.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),du=c.union([c.string(),c.number().int()]),uu=c.string(),rR=c.looseObject({ttl:c.number().optional(),pollInterval:c.number().optional()}),Sb=c.object({ttl:c.number().optional()}),$b=c.object({taskId:c.string()}),Ti=c.looseObject({progressToken:du.optional(),[Ct]:$b.optional()}),He=c.object({_meta:Ti.optional()}),sn=He.extend({task:Sb.optional()}),pu=t=>sn.safeParse(t).success,$e=c.object({method:c.string(),params:He.loose().optional()}),Ze=c.object({_meta:Ti.optional()}),Ye=c.object({method:c.string(),params:Ze.loose().optional()}),ke=c.looseObject({_meta:Ti.optional()}),vo=c.union([c.string(),c.number().int()]),fu=c.object({jsonrpc:c.literal(wo),id:vo,...$e.shape}).strict(),Ei=t=>fu.safeParse(t).success,hu=c.object({jsonrpc:c.literal(wo),...Ye.shape}).strict(),mu=t=>hu.safeParse(t).success,Ri=c.object({jsonrpc:c.literal(wo),id:vo,result:ke}).strict(),an=t=>Ri.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={}));Pi=c.object({jsonrpc:c.literal(wo),id:vo.optional(),error:c.object({code:c.number().int(),message:c.string(),data:c.unknown().optional()})}).strict(),gu=t=>Pi.safeParse(t).success,yu=c.union([fu,hu,Ri,Pi]),nR=c.union([Ri,Pi]),_o=ke.strict(),kb=Ze.extend({requestId:vo.optional(),reason:c.string().optional()}),So=Ye.extend({method:c.literal("notifications/cancelled"),params:kb}),xb=c.object({src:c.string(),mimeType:c.string().optional(),sizes:c.array(c.string()).optional(),theme:c.enum(["light","dark"]).optional()}),cn=c.object({icons:c.array(xb).optional()}),gr=c.object({name:c.string(),title:c.string().optional()}),bu=gr.extend({...gr.shape,...cn.shape,version:c.string(),websiteUrl:c.string().optional(),description:c.string().optional()}),Tb=c.intersection(c.object({applyDefaults:c.boolean().optional()}),c.record(c.string(),c.unknown())),Eb=c.preprocess(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,c.intersection(c.object({form:Tb.optional(),url:ve.optional()}),c.record(c.string(),c.unknown()).optional())),Rb=c.looseObject({list:ve.optional(),cancel:ve.optional(),requests:c.looseObject({sampling:c.looseObject({createMessage:ve.optional()}).optional(),elicitation:c.looseObject({create:ve.optional()}).optional()}).optional()}),Pb=c.looseObject({list:ve.optional(),cancel:ve.optional(),requests:c.looseObject({tools:c.looseObject({call:ve.optional()}).optional()}).optional()}),Ab=c.object({experimental:c.record(c.string(),ve).optional(),sampling:c.object({context:ve.optional(),tools:ve.optional()}).optional(),elicitation:Eb.optional(),roots:c.object({listChanged:c.boolean().optional()}).optional(),tasks:Rb.optional(),extensions:c.record(c.string(),ve).optional()}),Cb=He.extend({protocolVersion:c.string(),capabilities:Ab,clientInfo:bu}),Ai=$e.extend({method:c.literal("initialize"),params:Cb}),Ib=c.object({experimental:c.record(c.string(),ve).optional(),logging:ve.optional(),completions:ve.optional(),prompts:c.object({listChanged:c.boolean().optional()}).optional(),resources:c.object({subscribe:c.boolean().optional(),listChanged:c.boolean().optional()}).optional(),tools:c.object({listChanged:c.boolean().optional()}).optional(),tasks:Pb.optional(),extensions:c.record(c.string(),ve).optional()}),Ob=ke.extend({protocolVersion:c.string(),capabilities:Ib,serverInfo:bu,instructions:c.string().optional()}),Ci=Ye.extend({method:c.literal("notifications/initialized"),params:Ze.optional()}),$o=$e.extend({method:c.literal("ping"),params:He.optional()}),Nb=c.object({progress:c.number(),total:c.optional(c.number()),message:c.optional(c.string())}),jb=c.object({...Ze.shape,...Nb.shape,progressToken:du}),ko=Ye.extend({method:c.literal("notifications/progress"),params:jb}),zb=He.extend({cursor:uu.optional()}),ln=$e.extend({params:zb.optional()}),dn=ke.extend({nextCursor:uu.optional()}),Lb=c.enum(["working","input_required","completed","failed","cancelled"]),un=c.object({taskId:c.string(),status:Lb,ttl:c.union([c.number(),c.null()]),createdAt:c.string(),lastUpdatedAt:c.string(),pollInterval:c.optional(c.number()),statusMessage:c.optional(c.string())}),yr=ke.extend({task:un}),Db=Ze.merge(un),pn=Ye.extend({method:c.literal("notifications/tasks/status"),params:Db}),xo=$e.extend({method:c.literal("tasks/get"),params:He.extend({taskId:c.string()})}),To=ke.merge(un),Eo=$e.extend({method:c.literal("tasks/result"),params:He.extend({taskId:c.string()})}),oR=ke.loose(),Ro=ln.extend({method:c.literal("tasks/list")}),Po=dn.extend({tasks:c.array(un)}),Ao=$e.extend({method:c.literal("tasks/cancel"),params:He.extend({taskId:c.string()})}),wu=ke.merge(un),vu=c.object({uri:c.string(),mimeType:c.optional(c.string()),_meta:c.record(c.string(),c.unknown()).optional()}),_u=vu.extend({text:c.string()}),Ii=c.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Su=vu.extend({blob:Ii}),fn=c.enum(["user","assistant"]),br=c.object({audience:c.array(fn).optional(),priority:c.number().min(0).max(1).optional(),lastModified:c.iso.datetime({offset:!0}).optional()}),$u=c.object({...gr.shape,...cn.shape,uri:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),size:c.optional(c.number()),annotations:br.optional(),_meta:c.optional(c.looseObject({}))}),Mb=c.object({...gr.shape,...cn.shape,uriTemplate:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),annotations:br.optional(),_meta:c.optional(c.looseObject({}))}),Co=ln.extend({method:c.literal("resources/list")}),qb=dn.extend({resources:c.array($u)}),Io=ln.extend({method:c.literal("resources/templates/list")}),Ub=dn.extend({resourceTemplates:c.array(Mb)}),Oi=He.extend({uri:c.string()}),Bb=Oi,Oo=$e.extend({method:c.literal("resources/read"),params:Bb}),Fb=ke.extend({contents:c.array(c.union([_u,Su]))}),Hb=Ye.extend({method:c.literal("notifications/resources/list_changed"),params:Ze.optional()}),Kb=Oi,Vb=$e.extend({method:c.literal("resources/subscribe"),params:Kb}),Gb=Oi,Wb=$e.extend({method:c.literal("resources/unsubscribe"),params:Gb}),Jb=Ze.extend({uri:c.string()}),Zb=Ye.extend({method:c.literal("notifications/resources/updated"),params:Jb}),Yb=c.object({name:c.string(),description:c.optional(c.string()),required:c.optional(c.boolean())}),Qb=c.object({...gr.shape,...cn.shape,description:c.optional(c.string()),arguments:c.optional(c.array(Yb)),_meta:c.optional(c.looseObject({}))}),No=ln.extend({method:c.literal("prompts/list")}),Xb=dn.extend({prompts:c.array(Qb)}),ew=He.extend({name:c.string(),arguments:c.record(c.string(),c.string()).optional()}),jo=$e.extend({method:c.literal("prompts/get"),params:ew}),Ni=c.object({type:c.literal("text"),text:c.string(),annotations:br.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),ji=c.object({type:c.literal("image"),data:Ii,mimeType:c.string(),annotations:br.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),zi=c.object({type:c.literal("audio"),data:Ii,mimeType:c.string(),annotations:br.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),tw=c.object({type:c.literal("tool_use"),name:c.string(),id:c.string(),input:c.record(c.string(),c.unknown()),_meta:c.record(c.string(),c.unknown()).optional()}),rw=c.object({type:c.literal("resource"),resource:c.union([_u,Su]),annotations:br.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),nw=$u.extend({type:c.literal("resource_link")}),Li=c.union([Ni,ji,zi,nw,rw]),ow=c.object({role:fn,content:Li}),sw=ke.extend({description:c.string().optional(),messages:c.array(ow)}),iw=Ye.extend({method:c.literal("notifications/prompts/list_changed"),params:Ze.optional()}),aw=c.object({title:c.string().optional(),readOnlyHint:c.boolean().optional(),destructiveHint:c.boolean().optional(),idempotentHint:c.boolean().optional(),openWorldHint:c.boolean().optional()}),cw=c.object({taskSupport:c.enum(["required","optional","forbidden"]).optional()}),ku=c.object({...gr.shape,...cn.shape,description:c.string().optional(),inputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),ve).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()),outputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),ve).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()).optional(),annotations:aw.optional(),execution:cw.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),zo=ln.extend({method:c.literal("tools/list")}),lw=dn.extend({tools:c.array(ku)}),Lo=ke.extend({content:c.array(Li).default([]),structuredContent:c.record(c.string(),c.unknown()).optional(),isError:c.boolean().optional()}),sR=Lo.or(ke.extend({toolResult:c.unknown()})),dw=sn.extend({name:c.string(),arguments:c.record(c.string(),c.unknown()).optional()}),wr=$e.extend({method:c.literal("tools/call"),params:dw}),uw=Ye.extend({method:c.literal("notifications/tools/list_changed"),params:Ze.optional()}),iR=c.object({autoRefresh:c.boolean().default(!0),debounceMs:c.number().int().nonnegative().default(300)}),hn=c.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),pw=He.extend({level:hn}),Di=$e.extend({method:c.literal("logging/setLevel"),params:pw}),fw=Ze.extend({level:hn,logger:c.string().optional(),data:c.unknown()}),hw=Ye.extend({method:c.literal("notifications/message"),params:fw}),mw=c.object({name:c.string().optional()}),gw=c.object({hints:c.array(mw).optional(),costPriority:c.number().min(0).max(1).optional(),speedPriority:c.number().min(0).max(1).optional(),intelligencePriority:c.number().min(0).max(1).optional()}),yw=c.object({mode:c.enum(["auto","required","none"]).optional()}),bw=c.object({type:c.literal("tool_result"),toolUseId:c.string().describe("The unique identifier for the corresponding tool call."),content:c.array(Li).default([]),structuredContent:c.object({}).loose().optional(),isError:c.boolean().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),ww=c.discriminatedUnion("type",[Ni,ji,zi]),bo=c.discriminatedUnion("type",[Ni,ji,zi,tw,bw]),vw=c.object({role:fn,content:c.union([bo,c.array(bo)]),_meta:c.record(c.string(),c.unknown()).optional()}),_w=sn.extend({messages:c.array(vw),modelPreferences:gw.optional(),systemPrompt:c.string().optional(),includeContext:c.enum(["none","thisServer","allServers"]).optional(),temperature:c.number().optional(),maxTokens:c.number().int(),stopSequences:c.array(c.string()).optional(),metadata:ve.optional(),tools:c.array(ku).optional(),toolChoice:yw.optional()}),Sw=$e.extend({method:c.literal("sampling/createMessage"),params:_w}),mn=ke.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens"]).or(c.string())),role:fn,content:ww}),Mi=ke.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(c.string())),role:fn,content:c.union([bo,c.array(bo)])}),$w=c.object({type:c.literal("boolean"),title:c.string().optional(),description:c.string().optional(),default:c.boolean().optional()}),kw=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),minLength:c.number().optional(),maxLength:c.number().optional(),format:c.enum(["email","uri","date","date-time"]).optional(),default:c.string().optional()}),xw=c.object({type:c.enum(["number","integer"]),title:c.string().optional(),description:c.string().optional(),minimum:c.number().optional(),maximum:c.number().optional(),default:c.number().optional()}),Tw=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),enum:c.array(c.string()),default:c.string().optional()}),Ew=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),oneOf:c.array(c.object({const:c.string(),title:c.string()})),default:c.string().optional()}),Rw=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),enum:c.array(c.string()),enumNames:c.array(c.string()).optional(),default:c.string().optional()}),Pw=c.union([Tw,Ew]),Aw=c.object({type:c.literal("array"),title:c.string().optional(),description:c.string().optional(),minItems:c.number().optional(),maxItems:c.number().optional(),items:c.object({type:c.literal("string"),enum:c.array(c.string())}),default:c.array(c.string()).optional()}),Cw=c.object({type:c.literal("array"),title:c.string().optional(),description:c.string().optional(),minItems:c.number().optional(),maxItems:c.number().optional(),items:c.object({anyOf:c.array(c.object({const:c.string(),title:c.string()}))}),default:c.array(c.string()).optional()}),Iw=c.union([Aw,Cw]),Ow=c.union([Rw,Pw,Iw]),Nw=c.union([Ow,$w,kw,xw]),jw=sn.extend({mode:c.literal("form").optional(),message:c.string(),requestedSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),Nw),required:c.array(c.string()).optional()})}),zw=sn.extend({mode:c.literal("url"),message:c.string(),elicitationId:c.string(),url:c.string().url()}),Lw=c.union([jw,zw]),Dw=$e.extend({method:c.literal("elicitation/create"),params:Lw}),Mw=Ze.extend({elicitationId:c.string()}),qw=Ye.extend({method:c.literal("notifications/elicitation/complete"),params:Mw}),vr=ke.extend({action:c.enum(["accept","decline","cancel"]),content:c.preprocess(t=>t===null?void 0:t,c.record(c.string(),c.union([c.string(),c.number(),c.boolean(),c.array(c.string())])).optional())}),Uw=c.object({type:c.literal("ref/resource"),uri:c.string()}),Bw=c.object({type:c.literal("ref/prompt"),name:c.string()}),Fw=He.extend({ref:c.union([Bw,Uw]),argument:c.object({name:c.string(),value:c.string()}),context:c.object({arguments:c.record(c.string(),c.string()).optional()}).optional()}),Do=$e.extend({method:c.literal("completion/complete"),params:Fw});Hw=ke.extend({completion:c.looseObject({values:c.array(c.string()).max(100),total:c.optional(c.number().int()),hasMore:c.optional(c.boolean())})}),Kw=c.object({uri:c.string().startsWith("file://"),name:c.string().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Vw=$e.extend({method:c.literal("roots/list"),params:He.optional()}),qi=ke.extend({roots:c.array(Kw)}),Gw=Ye.extend({method:c.literal("notifications/roots/list_changed"),params:Ze.optional()}),aR=c.union([$o,Ai,Do,Di,jo,No,Co,Io,Oo,Vb,Wb,wr,zo,xo,Eo,Ro,Ao]),cR=c.union([So,ko,Ci,Gw,pn]),lR=c.union([_o,mn,Mi,vr,qi,To,Po,yr]),dR=c.union([$o,Sw,Dw,Vw,xo,Eo,Ro,Ao]),uR=c.union([So,ko,hw,Zb,Hb,uw,iw,pn,qw]),pR=c.union([_o,Ob,Hw,sw,Xb,qb,Ub,Fb,Lo,lw,To,Po,yr]),z=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===M.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new ki(o.elicitations,r)}return new t(e,r,n)}},ki=class extends z{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(M.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function It(t){return t==="completed"||t==="failed"||t==="cancelled"}var Eu=O(()=>{});var Pu,Ru,Au,Mo=O(()=>{Pu=Symbol("Let zodToJsonSchema decide on which parser to use"),Ru={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"},Au=t=>typeof t=="string"?{...Ru,name:t}:{...Ru,...t}});var Cu,Ui=O(()=>{Mo();Cu=t=>{let e=Au(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function Bi(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ee(t,e,r,n,o){t[e]=r,Bi(t,e,n,o)}var Ot=O(()=>{});var qo,Uo=O(()=>{qo=(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 he(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?qo(e,t.currentPath):e.join("/")}}var Qe=O(()=>{Uo()});import{ZodFirstPartyTypeKind as Ww}from"zod/v3";function Iu(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==Ww.ZodAny&&(r.items=q(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ee(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ee(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ee(r,"minItems",t.exactLength.value,t.exactLength.message,e),ee(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var Fi=O(()=>{Ot();we()});function Ou(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?ee(r,"minimum",n.value,n.message,e):ee(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ee(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ee(r,"maximum",n.value,n.message,e):ee(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ee(r,"maximum",n.value,n.message,e));break;case"multipleOf":ee(r,"multipleOf",n.value,n.message,e);break}return r}var Hi=O(()=>{Ot()});function Nu(){return{type:"boolean"}}var Ki=O(()=>{});function Bo(t,e){return q(t.type._def,e)}var Fo=O(()=>{we()});var ju,Vi=O(()=>{we();ju=(t,e)=>q(t.innerType._def,e)});function Gi(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Gi(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Jw(t,e)}}var Jw,Wi=O(()=>{Ot();Jw=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":ee(r,"minimum",n.value,n.message,e);break;case"max":ee(r,"maximum",n.value,n.message,e);break}return r}});function zu(t,e){return{...q(t.innerType._def,e),default:t.defaultValue()}}var Ji=O(()=>{we()});function Lu(t,e){return e.effectStrategy==="input"?q(t.schema._def,e):he(e)}var Zi=O(()=>{we();Qe()});function Du(t){return{type:"string",enum:Array.from(t.values)}}var Yi=O(()=>{});function Mu(t,e){let r=[q(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),q(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(Zw(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...l}=s;i=l}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}var Zw,Qi=O(()=>{we();Zw=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function qu(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 Xi=O(()=>{});function Ho(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ee(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ee(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":ot(r,"email",n.message,e);break;case"format:idn-email":ot(r,"idn-email",n.message,e);break;case"pattern:zod":Ie(r,nt.email,n.message,e);break}break;case"url":ot(r,"uri",n.message,e);break;case"uuid":ot(r,"uuid",n.message,e);break;case"regex":Ie(r,n.regex,n.message,e);break;case"cuid":Ie(r,nt.cuid,n.message,e);break;case"cuid2":Ie(r,nt.cuid2,n.message,e);break;case"startsWith":Ie(r,RegExp(`^${ta(n.value,e)}`),n.message,e);break;case"endsWith":Ie(r,RegExp(`${ta(n.value,e)}$`),n.message,e);break;case"datetime":ot(r,"date-time",n.message,e);break;case"date":ot(r,"date",n.message,e);break;case"time":ot(r,"time",n.message,e);break;case"duration":ot(r,"duration",n.message,e);break;case"length":ee(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ee(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Ie(r,RegExp(ta(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&ot(r,"ipv4",n.message,e),n.version!=="v4"&&ot(r,"ipv6",n.message,e);break}case"base64url":Ie(r,nt.base64url,n.message,e);break;case"jwt":Ie(r,nt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Ie(r,nt.ipv4Cidr,n.message,e),n.version!=="v4"&&Ie(r,nt.ipv6Cidr,n.message,e);break}case"emoji":Ie(r,nt.emoji(),n.message,e);break;case"ulid":{Ie(r,nt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{ot(r,"binary",n.message,e);break}case"contentEncoding:base64":{ee(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Ie(r,nt.base64,n.message,e);break}}break}case"nanoid":Ie(r,nt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function ta(t,e){return e.patternStrategy==="escape"?Qw(t):t}function Qw(t){let e="";for(let r=0;r<t.length;r++)Yw.has(t[r])||(e+="\\"),e+=t[r];return e}function ot(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ee(t,"format",e,r,n)}function Ie(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Uu(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ee(t,"pattern",Uu(e,n),r,n)}function Uu(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let l=0;l<n.length;l++){if(s){o+=n[l],s=!1;continue}if(r.i){if(i){if(n[l].match(/[a-z]/)){a?(o+=n[l],o+=`${n[l-2]}-${n[l]}`.toUpperCase(),a=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(o+=n[l],a=!0):o+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){o+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(r.m){if(n[l]==="^"){o+=`(^|(?<=[\r
|
|
880
|
+
]))`;continue}else if(n[l]==="$"){o+=`($|(?=[\r
|
|
881
|
+
]))`;continue}}if(r.s&&n[l]==="."){o+=i?`${n[l]}\r
|
|
882
|
+
`:`[${n[l]}\r
|
|
883
|
+
]`;continue}o+=n[l],n[l]==="\\"?s=!0:i&&n[l]==="]"?i=!1:!i&&n[l]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var ea,nt,Yw,Ko=O(()=>{Ot();nt={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:()=>(ea===void 0&&(ea=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ea),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-_]*$/};Yw=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});import{ZodFirstPartyTypeKind as gn}from"zod/v3";function Vo(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===gn.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:q(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??he(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:q(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===gn.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Ho(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===gn.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===gn.ZodBranded&&t.keyType._def.type._def.typeName===gn.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Bo(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var Go=O(()=>{we();Ko();Fo();Qe()});function Bu(t,e){if(e.mapStrategy==="record")return Vo(t,e);let r=q(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||he(e),n=q(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||he(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var ra=O(()=>{we();Go();Qe()});function Fu(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}var na=O(()=>{});function Hu(t){return t.target==="openAi"?void 0:{not:he({...t,currentPath:[...t.currentPath,"not"]})}}var oa=O(()=>{Qe()});function Ku(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var sa=O(()=>{});function Gu(t,e){if(e.target==="openApi3")return Vu(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in yn&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=yn[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return Vu(t,e)}var yn,Vu,Wo=O(()=>{we();yn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Vu=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>q(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function Wu(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:yn[t.innerType._def.typeName],nullable:!0}:{type:[yn[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=q(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=q(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var ia=O(()=>{we();Wo()});function Ju(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",Bi(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ee(r,"minimum",n.value,n.message,e):ee(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ee(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ee(r,"maximum",n.value,n.message,e):ee(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ee(r,"maximum",n.value,n.message,e));break;case"multipleOf":ee(r,"multipleOf",n.value,n.message,e);break}return r}var aa=O(()=>{Ot()});function Zu(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let l=s[a];if(l===void 0||l._def===void 0)continue;let p=ev(l);p&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),p=!1);let u=q(l._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});u!==void 0&&(n.properties[a]=u,p||o.push(a))}o.length&&(n.required=o);let i=Xw(t,e);return i!==void 0&&(n.additionalProperties=i),n}function Xw(t,e){if(t.catchall._def.typeName!=="ZodNever")return q(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 ev(t){try{return t.isOptional()}catch{return!0}}var ca=O(()=>{we()});var Yu,la=O(()=>{we();Qe();Yu=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return q(t.innerType._def,e);let r=q(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:he(e)},r]}:he(e)}});var Qu,da=O(()=>{we();Qu=(t,e)=>{if(e.pipeStrategy==="input")return q(t.in._def,e);if(e.pipeStrategy==="output")return q(t.out._def,e);let r=q(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=q(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function Xu(t,e){return q(t.type._def,e)}var ua=O(()=>{we()});function ep(t,e){let n={type:"array",uniqueItems:!0,items:q(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ee(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ee(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var pa=O(()=>{Ot();we()});function tp(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>q(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:q(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>q(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var fa=O(()=>{we()});function rp(t){return{not:he(t)}}var ha=O(()=>{Qe()});function np(t){return he(t)}var ma=O(()=>{Qe()});var op,ga=O(()=>{we();op=(t,e)=>q(t.innerType._def,e)});import{ZodFirstPartyTypeKind as Y}from"zod/v3";var sp,ya=O(()=>{Qe();Fi();Hi();Ki();Fo();Vi();Wi();Ji();Zi();Yi();Qi();Xi();ra();na();oa();sa();ia();aa();ca();la();da();ua();Go();pa();Ko();fa();ha();Wo();ma();ga();sp=(t,e,r)=>{switch(e){case Y.ZodString:return Ho(t,r);case Y.ZodNumber:return Ju(t,r);case Y.ZodObject:return Zu(t,r);case Y.ZodBigInt:return Ou(t,r);case Y.ZodBoolean:return Nu();case Y.ZodDate:return Gi(t,r);case Y.ZodUndefined:return rp(r);case Y.ZodNull:return Ku(r);case Y.ZodArray:return Iu(t,r);case Y.ZodUnion:case Y.ZodDiscriminatedUnion:return Gu(t,r);case Y.ZodIntersection:return Mu(t,r);case Y.ZodTuple:return tp(t,r);case Y.ZodRecord:return Vo(t,r);case Y.ZodLiteral:return qu(t,r);case Y.ZodEnum:return Du(t);case Y.ZodNativeEnum:return Fu(t);case Y.ZodNullable:return Wu(t,r);case Y.ZodOptional:return Yu(t,r);case Y.ZodMap:return Bu(t,r);case Y.ZodSet:return ep(t,r);case Y.ZodLazy:return()=>t.getter()._def;case Y.ZodPromise:return Xu(t,r);case Y.ZodNaN:case Y.ZodNever:return Hu(r);case Y.ZodEffects:return Lu(t,r);case Y.ZodAny:return he(r);case Y.ZodUnknown:return np(r);case Y.ZodDefault:return zu(t,r);case Y.ZodBranded:return Bo(t,r);case Y.ZodReadonly:return op(t,r);case Y.ZodCatch:return ju(t,r);case Y.ZodPipeline:return Qu(t,r);case Y.ZodFunction:case Y.ZodVoid:case Y.ZodSymbol:return;default:return(n=>{})(e)}}});function q(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==Pu)return a}if(n&&!r){let a=tv(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=sp(t,t.typeName,e),i=typeof s=="function"?q(s(),e):s;if(i&&rv(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var tv,rv,we=O(()=>{Mo();ya();Uo();Qe();tv=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:qo(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`),he(e)):e.$refStrategy==="seen"?he(e):void 0}},rv=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var ip=O(()=>{});var ba,wa=O(()=>{we();Ui();Qe();ba=(t,e)=>{let r=Cu(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[p,u])=>({...l,[p]:q(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,p]},!0)??he(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=q(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??he(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var ap=O(()=>{Mo();Ui();Ot();Uo();we();ip();Qe();Fi();Hi();Ki();Fo();Vi();Wi();Ji();Zi();Yi();Qi();Xi();ra();na();oa();sa();ia();aa();ca();la();da();ua();ga();Go();pa();Ko();fa();ha();Wo();ma();ya();wa();wa()});import*as cp from"zod/v4-mini";function nv(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function va(t,e){return ut(t)?cp.toJSONSchema(t,{target:nv(e?.target),io:e?.pipeStrategy??"input"}):ba(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function _a(t){let r=At(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=mr(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Sa(t,e){let r=Pt(t,e);if(!r.success)throw r.error;return r.data}var $a=O(()=>{on();ap()});function lp(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function dp(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];lp(i)&&lp(s)?r[o]={...i,...s}:r[o]=s}return r}var ov,Jo,up=O(()=>{on();_r();Eu();$a();ov=6e4,Jo=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(So,r=>{this._oncancel(r)}),this.setNotificationHandler(ko,r=>{this._onprogress(r)}),this.setRequestHandler($o,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(xo,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new z(M.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Eo,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let l=a.message,p=l.id,u=this._requestResolvers.get(p);if(u)if(this._requestResolvers.delete(p),a.type==="response")u(l);else{let d=l,f=new z(d.error.code,d.error.message,d.error.data);u(f)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${p}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new z(M.InvalidParams,`Task not found: ${s}`);if(!It(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(It(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Ct]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Ro,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new z(M.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Ao,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new z(M.InvalidParams,`Task not found: ${r.params.taskId}`);if(It(o.status))throw new z(M.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new z(M.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof z?o:new z(M.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),z.fromError(M.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),an(s)||gu(s)?this._onresponse(s):Ei(s)?this._onrequest(s,i):mu(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=z.fromError(M.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[Ct]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:M.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(u).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=pu(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,p={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(u,d)},sendRequest:async(u,d,f)=>{if(i.signal.aborted)throw new z(M.ConnectionClosed,"Request was cancelled");let g={...f,relatedRequestId:e.id};s&&!g.relatedTask&&(g.relatedTask={taskId:s});let b=g.relatedTask?.taskId??s;return b&&l&&await l.updateTaskStatus(b,"input_required"),await this.request(u,d,g)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:l,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,p)).then(async u=>{if(i.signal.aborted)return;let d={result:u,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async u=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:M.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(l){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(l);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),an(e))n(e);else{let i=new z(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(an(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),an(e))o(e);else{let i=z.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof z?i:new z(M.InternalError,String(i))}}return}let s;try{let i=await this.request(e,yr,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new z(M.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},It(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new z(M.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new z(M.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let l=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(p=>setTimeout(p,l)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof z?i:new z(M.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:l}=n??{};return new Promise((p,u)=>{let d=N=>{u(N)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(N){d(N);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,g={...e,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),g.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),a&&(g.params={...g.params,task:a}),l&&(g.params={...g.params,_meta:{...g.params?._meta||{},[Ct]:l}});let b=N=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(N)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(Q=>this._onerror(new Error(`Failed to send cancellation: ${Q}`)));let D=N instanceof z?N:new z(M.RequestTimeout,String(N));u(D)};this._responseHandlers.set(f,N=>{if(!n?.signal?.aborted){if(N instanceof Error)return u(N);try{let D=Pt(r,N.result);D.success?p(D.data):u(D.error)}catch(D){u(D)}}}),n?.signal?.addEventListener("abort",()=>{b(n?.signal?.reason)});let v=n?.timeout??ov,x=()=>b(z.fromError(M.RequestTimeout,"Request timed out",{timeout:v}));this._setupTimeout(f,v,n?.maxTotalTimeout,x,n?.resetTimeoutOnProgress??!1);let P=l?.taskId;if(P){let N=D=>{let Q=this._responseHandlers.get(f);Q?Q(D):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,N),this._enqueueTaskMessage(P,{type:"request",message:g,timestamp:Date.now()}).catch(D=>{this._cleanupTimeout(f),u(D)})}else this._transport.send(g,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(N=>{this._cleanupTimeout(f),u(N)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},To,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},Po,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},wu,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||{},[Ct]: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||{},[Ct]:r.relatedTask}}}),this._transport?.send(a,r).catch(l=>this._onerror(l))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Ct]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=_a(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Sa(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=_a(e);this._notificationHandlers.set(n,o=>{let s=Sa(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&Ei(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new z(M.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new z(M.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new z(M.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new z(M.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let l=pn.parse({method:"notifications/tasks/status",params:a});await this.notification(l),It(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new z(M.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(It(a.status))throw new z(M.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let l=await n.getTask(o,r);if(l){let p=pn.parse({method:"notifications/tasks/status",params:l});await this.notification(p),It(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var vn=j(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.regexpCode=oe.getEsmExportName=oe.getProperty=oe.safeStringify=oe.stringify=oe.strConcat=oe.addCodeArg=oe.str=oe._=oe.nil=oe._Code=oe.Name=oe.IDENTIFIER=oe._CodeOrName=void 0;var bn=class{};oe._CodeOrName=bn;oe.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Yt=class extends bn{constructor(e){if(super(),!oe.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}}};oe.Name=Yt;var Xe=class extends bn{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 Yt&&(r[n.str]=(r[n.str]||0)+1),r),{})}};oe._Code=Xe;oe.nil=new Xe("");function pp(t,...e){let r=[t[0]],n=0;for(;n<e.length;)xa(r,e[n]),r.push(t[++n]);return new Xe(r)}oe._=pp;var ka=new Xe("+");function fp(t,...e){let r=[wn(t[0])],n=0;for(;n<e.length;)r.push(ka),xa(r,e[n]),r.push(ka,wn(t[++n]));return sv(r),new Xe(r)}oe.str=fp;function xa(t,e){e instanceof Xe?t.push(...e._items):e instanceof Yt?t.push(e):t.push(cv(e))}oe.addCodeArg=xa;function sv(t){let e=1;for(;e<t.length-1;){if(t[e]===ka){let r=iv(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function iv(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Yt||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 Yt))return`"${t}${e.slice(1)}`}function av(t,e){return e.emptyStr()?t:t.emptyStr()?e:fp`${t}${e}`}oe.strConcat=av;function cv(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:wn(Array.isArray(t)?t.join(","):t)}function lv(t){return new Xe(wn(t))}oe.stringify=lv;function wn(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}oe.safeStringify=wn;function dv(t){return typeof t=="string"&&oe.IDENTIFIER.test(t)?new Xe(`.${t}`):pp`[${t}]`}oe.getProperty=dv;function uv(t){if(typeof t=="string"&&oe.IDENTIFIER.test(t))return new Xe(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}oe.getEsmExportName=uv;function pv(t){return new Xe(t.toString())}oe.regexpCode=pv});var Ra=j(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.ValueScope=De.ValueScopeName=De.Scope=De.varKinds=De.UsedValueState=void 0;var Le=vn(),Ta=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Zo;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Zo||(De.UsedValueState=Zo={}));De.varKinds={const:new Le.Name("const"),let:new Le.Name("let"),var:new Le.Name("var")};var Yo=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Le.Name?e:this.name(e)}name(e){return new Le.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}}};De.Scope=Yo;var Qo=class extends Le.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Le._)`.${new Le.Name(r)}[${n}]`}};De.ValueScopeName=Qo;var fv=(0,Le._)`\n`,Ea=class extends Yo{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?fv:Le.nil}}get(){return this._scope}name(e){return new Qo(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let u=a.get(i);if(u)return u}else a=this._values[s]=new Map;a.set(i,o);let l=this._scope[s]||(this._scope[s]=[]),p=l.length;return l[p]=r.ref,o.setValue(r,{property:s,itemIndex:p}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Le._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=Le.nil;for(let i in e){let a=e[i];if(!a)continue;let l=n[i]=n[i]||new Map;a.forEach(p=>{if(l.has(p))return;l.set(p,Zo.Started);let u=r(p);if(u){let d=this.opts.es5?De.varKinds.var:De.varKinds.const;s=(0,Le._)`${s}${d} ${p} = ${u};${this.opts._n}`}else if(u=o?.(p))s=(0,Le._)`${s}${u}${this.opts._n}`;else throw new Ta(p);l.set(p,Zo.Completed)})}return s}};De.ValueScope=Ea});var V=j(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.or=G.and=G.not=G.CodeGen=G.operators=G.varKinds=G.ValueScopeName=G.ValueScope=G.Scope=G.Name=G.regexpCode=G.stringify=G.getProperty=G.nil=G.strConcat=G.str=G._=void 0;var te=vn(),st=Ra(),Nt=vn();Object.defineProperty(G,"_",{enumerable:!0,get:function(){return Nt._}});Object.defineProperty(G,"str",{enumerable:!0,get:function(){return Nt.str}});Object.defineProperty(G,"strConcat",{enumerable:!0,get:function(){return Nt.strConcat}});Object.defineProperty(G,"nil",{enumerable:!0,get:function(){return Nt.nil}});Object.defineProperty(G,"getProperty",{enumerable:!0,get:function(){return Nt.getProperty}});Object.defineProperty(G,"stringify",{enumerable:!0,get:function(){return Nt.stringify}});Object.defineProperty(G,"regexpCode",{enumerable:!0,get:function(){return Nt.regexpCode}});Object.defineProperty(G,"Name",{enumerable:!0,get:function(){return Nt.Name}});var rs=Ra();Object.defineProperty(G,"Scope",{enumerable:!0,get:function(){return rs.Scope}});Object.defineProperty(G,"ValueScope",{enumerable:!0,get:function(){return rs.ValueScope}});Object.defineProperty(G,"ValueScopeName",{enumerable:!0,get:function(){return rs.ValueScopeName}});Object.defineProperty(G,"varKinds",{enumerable:!0,get:function(){return rs.varKinds}});G.operators={GT:new te._Code(">"),GTE:new te._Code(">="),LT:new te._Code("<"),LTE:new te._Code("<="),EQ:new te._Code("==="),NEQ:new te._Code("!=="),NOT:new te._Code("!"),OR:new te._Code("||"),AND:new te._Code("&&"),ADD:new te._Code("+")};var bt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Pa=class extends bt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?st.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=$r(this.rhs,e,r)),this}get names(){return this.rhs instanceof te._CodeOrName?this.rhs.names:{}}},Xo=class extends bt{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof te.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=$r(this.rhs,e,r),this}get names(){let e=this.lhs instanceof te.Name?{}:{...this.lhs.names};return ts(e,this.rhs)}},Aa=class extends Xo{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Ca=class extends bt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Ia=class extends bt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Oa=class extends bt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Na=class extends bt{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=$r(this.code,e,r),this}get names(){return this.code instanceof te._CodeOrName?this.code.names:{}}},_n=class extends bt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(hv(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>er(e,r.names),{})}},wt=class extends _n{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},ja=class extends _n{},Sr=class extends wt{};Sr.kind="else";var Qt=class t extends wt{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 Sr(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(hp(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=$r(this.condition,e,r),this}get names(){let e=super.names;return ts(e,this.condition),this.else&&er(e,this.else.names),e}};Qt.kind="if";var Xt=class extends wt{};Xt.kind="for";var za=class extends Xt{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=$r(this.iteration,e,r),this}get names(){return er(super.names,this.iteration.names)}},La=class extends Xt{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?st.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=ts(super.names,this.from);return ts(e,this.to)}},es=class extends Xt{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=$r(this.iterable,e,r),this}get names(){return er(super.names,this.iterable.names)}},Sn=class extends wt{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)}};Sn.kind="func";var $n=class extends _n{render(e){return"return "+super.render(e)}};$n.kind="return";var Da=class extends wt{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&er(e,this.catch.names),this.finally&&er(e,this.finally.names),e}},kn=class extends wt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};kn.kind="catch";var xn=class extends wt{render(e){return"finally"+super.render(e)}};xn.kind="finally";var Ma=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
884
|
+
`:""},this._extScope=e,this._scope=new st.Scope({parent:e}),this._nodes=[new ja]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new Pa(e,s,n)),s}const(e,r,n){return this._def(st.varKinds.const,e,r,n)}let(e,r,n){return this._def(st.varKinds.let,e,r,n)}var(e,r,n){return this._def(st.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Xo(e,r,n))}add(e,r){return this._leafNode(new Aa(e,G.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==te.nil&&this._leafNode(new Na(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,te.addCodeArg)(r,o));return r.push("}"),new te._Code(r)}if(e,r,n){if(this._blockNode(new Qt(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 Qt(e))}else(){return this._elseNode(new Sr)}endIf(){return this._endBlockNode(Qt,Sr)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new za(e),r)}forRange(e,r,n,o,s=this.opts.es5?st.varKinds.var:st.varKinds.let){let i=this._scope.toName(e);return this._for(new La(s,i,r,n),()=>o(i))}forOf(e,r,n,o=st.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof te.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,te._)`${i}.length`,a=>{this.var(s,(0,te._)`${i}[${a}]`),n(s)})}return this._for(new es("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?st.varKinds.var:st.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,te._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new es("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Xt)}label(e){return this._leafNode(new Ca(e))}break(e){return this._leafNode(new Ia(e))}return(e){let r=new $n;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode($n)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Da;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new kn(s),r(s)}return n&&(this._currNode=o.finally=new xn,this.code(n)),this._endBlockNode(kn,xn)}throw(e){return this._leafNode(new Oa(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=te.nil,n,o){return this._blockNode(new Sn(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Sn)}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 Qt))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}};G.CodeGen=Ma;function er(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function ts(t,e){return e instanceof te._CodeOrName?er(t,e.names):t}function $r(t,e,r){if(t instanceof te.Name)return n(t);if(!o(t))return t;return new te._Code(t._items.reduce((s,i)=>(i instanceof te.Name&&(i=n(i)),i instanceof te._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof te._Code&&s._items.some(i=>i instanceof te.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function hv(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function hp(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,te._)`!${qa(t)}`}G.not=hp;var mv=mp(G.operators.AND);function gv(...t){return t.reduce(mv)}G.and=gv;var yv=mp(G.operators.OR);function bv(...t){return t.reduce(yv)}G.or=bv;function mp(t){return(e,r)=>e===te.nil?r:r===te.nil?e:(0,te._)`${qa(e)} ${t} ${qa(r)}`}function qa(t){return t instanceof te.Name?t:(0,te._)`(${t})`}});var re=j(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.checkStrictMode=J.getErrorPath=J.Type=J.useFunc=J.setEvaluated=J.evaluatedPropsToName=J.mergeEvaluated=J.eachItem=J.unescapeJsonPointer=J.escapeJsonPointer=J.escapeFragment=J.unescapeFragment=J.schemaRefOrVal=J.schemaHasRulesButRef=J.schemaHasRules=J.checkUnknownRules=J.alwaysValidSchema=J.toHash=void 0;var ce=V(),wv=vn();function vv(t){let e={};for(let r of t)e[r]=!0;return e}J.toHash=vv;function _v(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(bp(t,e),!wp(e,t.self.RULES.all))}J.alwaysValidSchema=_v;function bp(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||Sp(t,`unknown keyword: "${s}"`)}J.checkUnknownRules=bp;function wp(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}J.schemaHasRules=wp;function Sv(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}J.schemaHasRulesButRef=Sv;function $v({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ce._)`${r}`}return(0,ce._)`${t}${e}${(0,ce.getProperty)(n)}`}J.schemaRefOrVal=$v;function kv(t){return vp(decodeURIComponent(t))}J.unescapeFragment=kv;function xv(t){return encodeURIComponent(Ba(t))}J.escapeFragment=xv;function Ba(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}J.escapeJsonPointer=Ba;function vp(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}J.unescapeJsonPointer=vp;function Tv(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}J.eachItem=Tv;function gp({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let l=i===void 0?s:i instanceof ce.Name?(s instanceof ce.Name?t(o,s,i):e(o,s,i),i):s instanceof ce.Name?(e(o,i,s),s):r(s,i);return a===ce.Name&&!(l instanceof ce.Name)?n(o,l):l}}J.mergeEvaluated={props:gp({mergeNames:(t,e,r)=>t.if((0,ce._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,ce._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,ce._)`${r} || {}`).code((0,ce._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,ce._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,ce._)`${r} || {}`),Fa(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:_p}),items:gp({mergeNames:(t,e,r)=>t.if((0,ce._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,ce._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,ce._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,ce._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function _p(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,ce._)`{}`);return e!==void 0&&Fa(t,r,e),r}J.evaluatedPropsToName=_p;function Fa(t,e,r){Object.keys(r).forEach(n=>t.assign((0,ce._)`${e}${(0,ce.getProperty)(n)}`,!0))}J.setEvaluated=Fa;var yp={};function Ev(t,e){return t.scopeValue("func",{ref:e,code:yp[e.code]||(yp[e.code]=new wv._Code(e.code))})}J.useFunc=Ev;var Ua;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Ua||(J.Type=Ua={}));function Rv(t,e,r){if(t instanceof ce.Name){let n=e===Ua.Num;return r?n?(0,ce._)`"[" + ${t} + "]"`:(0,ce._)`"['" + ${t} + "']"`:n?(0,ce._)`"/" + ${t}`:(0,ce._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ce.getProperty)(t).toString():"/"+Ba(t)}J.getErrorPath=Rv;function Sp(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}J.checkStrictMode=Sp});var vt=j(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});var Re=V(),Pv={data:new Re.Name("data"),valCxt:new Re.Name("valCxt"),instancePath:new Re.Name("instancePath"),parentData:new Re.Name("parentData"),parentDataProperty:new Re.Name("parentDataProperty"),rootData:new Re.Name("rootData"),dynamicAnchors:new Re.Name("dynamicAnchors"),vErrors:new Re.Name("vErrors"),errors:new Re.Name("errors"),this:new Re.Name("this"),self:new Re.Name("self"),scope:new Re.Name("scope"),json:new Re.Name("json"),jsonPos:new Re.Name("jsonPos"),jsonLen:new Re.Name("jsonLen"),jsonPart:new Re.Name("jsonPart")};Ha.default=Pv});var Tn=j(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.extendErrors=Pe.resetErrorsCount=Pe.reportExtraError=Pe.reportError=Pe.keyword$DataError=Pe.keywordError=void 0;var ne=V(),ns=re(),Oe=vt();Pe.keywordError={message:({keyword:t})=>(0,ne.str)`must pass "${t}" keyword validation`};Pe.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ne.str)`"${t}" keyword must be ${e} ($data)`:(0,ne.str)`"${t}" keyword is invalid ($data)`};function Av(t,e=Pe.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,l=xp(t,e,r);n??(i||a)?$p(s,l):kp(o,(0,ne._)`[${l}]`)}Pe.reportError=Av;function Cv(t,e=Pe.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=xp(t,e,r);$p(o,a),s||i||kp(n,Oe.default.vErrors)}Pe.reportExtraError=Cv;function Iv(t,e){t.assign(Oe.default.errors,e),t.if((0,ne._)`${Oe.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ne._)`${Oe.default.vErrors}.length`,e),()=>t.assign(Oe.default.vErrors,null)))}Pe.resetErrorsCount=Iv;function Ov({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,Oe.default.errors,a=>{t.const(i,(0,ne._)`${Oe.default.vErrors}[${a}]`),t.if((0,ne._)`${i}.instancePath === undefined`,()=>t.assign((0,ne._)`${i}.instancePath`,(0,ne.strConcat)(Oe.default.instancePath,s.errorPath))),t.assign((0,ne._)`${i}.schemaPath`,(0,ne.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,ne._)`${i}.schema`,r),t.assign((0,ne._)`${i}.data`,n))})}Pe.extendErrors=Ov;function $p(t,e){let r=t.const("err",e);t.if((0,ne._)`${Oe.default.vErrors} === null`,()=>t.assign(Oe.default.vErrors,(0,ne._)`[${r}]`),(0,ne._)`${Oe.default.vErrors}.push(${r})`),t.code((0,ne._)`${Oe.default.errors}++`)}function kp(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,ne._)`new ${t.ValidationError}(${e})`):(r.assign((0,ne._)`${n}.errors`,e),r.return(!1))}var tr={keyword:new ne.Name("keyword"),schemaPath:new ne.Name("schemaPath"),params:new ne.Name("params"),propertyName:new ne.Name("propertyName"),message:new ne.Name("message"),schema:new ne.Name("schema"),parentSchema:new ne.Name("parentSchema")};function xp(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,ne._)`{}`:Nv(t,e,r)}function Nv(t,e,r={}){let{gen:n,it:o}=t,s=[jv(o,r),zv(t,r)];return Lv(t,e,s),n.object(...s)}function jv({errorPath:t},{instancePath:e}){let r=e?(0,ne.str)`${t}${(0,ns.getErrorPath)(e,ns.Type.Str)}`:t;return[Oe.default.instancePath,(0,ne.strConcat)(Oe.default.instancePath,r)]}function zv({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,ne.str)`${e}/${t}`;return r&&(o=(0,ne.str)`${o}${(0,ns.getErrorPath)(r,ns.Type.Str)}`),[tr.schemaPath,o]}function Lv(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:l,propertyName:p,topSchemaRef:u,schemaPath:d}=a;n.push([tr.keyword,o],[tr.params,typeof e=="function"?e(t):e||(0,ne._)`{}`]),l.messages&&n.push([tr.message,typeof r=="function"?r(t):r]),l.verbose&&n.push([tr.schema,i],[tr.parentSchema,(0,ne._)`${u}${d}`],[Oe.default.data,s]),p&&n.push([tr.propertyName,p])}});var Ep=j(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.boolOrEmptySchema=kr.topBoolOrEmptySchema=void 0;var Dv=Tn(),Mv=V(),qv=vt(),Uv={message:"boolean schema is false"};function Bv(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Tp(t,!1):typeof r=="object"&&r.$async===!0?e.return(qv.default.data):(e.assign((0,Mv._)`${n}.errors`,null),e.return(!0))}kr.topBoolOrEmptySchema=Bv;function Fv(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Tp(t)):r.var(e,!0)}kr.boolOrEmptySchema=Fv;function Tp(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,Dv.reportError)(o,Uv,void 0,e)}});var Ka=j(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.getRules=xr.isJSONType=void 0;var Hv=["string","number","integer","boolean","null","object","array"],Kv=new Set(Hv);function Vv(t){return typeof t=="string"&&Kv.has(t)}xr.isJSONType=Vv;function Gv(){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:{}}}xr.getRules=Gv});var Va=j(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.shouldUseRule=jt.shouldUseGroup=jt.schemaHasRulesForType=void 0;function Wv({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Rp(t,n)}jt.schemaHasRulesForType=Wv;function Rp(t,e){return e.rules.some(r=>Pp(t,r))}jt.shouldUseGroup=Rp;function Pp(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))}jt.shouldUseRule=Pp});var En=j(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.reportTypeError=Ae.checkDataTypes=Ae.checkDataType=Ae.coerceAndCheckDataType=Ae.getJSONTypes=Ae.getSchemaTypes=Ae.DataType=void 0;var Jv=Ka(),Zv=Va(),Yv=Tn(),K=V(),Ap=re(),Tr;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Tr||(Ae.DataType=Tr={}));function Qv(t){let e=Cp(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}Ae.getSchemaTypes=Qv;function Cp(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(Jv.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ae.getJSONTypes=Cp;function Xv(t,e){let{gen:r,data:n,opts:o}=t,s=e_(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,Zv.schemaHasRulesForType)(t,e[0]));if(i){let a=Wa(e,n,o.strictNumbers,Tr.Wrong);r.if(a,()=>{s.length?t_(t,e,s):Ja(t)})}return i}Ae.coerceAndCheckDataType=Xv;var Ip=new Set(["string","number","integer","boolean","null"]);function e_(t,e){return e?t.filter(r=>Ip.has(r)||e==="array"&&r==="array"):[]}function t_(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,K._)`typeof ${o}`),a=n.let("coerced",(0,K._)`undefined`);s.coerceTypes==="array"&&n.if((0,K._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,K._)`${o}[0]`).assign(i,(0,K._)`typeof ${o}`).if(Wa(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,K._)`${a} !== undefined`);for(let p of r)(Ip.has(p)||p==="array"&&s.coerceTypes==="array")&&l(p);n.else(),Ja(t),n.endIf(),n.if((0,K._)`${a} !== undefined`,()=>{n.assign(o,a),r_(t,a)});function l(p){switch(p){case"string":n.elseIf((0,K._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,K._)`"" + ${o}`).elseIf((0,K._)`${o} === null`).assign(a,(0,K._)`""`);return;case"number":n.elseIf((0,K._)`${i} == "boolean" || ${o} === null
|
|
885
|
+
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,K._)`+${o}`);return;case"integer":n.elseIf((0,K._)`${i} === "boolean" || ${o} === null
|
|
886
|
+
|| (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,K._)`+${o}`);return;case"boolean":n.elseIf((0,K._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,K._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,K._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,K._)`${i} === "string" || ${i} === "number"
|
|
887
|
+
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,K._)`[${o}]`)}}}function r_({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,K._)`${e} !== undefined`,()=>t.assign((0,K._)`${e}[${r}]`,n))}function Ga(t,e,r,n=Tr.Correct){let o=n===Tr.Correct?K.operators.EQ:K.operators.NEQ,s;switch(t){case"null":return(0,K._)`${e} ${o} null`;case"array":s=(0,K._)`Array.isArray(${e})`;break;case"object":s=(0,K._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,K._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,K._)`typeof ${e} ${o} ${t}`}return n===Tr.Correct?s:(0,K.not)(s);function i(a=K.nil){return(0,K.and)((0,K._)`typeof ${e} == "number"`,a,r?(0,K._)`isFinite(${e})`:K.nil)}}Ae.checkDataType=Ga;function Wa(t,e,r,n){if(t.length===1)return Ga(t[0],e,r,n);let o,s=(0,Ap.toHash)(t);if(s.array&&s.object){let i=(0,K._)`typeof ${e} != "object"`;o=s.null?i:(0,K._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=K.nil;s.number&&delete s.integer;for(let i in s)o=(0,K.and)(o,Ga(i,e,r,n));return o}Ae.checkDataTypes=Wa;var n_={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,K._)`{type: ${t}}`:(0,K._)`{type: ${e}}`};function Ja(t){let e=o_(t);(0,Yv.reportError)(e,n_)}Ae.reportTypeError=Ja;function o_(t){let{gen:e,data:r,schema:n}=t,o=(0,Ap.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Np=j(os=>{"use strict";Object.defineProperty(os,"__esModule",{value:!0});os.assignDefaults=void 0;var Er=V(),s_=re();function i_(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Op(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Op(t,s,o.default))}os.assignDefaults=i_;function Op(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Er._)`${s}${(0,Er.getProperty)(e)}`;if(o){(0,s_.checkStrictMode)(t,`default is ignored for: ${a}`);return}let l=(0,Er._)`${a} === undefined`;i.useDefaults==="empty"&&(l=(0,Er._)`${l} || ${a} === null || ${a} === ""`),n.if(l,(0,Er._)`${a} = ${(0,Er.stringify)(r)}`)}});var et=j(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.validateUnion=ie.validateArray=ie.usePattern=ie.callValidateCode=ie.schemaProperties=ie.allSchemaProperties=ie.noPropertyInData=ie.propertyInData=ie.isOwnProperty=ie.hasPropFunc=ie.reportMissingProp=ie.checkMissingProp=ie.checkReportMissingProp=void 0;var de=V(),Za=re(),zt=vt(),a_=re();function c_(t,e){let{gen:r,data:n,it:o}=t;r.if(Qa(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,de._)`${e}`},!0),t.error()})}ie.checkReportMissingProp=c_;function l_({gen:t,data:e,it:{opts:r}},n,o){return(0,de.or)(...n.map(s=>(0,de.and)(Qa(t,e,s,r.ownProperties),(0,de._)`${o} = ${s}`)))}ie.checkMissingProp=l_;function d_(t,e){t.setParams({missingProperty:e},!0),t.error()}ie.reportMissingProp=d_;function jp(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,de._)`Object.prototype.hasOwnProperty`})}ie.hasPropFunc=jp;function Ya(t,e,r){return(0,de._)`${jp(t)}.call(${e}, ${r})`}ie.isOwnProperty=Ya;function u_(t,e,r,n){let o=(0,de._)`${e}${(0,de.getProperty)(r)} !== undefined`;return n?(0,de._)`${o} && ${Ya(t,e,r)}`:o}ie.propertyInData=u_;function Qa(t,e,r,n){let o=(0,de._)`${e}${(0,de.getProperty)(r)} === undefined`;return n?(0,de.or)(o,(0,de.not)(Ya(t,e,r))):o}ie.noPropertyInData=Qa;function zp(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ie.allSchemaProperties=zp;function p_(t,e){return zp(e).filter(r=>!(0,Za.alwaysValidSchema)(t,e[r]))}ie.schemaProperties=p_;function f_({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,l,p){let u=p?(0,de._)`${t}, ${e}, ${n}${o}`:e,d=[[zt.default.instancePath,(0,de.strConcat)(zt.default.instancePath,s)],[zt.default.parentData,i.parentData],[zt.default.parentDataProperty,i.parentDataProperty],[zt.default.rootData,zt.default.rootData]];i.opts.dynamicRef&&d.push([zt.default.dynamicAnchors,zt.default.dynamicAnchors]);let f=(0,de._)`${u}, ${r.object(...d)}`;return l!==de.nil?(0,de._)`${a}.call(${l}, ${f})`:(0,de._)`${a}(${f})`}ie.callValidateCode=f_;var h_=(0,de._)`new RegExp`;function m_({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,de._)`${o.code==="new RegExp"?h_:(0,a_.useFunc)(t,o)}(${r}, ${n})`})}ie.usePattern=m_;function g_(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let l=e.const("len",(0,de._)`${r}.length`);e.forRange("i",0,l,p=>{t.subschema({keyword:n,dataProp:p,dataPropType:Za.Type.Num},s),e.if((0,de.not)(s),a)})}}ie.validateArray=g_;function y_(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0,Za.alwaysValidSchema)(o,l))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((l,p)=>{let u=t.subschema({keyword:n,schemaProp:p,compositeRule:!0},a);e.assign(i,(0,de._)`${i} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,de.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}ie.validateUnion=y_});var Mp=j(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.validateKeywordUsage=pt.validSchemaType=pt.funcKeywordCode=pt.macroKeywordCode=void 0;var Ne=V(),rr=vt(),b_=et(),w_=Tn();function v_(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),l=Dp(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let p=r.name("valid");t.subschema({schema:a,schemaPath:Ne.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},p),t.pass(p,()=>t.error(!0))}pt.macroKeywordCode=v_;function __(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:l}=t;$_(l,e);let p=!a&&e.compile?e.compile.call(l.self,s,i,l):e.validate,u=Dp(n,o,p),d=n.let("valid");t.block$data(d,f),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function f(){if(e.errors===!1)v(),e.modifying&&Lp(t),x(()=>t.error());else{let P=e.async?g():b();e.modifying&&Lp(t),x(()=>S_(t,P))}}function g(){let P=n.let("ruleErrs",null);return n.try(()=>v((0,Ne._)`await `),N=>n.assign(d,!1).if((0,Ne._)`${N} instanceof ${l.ValidationError}`,()=>n.assign(P,(0,Ne._)`${N}.errors`),()=>n.throw(N))),P}function b(){let P=(0,Ne._)`${u}.errors`;return n.assign(P,null),v(Ne.nil),P}function v(P=e.async?(0,Ne._)`await `:Ne.nil){let N=l.opts.passContext?rr.default.this:rr.default.self,D=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Ne._)`${P}${(0,b_.callValidateCode)(t,u,N,D)}`,e.modifying)}function x(P){var N;n.if((0,Ne.not)((N=e.valid)!==null&&N!==void 0?N:d),P)}}pt.funcKeywordCode=__;function Lp(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Ne._)`${n.parentData}[${n.parentDataProperty}]`))}function S_(t,e){let{gen:r}=t;r.if((0,Ne._)`Array.isArray(${e})`,()=>{r.assign(rr.default.vErrors,(0,Ne._)`${rr.default.vErrors} === null ? ${e} : ${rr.default.vErrors}.concat(${e})`).assign(rr.default.errors,(0,Ne._)`${rr.default.vErrors}.length`),(0,w_.extendErrors)(t)},()=>t.error())}function $_({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Dp(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,Ne.stringify)(r)})}function k_(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")}pt.validSchemaType=k_;function x_({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let l=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}pt.validateKeywordUsage=x_});var Up=j(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.extendSubschemaMode=Lt.extendSubschemaData=Lt.getSubschema=void 0;var ft=V(),qp=re();function T_(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,ft._)`${t.schemaPath}${(0,ft.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,ft._)`${t.schemaPath}${(0,ft.getProperty)(e)}${(0,ft.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,qp.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Lt.getSubschema=T_;function E_(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:p,dataPathArr:u,opts:d}=e,f=a.let("data",(0,ft._)`${e.data}${(0,ft.getProperty)(r)}`,!0);l(f),t.errorPath=(0,ft.str)`${p}${(0,qp.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,ft._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(o!==void 0){let p=o instanceof ft.Name?o:a.let("data",o,!0);l(p),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function l(p){t.data=p,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,p]}}Lt.extendSubschemaData=E_;function R_(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}Lt.extendSubschemaMode=R_});var Xa=j((RC,Bp)=>{"use strict";Bp.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var Hp=j((PC,Fp)=>{"use strict";var Dt=Fp.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};ss(e,n,o,t,"",t)};Dt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Dt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Dt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Dt.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 ss(t,e,r,n,o,s,i,a,l,p){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,l,p);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in Dt.arrayKeywords)for(var f=0;f<d.length;f++)ss(t,e,r,d[f],o+"/"+u+"/"+f,s,o,u,n,f)}else if(u in Dt.propsKeywords){if(d&&typeof d=="object")for(var g in d)ss(t,e,r,d[g],o+"/"+u+"/"+P_(g),s,o,u,n,g)}else(u in Dt.keywords||t.allKeys&&!(u in Dt.skipKeywords))&&ss(t,e,r,d,o+"/"+u,s,o,u,n)}r(n,o,s,i,a,l,p)}}function P_(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Rn=j(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.getSchemaRefs=Me.resolveUrl=Me.normalizeId=Me._getFullPath=Me.getFullPath=Me.inlineRef=void 0;var A_=re(),C_=Xa(),I_=Hp(),O_=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function N_(t,e=!0){return typeof t=="boolean"?!0:e===!0?!ec(t):e?Kp(t)<=e:!1}Me.inlineRef=N_;var j_=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function ec(t){for(let e in t){if(j_.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(ec)||typeof r=="object"&&ec(r))return!0}return!1}function Kp(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!O_.has(r)&&(typeof t[r]=="object"&&(0,A_.eachItem)(t[r],n=>e+=Kp(n)),e===1/0))return 1/0}return e}function Vp(t,e="",r){r!==!1&&(e=Rr(e));let n=t.parse(e);return Gp(t,n)}Me.getFullPath=Vp;function Gp(t,e){return t.serialize(e).split("#")[0]+"#"}Me._getFullPath=Gp;var z_=/#\/?$/;function Rr(t){return t?t.replace(z_,""):""}Me.normalizeId=Rr;function L_(t,e,r){return r=Rr(r),t.resolve(e,r)}Me.resolveUrl=L_;var D_=/^[a-z_][-a-z0-9._]*$/i;function M_(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Rr(t[r]||e),s={"":o},i=Vp(n,o,!1),a={},l=new Set;return I_(t,{allKeys:!0},(d,f,g,b)=>{if(b===void 0)return;let v=i+f,x=s[b];typeof d[r]=="string"&&(x=P.call(this,d[r])),N.call(this,d.$anchor),N.call(this,d.$dynamicAnchor),s[f]=x;function P(D){let Q=this.opts.uriResolver.resolve;if(D=Rr(x?Q(x,D):D),l.has(D))throw u(D);l.add(D);let U=this.refs[D];return typeof U=="string"&&(U=this.refs[U]),typeof U=="object"?p(d,U.schema,D):D!==Rr(v)&&(D[0]==="#"?(p(d,a[D],D),a[D]=d):this.refs[D]=v),D}function N(D){if(typeof D=="string"){if(!D_.test(D))throw new Error(`invalid anchor "${D}"`);P.call(this,`#${D}`)}}}),a;function p(d,f,g){if(f!==void 0&&!C_(d,f))throw u(g)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Me.getSchemaRefs=M_});var Cn=j(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.getData=Mt.KeywordCxt=Mt.validateFunctionCode=void 0;var Qp=Ep(),Wp=En(),rc=Va(),is=En(),q_=Np(),An=Mp(),tc=Up(),L=V(),B=vt(),U_=Rn(),_t=re(),Pn=Tn();function B_(t){if(tf(t)&&(rf(t),ef(t))){K_(t);return}Xp(t,()=>(0,Qp.topBoolOrEmptySchema)(t))}Mt.validateFunctionCode=B_;function Xp({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,L._)`${B.default.data}, ${B.default.valCxt}`,n.$async,()=>{t.code((0,L._)`"use strict"; ${Jp(r,o)}`),H_(t,o),t.code(s)}):t.func(e,(0,L._)`${B.default.data}, ${F_(o)}`,n.$async,()=>t.code(Jp(r,o)).code(s))}function F_(t){return(0,L._)`{${B.default.instancePath}="", ${B.default.parentData}, ${B.default.parentDataProperty}, ${B.default.rootData}=${B.default.data}${t.dynamicRef?(0,L._)`, ${B.default.dynamicAnchors}={}`:L.nil}}={}`}function H_(t,e){t.if(B.default.valCxt,()=>{t.var(B.default.instancePath,(0,L._)`${B.default.valCxt}.${B.default.instancePath}`),t.var(B.default.parentData,(0,L._)`${B.default.valCxt}.${B.default.parentData}`),t.var(B.default.parentDataProperty,(0,L._)`${B.default.valCxt}.${B.default.parentDataProperty}`),t.var(B.default.rootData,(0,L._)`${B.default.valCxt}.${B.default.rootData}`),e.dynamicRef&&t.var(B.default.dynamicAnchors,(0,L._)`${B.default.valCxt}.${B.default.dynamicAnchors}`)},()=>{t.var(B.default.instancePath,(0,L._)`""`),t.var(B.default.parentData,(0,L._)`undefined`),t.var(B.default.parentDataProperty,(0,L._)`undefined`),t.var(B.default.rootData,B.default.data),e.dynamicRef&&t.var(B.default.dynamicAnchors,(0,L._)`{}`)})}function K_(t){let{schema:e,opts:r,gen:n}=t;Xp(t,()=>{r.$comment&&e.$comment&&of(t),Z_(t),n.let(B.default.vErrors,null),n.let(B.default.errors,0),r.unevaluated&&V_(t),nf(t),X_(t)})}function V_(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,L._)`${r}.evaluated`),e.if((0,L._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,L._)`${t.evaluated}.props`,(0,L._)`undefined`)),e.if((0,L._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,L._)`${t.evaluated}.items`,(0,L._)`undefined`))}function Jp(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,L._)`/*# sourceURL=${r} */`:L.nil}function G_(t,e){if(tf(t)&&(rf(t),ef(t))){W_(t,e);return}(0,Qp.boolOrEmptySchema)(t,e)}function ef({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 tf(t){return typeof t.schema!="boolean"}function W_(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&of(t),Y_(t),Q_(t);let s=n.const("_errs",B.default.errors);nf(t,s),n.var(e,(0,L._)`${s} === ${B.default.errors}`)}function rf(t){(0,_t.checkUnknownRules)(t),J_(t)}function nf(t,e){if(t.opts.jtd)return Zp(t,[],!1,e);let r=(0,Wp.getSchemaTypes)(t.schema),n=(0,Wp.coerceAndCheckDataType)(t,r);Zp(t,r,!n,e)}function J_(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,_t.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function Z_(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,_t.checkStrictMode)(t,"default is ignored in the schema root")}function Y_(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,U_.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Q_(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function of({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,L._)`${B.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,L.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,L._)`${B.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function X_(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,L._)`${B.default.errors} === 0`,()=>e.return(B.default.data),()=>e.throw((0,L._)`new ${o}(${B.default.vErrors})`)):(e.assign((0,L._)`${n}.errors`,B.default.vErrors),s.unevaluated&&eS(t),e.return((0,L._)`${B.default.errors} === 0`))}function eS({gen:t,evaluated:e,props:r,items:n}){r instanceof L.Name&&t.assign((0,L._)`${e}.props`,r),n instanceof L.Name&&t.assign((0,L._)`${e}.items`,n)}function Zp(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:l,self:p}=t,{RULES:u}=p;if(s.$ref&&(l.ignoreKeywordsWithRef||!(0,_t.schemaHasRulesButRef)(s,u))){o.block(()=>af(t,"$ref",u.all.$ref.definition));return}l.jtd||tS(t,e),o.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,rc.shouldUseGroup)(s,f)&&(f.type?(o.if((0,is.checkDataType)(f.type,i,l.strictNumbers)),Yp(t,f),e.length===1&&e[0]===f.type&&r&&(o.else(),(0,is.reportTypeError)(t)),o.endIf()):Yp(t,f),a||o.if((0,L._)`${B.default.errors} === ${n||0}`))}}function Yp(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,q_.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,rc.shouldUseRule)(n,s)&&af(t,s.keyword,s.definition,e.type)})}function tS(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(rS(t,e),t.opts.allowUnionTypes||nS(t,e),oS(t,t.dataTypes))}function rS(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{sf(t.dataTypes,r)||nc(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),iS(t,e)}}function nS(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&nc(t,"use allowUnionTypes to allow union type keyword")}function oS(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,rc.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>sS(e,i))&&nc(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function sS(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function sf(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function iS(t,e){let r=[];for(let n of t.dataTypes)sf(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function nc(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,_t.checkStrictMode)(t,e,t.opts.strictTypes)}var as=class{constructor(e,r,n){if((0,An.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,_t.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",cf(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,An.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",B.default.errors))}result(e,r,n){this.failResult((0,L.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,L.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,L._)`${r} !== undefined && (${(0,L.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?Pn.reportExtraError:Pn.reportError)(this,this.def.error,r)}$dataError(){(0,Pn.reportError)(this,this.def.$dataError||Pn.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Pn.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=L.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=L.nil,r=L.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,L.or)((0,L._)`${o} === undefined`,r)),e!==L.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==L.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,L.or)(i(),a());function i(){if(n.length){if(!(r instanceof L.Name))throw new Error("ajv implementation error");let l=Array.isArray(n)?n:[n];return(0,L._)`${(0,is.checkDataTypes)(l,r,s.opts.strictNumbers,is.DataType.Wrong)}`}return L.nil}function a(){if(o.validateSchema){let l=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,L._)`!${l}(${r})`}return L.nil}}subschema(e,r){let n=(0,tc.getSubschema)(this.it,e);(0,tc.extendSubschemaData)(n,this.it,e),(0,tc.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return G_(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=_t.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=_t.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,L.Name)),!0}};Mt.KeywordCxt=as;function af(t,e,r,n){let o=new as(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,An.funcKeywordCode)(o,r):"macro"in r?(0,An.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,An.funcKeywordCode)(o,r)}var aS=/^\/(?:[^~]|~0|~1)*$/,cS=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function cf(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return B.default.rootData;if(t[0]==="/"){if(!aS.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=B.default.rootData}else{let p=cS.exec(t);if(!p)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+p[1];if(o=p[2],o==="#"){if(u>=e)throw new Error(l("property/index",u));return n[e-u]}if(u>e)throw new Error(l("data",u));if(s=r[e-u],!o)return s}let i=s,a=o.split("/");for(let p of a)p&&(s=(0,L._)`${s}${(0,L.getProperty)((0,_t.unescapeJsonPointer)(p))}`,i=(0,L._)`${i} && ${s}`);return i;function l(p,u){return`Cannot access ${p} ${u} levels up, current level is ${e}`}}Mt.getData=cf});var cs=j(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});var oc=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};sc.default=oc});var In=j(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});var ic=Rn(),ac=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,ic.resolveUrl)(e,r,n),this.missingSchema=(0,ic.normalizeId)((0,ic.getFullPath)(e,this.missingRef))}};cc.default=ac});var ds=j(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.resolveSchema=tt.getCompilingSchema=tt.resolveRef=tt.compileSchema=tt.SchemaEnv=void 0;var it=V(),lS=cs(),nr=vt(),at=Rn(),lf=re(),dS=Cn(),Pr=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,at.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};tt.SchemaEnv=Pr;function dc(t){let e=df.call(this,t);if(e)return e;let r=(0,at.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new it.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:lS.default,code:(0,it._)`require("ajv/dist/runtime/validation_error").default`}));let l=i.scopeName("validate");t.validateName=l;let p={gen:i,allErrors:this.opts.allErrors,data:nr.default.data,parentData:nr.default.parentData,parentDataProperty:nr.default.parentDataProperty,dataNames:[nr.default.data],dataPathArr:[it.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,it.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:it.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,it._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,dS.validateFunctionCode)(p),i.optimize(this.opts.code.optimize);let d=i.toString();u=`${i.scopeRefs(nr.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let g=new Function(`${nr.default.self}`,`${nr.default.scope}`,u)(this,this.scope.get());if(this.scope.value(l,{ref:g}),g.errors=null,g.schema=t.schema,g.schemaEnv=t,t.$async&&(g.$async=!0),this.opts.code.source===!0&&(g.source={validateName:l,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:b,items:v}=p;g.evaluated={props:b instanceof it.Name?void 0:b,items:v instanceof it.Name?void 0:v,dynamicProps:b instanceof it.Name,dynamicItems:v instanceof it.Name},g.source&&(g.source.evaluated=(0,it.stringify)(g.evaluated))}return t.validate=g,t}catch(d){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(t)}}tt.compileSchema=dc;function uS(t,e,r){var n;r=(0,at.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=hS.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new Pr({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=pS.call(this,s)}tt.resolveRef=uS;function pS(t){return(0,at.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:dc.call(this,t)}function df(t){for(let e of this._compilations)if(fS(e,t))return e}tt.getCompilingSchema=df;function fS(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function hS(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||ls.call(this,t,e)}function ls(t,e){let r=this.opts.uriResolver.parse(e),n=(0,at._getFullPath)(this.opts.uriResolver,r),o=(0,at.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return lc.call(this,r,t);let s=(0,at.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=ls.call(this,t,i);return typeof a?.schema!="object"?void 0:lc.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||dc.call(this,i),s===(0,at.normalizeId)(e)){let{schema:a}=i,{schemaId:l}=this.opts,p=a[l];return p&&(o=(0,at.resolveUrl)(this.opts.uriResolver,o,p)),new Pr({schema:a,schemaId:l,root:t,baseId:o})}return lc.call(this,r,i)}}tt.resolveSchema=ls;var mS=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function lc(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let l=r[(0,lf.unescapeFragment)(a)];if(l===void 0)return;r=l;let p=typeof r=="object"&&r[this.opts.schemaId];!mS.has(a)&&p&&(e=(0,at.resolveUrl)(this.opts.uriResolver,e,p))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,lf.schemaHasRulesButRef)(r,this.RULES)){let a=(0,at.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=ls.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Pr({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var uf=j((jC,gS)=>{gS.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 fc=j((zC,yf)=>{"use strict";var yS=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),ff=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),uc=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),hf=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),bS=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function pc(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 wS=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function pf(t){return t.length=0,!0}function vS(t,e,r){if(t.length){let n=pc(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function _S(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=vS;for(let l=0;l<t.length;l++){let p=t[l];if(!(p==="["||p==="]"))if(p===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}l>0&&t[l-1]===":"&&(s=!0),n.push(":");continue}else if(p==="%"){if(!a(o,n,r))break;a=pf}else{o.push(p);continue}}return o.length&&(a===pf?r.zone=o.join(""):i?n.push(o.join("")):n.push(pc(o))),r.address=n.join(""),r}function mf(t){if(SS(t,":")<2)return{host:t,isIPV6:!1};let e=_S(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 SS(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function $S(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}var kS={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},xS=/[@/?#:]/g,TS=/[@/?#]/g;function gf(t,e){let r=e?TS:xS;return r.lastIndex=0,t.replace(r,n=>kS[n])}function ES(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(uc(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&hf(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function RS(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(uc(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&hf(s)?e+=s:e+="%"+o,r+=2;continue}}bS(t[r])?e+=t[r]:e+=escape(t[r])}return e}function PS(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(uc(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function AS(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!ff(r)){let n=mf(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=gf(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}yf.exports={nonSimpleDomain:wS,recomposeAuthority:AS,reescapeHostDelimiters:gf,normalizePercentEncoding:ES,normalizePathEncoding:RS,escapePreservingEscapes:PS,removeDotSegments:$S,isIPv4:ff,isUUID:yS,normalizeIPv6:mf,stringArrayToHexStripped:pc}});var Sf=j((LC,_f)=>{"use strict";var{isUUID:CS}=fc(),IS=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,OS=["http","https","ws","wss","urn","urn:uuid"];function NS(t){return OS.indexOf(t)!==-1}function hc(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 bf(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function wf(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 jS(t){return t.secure=hc(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function zS(t){if((t.port===(hc(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 LS(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(IS);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=mc(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function DS(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=mc(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function MS(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!CS(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function qS(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var vf={scheme:"http",domainHost:!0,parse:bf,serialize:wf},US={scheme:"https",domainHost:vf.domainHost,parse:bf,serialize:wf},us={scheme:"ws",domainHost:!0,parse:jS,serialize:zS},BS={scheme:"wss",domainHost:us.domainHost,parse:us.parse,serialize:us.serialize},FS={scheme:"urn",parse:LS,serialize:DS,skipNormalize:!0},HS={scheme:"urn:uuid",parse:MS,serialize:qS,skipNormalize:!0},ps={http:vf,https:US,ws:us,wss:BS,urn:FS,"urn:uuid":HS};Object.setPrototypeOf(ps,null);function mc(t){return t&&(ps[t]||ps[t.toLowerCase()])||void 0}_f.exports={wsIsSecure:hc,SCHEMES:ps,isValidSchemeName:NS,getSchemeHandler:mc}});var Rf=j((DC,fs)=>{"use strict";var{normalizeIPv6:KS,removeDotSegments:On,recomposeAuthority:VS,normalizePercentEncoding:GS,normalizePathEncoding:WS,escapePreservingEscapes:JS,reescapeHostDelimiters:ZS,isIPv4:YS,nonSimpleDomain:QS}=fc(),{SCHEMES:XS,getSchemeHandler:kf}=Sf();function e$(t,e){return typeof t=="string"?t=i$(t,e):typeof t=="object"&&(t=Ar(or(t,e),e)),t}function t$(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=xf(Ar(t,n),Ar(e,n),n,!0);return n.skipEscape=!0,or(o,n)}function xf(t,e,r,n){let o={};return n||(t=Ar(or(t,r),r),e=Ar(or(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=On(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=On(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=On(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=On(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function r$(t,e,r){let n=$f(t,r),o=$f(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function or(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=kf(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=GS(r.path):(r.path=JS(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=VS(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=On(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var n$=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,o$=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/;function s$(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 Tf(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let i=t.match(o$);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(n$);if(a){n.scheme=a[1],n.userinfo=a[3],n.host=a[4],n.port=parseInt(a[5],10),n.path=a[6]||"",n.query=a[7],n.fragment=a[8],isNaN(n.port)&&(n.port=a[5]);let l=s$(n,a);if(l!==void 0&&(n.error=n.error||l,o=!0),n.host)if(YS(n.host)===!1){let d=KS(n.host);n.host=d.host.toLowerCase(),s=d.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let p=kf(r.scheme||n.scheme);if(!r.unicodeSupport&&(!p||!p.unicodeSupport)&&n.host&&(r.domainHost||p&&p.domainHost)&&s===!1&&QS(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(u){n.error=n.error||"Host's domain name can not be converted to ASCII: "+u}if((!p||p&&!p.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=ZS(unescape(n.host),s))),n.path&&(n.path=WS(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}p&&p.parse&&p.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function Ar(t,e){return Tf(t,e).parsed}function i$(t,e){return Ef(t,e).normalized}function Ef(t,e){let{parsed:r,malformedAuthorityOrPort:n}=Tf(t,e);return{normalized:n?t:or(r,e),malformedAuthorityOrPort:n}}function $f(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Ef(t,e);return n?void 0:r}if(typeof t=="object")return or(t,e)}var gc={SCHEMES:XS,normalize:e$,resolve:t$,resolveComponent:xf,equal:r$,serialize:or,parse:Ar};fs.exports=gc;fs.exports.default=gc;fs.exports.fastUri=gc});var Af=j(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});var Pf=Rf();Pf.code='require("ajv/dist/runtime/uri").default';yc.default=Pf});var Df=j(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.CodeGen=xe.Name=xe.nil=xe.stringify=xe.str=xe._=xe.KeywordCxt=void 0;var a$=Cn();Object.defineProperty(xe,"KeywordCxt",{enumerable:!0,get:function(){return a$.KeywordCxt}});var Cr=V();Object.defineProperty(xe,"_",{enumerable:!0,get:function(){return Cr._}});Object.defineProperty(xe,"str",{enumerable:!0,get:function(){return Cr.str}});Object.defineProperty(xe,"stringify",{enumerable:!0,get:function(){return Cr.stringify}});Object.defineProperty(xe,"nil",{enumerable:!0,get:function(){return Cr.nil}});Object.defineProperty(xe,"Name",{enumerable:!0,get:function(){return Cr.Name}});Object.defineProperty(xe,"CodeGen",{enumerable:!0,get:function(){return Cr.CodeGen}});var c$=cs(),jf=In(),l$=Ka(),Nn=ds(),d$=V(),jn=Rn(),hs=En(),wc=re(),Cf=uf(),u$=Af(),zf=(t,e)=>new RegExp(t,e);zf.code="new RegExp";var p$=["removeAdditional","useDefaults","coerceTypes"],f$=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),h$={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},m$={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},If=200;function g$(t){var e,r,n,o,s,i,a,l,p,u,d,f,g,b,v,x,P,N,D,Q,U,je,Ee,lr,Ur;let St=t.strict,Br=(e=t.code)===null||e===void 0?void 0:e.optimize,Ft=Br===!0||Br===void 0?1:Br||0,h=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:zf,m=(o=t.uriResolver)!==null&&o!==void 0?o:u$.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:St)!==null&&i!==void 0?i:!0,strictNumbers:(l=(a=t.strictNumbers)!==null&&a!==void 0?a:St)!==null&&l!==void 0?l:!0,strictTypes:(u=(p=t.strictTypes)!==null&&p!==void 0?p:St)!==null&&u!==void 0?u:"log",strictTuples:(f=(d=t.strictTuples)!==null&&d!==void 0?d:St)!==null&&f!==void 0?f:"log",strictRequired:(b=(g=t.strictRequired)!==null&&g!==void 0?g:St)!==null&&b!==void 0?b:!1,code:t.code?{...t.code,optimize:Ft,regExp:h}:{optimize:Ft,regExp:h},loopRequired:(v=t.loopRequired)!==null&&v!==void 0?v:If,loopEnum:(x=t.loopEnum)!==null&&x!==void 0?x:If,meta:(P=t.meta)!==null&&P!==void 0?P:!0,messages:(N=t.messages)!==null&&N!==void 0?N:!0,inlineRefs:(D=t.inlineRefs)!==null&&D!==void 0?D:!0,schemaId:(Q=t.schemaId)!==null&&Q!==void 0?Q:"$id",addUsedSchema:(U=t.addUsedSchema)!==null&&U!==void 0?U:!0,validateSchema:(je=t.validateSchema)!==null&&je!==void 0?je:!0,validateFormats:(Ee=t.validateFormats)!==null&&Ee!==void 0?Ee:!0,unicodeRegExp:(lr=t.unicodeRegExp)!==null&&lr!==void 0?lr:!0,int32range:(Ur=t.int32range)!==null&&Ur!==void 0?Ur:!0,uriResolver:m}}var zn=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,...g$(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new d$.ValueScope({scope:{},prefixes:f$,es5:r,lines:n}),this.logger=S$(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,l$.getRules)(),Of.call(this,h$,e,"NOT SUPPORTED"),Of.call(this,m$,e,"DEPRECATED","warn"),this._metaOpts=v$.call(this),e.formats&&b$.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&w$.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),y$.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=Cf;n==="id"&&(o={...Cf},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(u,d){await s.call(this,u.$schema);let f=this._addSchema(u,d);return f.validate||i.call(this,f)}async function s(u){u&&!this.getSchema(u)&&await o.call(this,{$ref:u},!0)}async function i(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof jf.default))throw d;return a.call(this,d),await l.call(this,d.missingSchema),i.call(this,u)}}function a({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function l(u){let d=await p.call(this,u);this.refs[u]||await s.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,r)}async function p(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,jn.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=Nf.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Nn.SchemaEnv({schema:{},schemaId:n});if(r=Nn.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=Nf.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,jn.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(k$.call(this,n,r),!r)return(0,wc.eachItem)(n,s=>bc.call(this,s)),this;T$.call(this,r);let o={...r,type:(0,hs.getJSONTypes)(r.type),schemaType:(0,hs.getJSONTypes)(r.schemaType)};return(0,wc.eachItem)(n,o.type.length===0?s=>bc.call(this,s,o):s=>o.type.forEach(i=>bc.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let l=n[a];if(typeof l!="object")continue;let{$data:p}=l.definition,u=i[a];p&&u&&(i[a]=Lf(u))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let l=this._cache.get(e);if(l!==void 0)return l;n=(0,jn.normalizeId)(i||n);let p=jn.getSchemaRefs.call(this,e,n);return l=new Nn.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:p}),this._cache.set(l.schema,l),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=l),o&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Nn.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{Nn.compileSchema.call(this,e)}finally{this.opts=r}}};zn.ValidationError=c$.default;zn.MissingRefError=jf.default;xe.default=zn;function Of(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function Nf(t){return t=(0,jn.normalizeId)(t),this.schemas[t]||this.refs[t]}function y$(){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 b$(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function w$(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function v$(){let t={...this.opts};for(let e of p$)delete t[e];return t}var _$={log(){},warn(){},error(){}};function S$(t){if(t===!1)return _$;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 $$=/^[a-z_$][a-z0-9_$:-]*$/i;function k$(t,e){let{RULES:r}=this;if((0,wc.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!$$.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 bc(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:l})=>l===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,hs.getJSONTypes)(e.type),schemaType:(0,hs.getJSONTypes)(e.schemaType)}};e.before?x$.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(l=>this.addKeyword(l))}function x$(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function T$(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Lf(e)),t.validateSchema=this.compile(e,!0))}var E$={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Lf(t){return{anyOf:[t,E$]}}});var Mf=j(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});var R$={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};vc.default=R$});var Ff=j(sr=>{"use strict";Object.defineProperty(sr,"__esModule",{value:!0});sr.callRef=sr.getValidate=void 0;var P$=In(),qf=et(),qe=V(),Ir=vt(),Uf=ds(),ms=re(),A$={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:l}=n,{root:p}=s;if((r==="#"||r==="#/")&&o===p.baseId)return d();let u=Uf.resolveRef.call(l,p,o,r);if(u===void 0)throw new P$.default(n.opts.uriResolver,o,r);if(u instanceof Uf.SchemaEnv)return f(u);return g(u);function d(){if(s===p)return gs(t,i,s,s.$async);let b=e.scopeValue("root",{ref:p});return gs(t,(0,qe._)`${b}.validate`,p,p.$async)}function f(b){let v=Bf(t,b);gs(t,v,b,b.$async)}function g(b){let v=e.scopeValue("schema",a.code.source===!0?{ref:b,code:(0,qe.stringify)(b)}:{ref:b}),x=e.name("valid"),P=t.subschema({schema:b,dataTypes:[],schemaPath:qe.nil,topSchemaRef:v,errSchemaPath:r},x);t.mergeEvaluated(P),t.ok(x)}}};function Bf(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,qe._)`${r.scopeValue("wrapper",{ref:e})}.validate`}sr.getValidate=Bf;function gs(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:l}=s,p=l.passContext?Ir.default.this:qe.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let b=o.let("valid");o.try(()=>{o.code((0,qe._)`await ${(0,qf.callValidateCode)(t,e,p)}`),g(e),i||o.assign(b,!0)},v=>{o.if((0,qe._)`!(${v} instanceof ${s.ValidationError})`,()=>o.throw(v)),f(v),i||o.assign(b,!1)}),t.ok(b)}function d(){t.result((0,qf.callValidateCode)(t,e,p),()=>g(e),()=>f(e))}function f(b){let v=(0,qe._)`${b}.errors`;o.assign(Ir.default.vErrors,(0,qe._)`${Ir.default.vErrors} === null ? ${v} : ${Ir.default.vErrors}.concat(${v})`),o.assign(Ir.default.errors,(0,qe._)`${Ir.default.vErrors}.length`)}function g(b){var v;if(!s.opts.unevaluated)return;let x=(v=r?.validate)===null||v===void 0?void 0:v.evaluated;if(s.props!==!0)if(x&&!x.dynamicProps)x.props!==void 0&&(s.props=ms.mergeEvaluated.props(o,x.props,s.props));else{let P=o.var("props",(0,qe._)`${b}.evaluated.props`);s.props=ms.mergeEvaluated.props(o,P,s.props,qe.Name)}if(s.items!==!0)if(x&&!x.dynamicItems)x.items!==void 0&&(s.items=ms.mergeEvaluated.items(o,x.items,s.items));else{let P=o.var("items",(0,qe._)`${b}.evaluated.items`);s.items=ms.mergeEvaluated.items(o,P,s.items,qe.Name)}}}sr.callRef=gs;sr.default=A$});var Hf=j(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var C$=Mf(),I$=Ff(),O$=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",C$.default,I$.default];_c.default=O$});var Kf=j(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});var ys=V(),qt=ys.operators,bs={maximum:{okStr:"<=",ok:qt.LTE,fail:qt.GT},minimum:{okStr:">=",ok:qt.GTE,fail:qt.LT},exclusiveMaximum:{okStr:"<",ok:qt.LT,fail:qt.GTE},exclusiveMinimum:{okStr:">",ok:qt.GT,fail:qt.LTE}},N$={message:({keyword:t,schemaCode:e})=>(0,ys.str)`must be ${bs[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ys._)`{comparison: ${bs[t].okStr}, limit: ${e}}`},j$={keyword:Object.keys(bs),type:"number",schemaType:"number",$data:!0,error:N$,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,ys._)`${r} ${bs[e].fail} ${n} || isNaN(${r})`)}};Sc.default=j$});var Vf=j($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});var Ln=V(),z$={message:({schemaCode:t})=>(0,Ln.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Ln._)`{multipleOf: ${t}}`},L$={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:z$,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Ln._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Ln._)`${i} !== parseInt(${i})`;t.fail$data((0,Ln._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};$c.default=L$});var Wf=j(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});function Gf(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}kc.default=Gf;Gf.code='require("ajv/dist/runtime/ucs2length").default'});var Jf=j(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var ir=V(),D$=re(),M$=Wf(),q$={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,ir.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,ir._)`{limit: ${t}}`},U$={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:q$,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?ir.operators.GT:ir.operators.LT,i=o.opts.unicode===!1?(0,ir._)`${r}.length`:(0,ir._)`${(0,D$.useFunc)(t.gen,M$.default)}(${r})`;t.fail$data((0,ir._)`${i} ${s} ${n}`)}};xc.default=U$});var Zf=j(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});var B$=et(),F$=re(),Or=V(),H$={message:({schemaCode:t})=>(0,Or.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Or._)`{pattern: ${t}}`},K$={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:H$,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:l}=i.opts.code,p=l.code==="new RegExp"?(0,Or._)`new RegExp`:(0,F$.useFunc)(e,l),u=e.let("valid");e.try(()=>e.assign(u,(0,Or._)`${p}(${s}, ${a}).test(${r})`),()=>e.assign(u,!1)),t.fail$data((0,Or._)`!${u}`)}else{let l=(0,B$.usePattern)(t,o);t.fail$data((0,Or._)`!${l}.test(${r})`)}}};Tc.default=K$});var Yf=j(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var Dn=V(),V$={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Dn.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Dn._)`{limit: ${t}}`},G$={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:V$,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Dn.operators.GT:Dn.operators.LT;t.fail$data((0,Dn._)`Object.keys(${r}).length ${o} ${n}`)}};Ec.default=G$});var Qf=j(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});var Mn=et(),qn=V(),W$=re(),J$={message:({params:{missingProperty:t}})=>(0,qn.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,qn._)`{missingProperty: ${t}}`},Z$={keyword:"required",type:"object",schemaType:"array",$data:!0,error:J$,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let l=r.length>=a.loopRequired;if(i.allErrors?p():u(),a.strictRequired){let g=t.parentSchema.properties,{definedProperties:b}=t.it;for(let v of r)if(g?.[v]===void 0&&!b.has(v)){let x=i.schemaEnv.baseId+i.errSchemaPath,P=`required property "${v}" is not defined at "${x}" (strictRequired)`;(0,W$.checkStrictMode)(i,P,i.opts.strictRequired)}}function p(){if(l||s)t.block$data(qn.nil,d);else for(let g of r)(0,Mn.checkReportMissingProp)(t,g)}function u(){let g=e.let("missing");if(l||s){let b=e.let("valid",!0);t.block$data(b,()=>f(g,b)),t.ok(b)}else e.if((0,Mn.checkMissingProp)(t,r,g)),(0,Mn.reportMissingProp)(t,g),e.else()}function d(){e.forOf("prop",n,g=>{t.setParams({missingProperty:g}),e.if((0,Mn.noPropertyInData)(e,o,g,a.ownProperties),()=>t.error())})}function f(g,b){t.setParams({missingProperty:g}),e.forOf(g,n,()=>{e.assign(b,(0,Mn.propertyInData)(e,o,g,a.ownProperties)),e.if((0,qn.not)(b),()=>{t.error(),e.break()})},qn.nil)}}};Rc.default=Z$});var Xf=j(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});var Un=V(),Y$={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Un.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Un._)`{limit: ${t}}`},Q$={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Y$,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Un.operators.GT:Un.operators.LT;t.fail$data((0,Un._)`${r}.length ${o} ${n}`)}};Pc.default=Q$});var ws=j(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});var eh=Xa();eh.code='require("ajv/dist/runtime/equal").default';Ac.default=eh});var th=j(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var Cc=En(),Te=V(),X$=re(),ek=ws(),tk={message:({params:{i:t,j:e}})=>(0,Te.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Te._)`{i: ${t}, j: ${e}}`},rk={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:tk,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let l=e.let("valid"),p=s.items?(0,Cc.getSchemaTypes)(s.items):[];t.block$data(l,u,(0,Te._)`${i} === false`),t.ok(l);function u(){let b=e.let("i",(0,Te._)`${r}.length`),v=e.let("j");t.setParams({i:b,j:v}),e.assign(l,!0),e.if((0,Te._)`${b} > 1`,()=>(d()?f:g)(b,v))}function d(){return p.length>0&&!p.some(b=>b==="object"||b==="array")}function f(b,v){let x=e.name("item"),P=(0,Cc.checkDataTypes)(p,x,a.opts.strictNumbers,Cc.DataType.Wrong),N=e.const("indices",(0,Te._)`{}`);e.for((0,Te._)`;${b}--;`,()=>{e.let(x,(0,Te._)`${r}[${b}]`),e.if(P,(0,Te._)`continue`),p.length>1&&e.if((0,Te._)`typeof ${x} == "string"`,(0,Te._)`${x} += "_"`),e.if((0,Te._)`typeof ${N}[${x}] == "number"`,()=>{e.assign(v,(0,Te._)`${N}[${x}]`),t.error(),e.assign(l,!1).break()}).code((0,Te._)`${N}[${x}] = ${b}`)})}function g(b,v){let x=(0,X$.useFunc)(e,ek.default),P=e.name("outer");e.label(P).for((0,Te._)`;${b}--;`,()=>e.for((0,Te._)`${v} = ${b}; ${v}--;`,()=>e.if((0,Te._)`${x}(${r}[${b}], ${r}[${v}])`,()=>{t.error(),e.assign(l,!1).break(P)})))}}};Ic.default=rk});var rh=j(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var Oc=V(),nk=re(),ok=ws(),sk={message:"must be equal to constant",params:({schemaCode:t})=>(0,Oc._)`{allowedValue: ${t}}`},ik={keyword:"const",$data:!0,error:sk,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Oc._)`!${(0,nk.useFunc)(e,ok.default)}(${r}, ${o})`):t.fail((0,Oc._)`${s} !== ${r}`)}};Nc.default=ik});var nh=j(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});var Bn=V(),ak=re(),ck=ws(),lk={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Bn._)`{allowedValues: ${t}}`},dk={keyword:"enum",schemaType:"array",$data:!0,error:lk,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,l,p=()=>l??(l=(0,ak.useFunc)(e,ck.default)),u;if(a||n)u=e.let("valid"),t.block$data(u,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let g=e.const("vSchema",s);u=(0,Bn.or)(...o.map((b,v)=>f(g,v)))}t.pass(u);function d(){e.assign(u,!1),e.forOf("v",s,g=>e.if((0,Bn._)`${p()}(${r}, ${g})`,()=>e.assign(u,!0).break()))}function f(g,b){let v=o[b];return typeof v=="object"&&v!==null?(0,Bn._)`${p()}(${r}, ${g}[${b}])`:(0,Bn._)`${r} === ${v}`}}};jc.default=dk});var oh=j(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var uk=Kf(),pk=Vf(),fk=Jf(),hk=Zf(),mk=Yf(),gk=Qf(),yk=Xf(),bk=th(),wk=rh(),vk=nh(),_k=[uk.default,pk.default,fk.default,hk.default,mk.default,gk.default,yk.default,bk.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},wk.default,vk.default];zc.default=_k});var Dc=j(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.validateAdditionalItems=void 0;var ar=V(),Lc=re(),Sk={message:({params:{len:t}})=>(0,ar.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,ar._)`{limit: ${t}}`},$k={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Sk,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Lc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}sh(t,n)}};function sh(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,ar._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,ar._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Lc.alwaysValidSchema)(i,n)){let p=r.var("valid",(0,ar._)`${a} <= ${e.length}`);r.if((0,ar.not)(p),()=>l(p)),t.ok(p)}function l(p){r.forRange("i",e.length,a,u=>{t.subschema({keyword:s,dataProp:u,dataPropType:Lc.Type.Num},p),i.allErrors||r.if((0,ar.not)(p),()=>r.break())})}}Fn.validateAdditionalItems=sh;Fn.default=$k});var Mc=j(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.validateTuple=void 0;var ih=V(),vs=re(),kk=et(),xk={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return ah(t,"additionalItems",e);r.items=!0,!(0,vs.alwaysValidSchema)(r,e)&&t.ok((0,kk.validateArray)(t))}};function ah(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;u(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=vs.mergeEvaluated.items(n,r.length,a.items));let l=n.name("valid"),p=n.const("len",(0,ih._)`${s}.length`);r.forEach((d,f)=>{(0,vs.alwaysValidSchema)(a,d)||(n.if((0,ih._)`${p} > ${f}`,()=>t.subschema({keyword:i,schemaProp:f,dataProp:f},l)),t.ok(l))});function u(d){let{opts:f,errSchemaPath:g}=a,b=r.length,v=b===d.minItems&&(b===d.maxItems||d[e]===!1);if(f.strictTuples&&!v){let x=`"${i}" is ${b}-tuple, but minItems or maxItems/${e} are not specified or different at path "${g}"`;(0,vs.checkStrictMode)(a,x,f.strictTuples)}}}Hn.validateTuple=ah;Hn.default=xk});var ch=j(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var Tk=Mc(),Ek={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,Tk.validateTuple)(t,"items")};qc.default=Ek});var dh=j(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});var lh=V(),Rk=re(),Pk=et(),Ak=Dc(),Ck={message:({params:{len:t}})=>(0,lh.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,lh._)`{limit: ${t}}`},Ik={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Ck,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,Rk.alwaysValidSchema)(n,e)&&(o?(0,Ak.validateAdditionalItems)(t,o):t.ok((0,Pk.validateArray)(t)))}};Uc.default=Ik});var uh=j(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var rt=V(),_s=re(),Ok={message:({params:{min:t,max:e}})=>e===void 0?(0,rt.str)`must contain at least ${t} valid item(s)`:(0,rt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,rt._)`{minContains: ${t}}`:(0,rt._)`{minContains: ${t}, maxContains: ${e}}`},Nk={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Ok,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:l,maxContains:p}=n;s.opts.next?(i=l===void 0?1:l,a=p):i=1;let u=e.const("len",(0,rt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,_s.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,_s.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,_s.alwaysValidSchema)(s,r)){let v=(0,rt._)`${u} >= ${i}`;a!==void 0&&(v=(0,rt._)`${v} && ${u} <= ${a}`),t.pass(v);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?g(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,rt._)`${o}.length > 0`,f)):(e.let(d,!1),f()),t.result(d,()=>t.reset());function f(){let v=e.name("_valid"),x=e.let("count",0);g(v,()=>e.if(v,()=>b(x)))}function g(v,x){e.forRange("i",0,u,P=>{t.subschema({keyword:"contains",dataProp:P,dataPropType:_s.Type.Num,compositeRule:!0},v),x()})}function b(v){e.code((0,rt._)`${v}++`),a===void 0?e.if((0,rt._)`${v} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,rt._)`${v} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,rt._)`${v} >= ${i}`,()=>e.assign(d,!0)))}}};Bc.default=Nk});var hh=j(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.validateSchemaDeps=ht.validatePropertyDeps=ht.error=void 0;var Fc=V(),jk=re(),Kn=et();ht.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Fc.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Fc._)`{property: ${t},
|
|
888
|
+
missingProperty: ${n},
|
|
889
|
+
depsCount: ${e},
|
|
890
|
+
deps: ${r}}`};var zk={keyword:"dependencies",type:"object",schemaType:"object",error:ht.error,code(t){let[e,r]=Lk(t);ph(t,e),fh(t,r)}};function Lk({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function ph(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let l=(0,Kn.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(l,()=>{for(let p of a)(0,Kn.checkReportMissingProp)(t,p)}):(r.if((0,Fc._)`${l} && (${(0,Kn.checkMissingProp)(t,a,s)})`),(0,Kn.reportMissingProp)(t,s),r.else())}}ht.validatePropertyDeps=ph;function fh(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,jk.alwaysValidSchema)(s,e[a])||(r.if((0,Kn.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let l=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(l,i)},()=>r.var(i,!0)),t.ok(i))}ht.validateSchemaDeps=fh;ht.default=zk});var gh=j(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});var mh=V(),Dk=re(),Mk={message:"property name must be valid",params:({params:t})=>(0,mh._)`{propertyName: ${t.propertyName}}`},qk={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Mk,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,Dk.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,mh.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Hc.default=qk});var Vc=j(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});var Ss=et(),ct=V(),Uk=vt(),$s=re(),Bk={message:"must NOT have additional properties",params:({params:t})=>(0,ct._)`{additionalProperty: ${t.additionalProperty}}`},Fk={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Bk,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:l}=i;if(i.props=!0,l.removeAdditional!=="all"&&(0,$s.alwaysValidSchema)(i,r))return;let p=(0,Ss.allSchemaProperties)(n.properties),u=(0,Ss.allSchemaProperties)(n.patternProperties);d(),t.ok((0,ct._)`${s} === ${Uk.default.errors}`);function d(){e.forIn("key",o,x=>{!p.length&&!u.length?b(x):e.if(f(x),()=>b(x))})}function f(x){let P;if(p.length>8){let N=(0,$s.schemaRefOrVal)(i,n.properties,"properties");P=(0,Ss.isOwnProperty)(e,N,x)}else p.length?P=(0,ct.or)(...p.map(N=>(0,ct._)`${x} === ${N}`)):P=ct.nil;return u.length&&(P=(0,ct.or)(P,...u.map(N=>(0,ct._)`${(0,Ss.usePattern)(t,N)}.test(${x})`))),(0,ct.not)(P)}function g(x){e.code((0,ct._)`delete ${o}[${x}]`)}function b(x){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){g(x);return}if(r===!1){t.setParams({additionalProperty:x}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,$s.alwaysValidSchema)(i,r)){let P=e.name("valid");l.removeAdditional==="failing"?(v(x,P,!1),e.if((0,ct.not)(P),()=>{t.reset(),g(x)})):(v(x,P),a||e.if((0,ct.not)(P),()=>e.break()))}}function v(x,P,N){let D={keyword:"additionalProperties",dataProp:x,dataPropType:$s.Type.Str};N===!1&&Object.assign(D,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(D,P)}}};Kc.default=Fk});var wh=j(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var Hk=Cn(),yh=et(),Gc=re(),bh=Vc(),Kk={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&bh.default.code(new Hk.KeywordCxt(s,bh.default,"additionalProperties"));let i=(0,yh.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Gc.mergeEvaluated.props(e,(0,Gc.toHash)(i),s.props));let a=i.filter(d=>!(0,Gc.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let l=e.name("valid");for(let d of a)p(d)?u(d):(e.if((0,yh.propertyInData)(e,o,d,s.opts.ownProperties)),u(d),s.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(l);function p(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function u(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},l)}}};Wc.default=Kk});var $h=j(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});var vh=et(),ks=V(),_h=re(),Sh=re(),Vk={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,vh.allSchemaProperties)(r),l=a.filter(v=>(0,_h.alwaysValidSchema)(s,r[v]));if(a.length===0||l.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let p=i.strictSchema&&!i.allowMatchingProperties&&o.properties,u=e.name("valid");s.props!==!0&&!(s.props instanceof ks.Name)&&(s.props=(0,Sh.evaluatedPropsToName)(e,s.props));let{props:d}=s;f();function f(){for(let v of a)p&&g(v),s.allErrors?b(v):(e.var(u,!0),b(v),e.if(u))}function g(v){for(let x in p)new RegExp(v).test(x)&&(0,_h.checkStrictMode)(s,`property ${x} matches pattern ${v} (use allowMatchingProperties)`)}function b(v){e.forIn("key",n,x=>{e.if((0,ks._)`${(0,vh.usePattern)(t,v)}.test(${x})`,()=>{let P=l.includes(v);P||t.subschema({keyword:"patternProperties",schemaProp:v,dataProp:x,dataPropType:Sh.Type.Str},u),s.opts.unevaluated&&d!==!0?e.assign((0,ks._)`${d}[${x}]`,!0):!P&&!s.allErrors&&e.if((0,ks.not)(u),()=>e.break())})})}}};Jc.default=Vk});var kh=j(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});var Gk=re(),Wk={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,Gk.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Zc.default=Wk});var xh=j(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});var Jk=et(),Zk={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Jk.validateUnion,error:{message:"must match a schema in anyOf"}};Yc.default=Zk});var Th=j(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});var xs=V(),Yk=re(),Qk={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,xs._)`{passingSchemas: ${t.passing}}`},Xk={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Qk,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),l=e.name("_valid");t.setParams({passing:a}),e.block(p),t.result(i,()=>t.reset(),()=>t.error(!0));function p(){s.forEach((u,d)=>{let f;(0,Yk.alwaysValidSchema)(o,u)?e.var(l,!0):f=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},l),d>0&&e.if((0,xs._)`${l} && ${i}`).assign(i,!1).assign(a,(0,xs._)`[${a}, ${d}]`).else(),e.if(l,()=>{e.assign(i,!0),e.assign(a,d),f&&t.mergeEvaluated(f,xs.Name)})})}}};Qc.default=Xk});var Eh=j(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});var ex=re(),tx={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,ex.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Xc.default=tx});var Ah=j(el=>{"use strict";Object.defineProperty(el,"__esModule",{value:!0});var Ts=V(),Ph=re(),rx={message:({params:t})=>(0,Ts.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Ts._)`{failingKeyword: ${t.ifClause}}`},nx={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:rx,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Ph.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Rh(n,"then"),s=Rh(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(l(),t.reset(),o&&s){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,p("then",u),p("else",u))}else o?e.if(a,p("then")):e.if((0,Ts.not)(a),p("else"));t.pass(i,()=>t.error(!0));function l(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function p(u,d){return()=>{let f=t.subschema({keyword:u},a);e.assign(i,a),t.mergeValidEvaluated(f,i),d?e.assign(d,(0,Ts._)`${u}`):t.setParams({ifClause:u})}}}};function Rh(t,e){let r=t.schema[e];return r!==void 0&&!(0,Ph.alwaysValidSchema)(t,r)}el.default=nx});var Ch=j(tl=>{"use strict";Object.defineProperty(tl,"__esModule",{value:!0});var ox=re(),sx={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,ox.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};tl.default=sx});var Ih=j(rl=>{"use strict";Object.defineProperty(rl,"__esModule",{value:!0});var ix=Dc(),ax=ch(),cx=Mc(),lx=dh(),dx=uh(),ux=hh(),px=gh(),fx=Vc(),hx=wh(),mx=$h(),gx=kh(),yx=xh(),bx=Th(),wx=Eh(),vx=Ah(),_x=Ch();function Sx(t=!1){let e=[gx.default,yx.default,bx.default,wx.default,vx.default,_x.default,px.default,fx.default,ux.default,hx.default,mx.default];return t?e.push(ax.default,lx.default):e.push(ix.default,cx.default),e.push(dx.default),e}rl.default=Sx});var Oh=j(nl=>{"use strict";Object.defineProperty(nl,"__esModule",{value:!0});var be=V(),$x={message:({schemaCode:t})=>(0,be.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,be._)`{format: ${t}}`},kx={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:$x,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:l,errSchemaPath:p,schemaEnv:u,self:d}=a;if(!l.validateFormats)return;o?f():g();function f(){let b=r.scopeValue("formats",{ref:d.formats,code:l.code.formats}),v=r.const("fDef",(0,be._)`${b}[${i}]`),x=r.let("fType"),P=r.let("format");r.if((0,be._)`typeof ${v} == "object" && !(${v} instanceof RegExp)`,()=>r.assign(x,(0,be._)`${v}.type || "string"`).assign(P,(0,be._)`${v}.validate`),()=>r.assign(x,(0,be._)`"string"`).assign(P,v)),t.fail$data((0,be.or)(N(),D()));function N(){return l.strictSchema===!1?be.nil:(0,be._)`${i} && !${P}`}function D(){let Q=u.$async?(0,be._)`(${v}.async ? await ${P}(${n}) : ${P}(${n}))`:(0,be._)`${P}(${n})`,U=(0,be._)`(typeof ${P} == "function" ? ${Q} : ${P}.test(${n}))`;return(0,be._)`${P} && ${P} !== true && ${x} === ${e} && !${U}`}}function g(){let b=d.formats[s];if(!b){N();return}if(b===!0)return;let[v,x,P]=D(b);v===e&&t.pass(Q());function N(){if(l.strictSchema===!1){d.logger.warn(U());return}throw new Error(U());function U(){return`unknown format "${s}" ignored in schema at path "${p}"`}}function D(U){let je=U instanceof RegExp?(0,be.regexpCode)(U):l.code.formats?(0,be._)`${l.code.formats}${(0,be.getProperty)(s)}`:void 0,Ee=r.scopeValue("formats",{key:s,ref:U,code:je});return typeof U=="object"&&!(U instanceof RegExp)?[U.type||"string",U.validate,(0,be._)`${Ee}.validate`]:["string",U,Ee]}function Q(){if(typeof b=="object"&&!(b instanceof RegExp)&&b.async){if(!u.$async)throw new Error("async format in sync schema");return(0,be._)`await ${P}(${n})`}return typeof x=="function"?(0,be._)`${P}(${n})`:(0,be._)`${P}.test(${n})`}}}};nl.default=kx});var Nh=j(ol=>{"use strict";Object.defineProperty(ol,"__esModule",{value:!0});var xx=Oh(),Tx=[xx.default];ol.default=Tx});var jh=j(Nr=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});Nr.contentVocabulary=Nr.metadataVocabulary=void 0;Nr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Nr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Lh=j(sl=>{"use strict";Object.defineProperty(sl,"__esModule",{value:!0});var Ex=Hf(),Rx=oh(),Px=Ih(),Ax=Nh(),zh=jh(),Cx=[Ex.default,Rx.default,(0,Px.default)(),Ax.default,zh.metadataVocabulary,zh.contentVocabulary];sl.default=Cx});var Mh=j(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});Es.DiscrError=void 0;var Dh;(function(t){t.Tag="tag",t.Mapping="mapping"})(Dh||(Es.DiscrError=Dh={}))});var Uh=j(al=>{"use strict";Object.defineProperty(al,"__esModule",{value:!0});var jr=V(),il=Mh(),qh=ds(),Ix=In(),Ox=re(),Nx={message:({params:{discrError:t,tagName:e}})=>t===il.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,jr._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},jx={keyword:"discriminator",type:"object",schemaType:"object",error:Nx,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let l=e.let("valid",!1),p=e.const("tag",(0,jr._)`${r}${(0,jr.getProperty)(a)}`);e.if((0,jr._)`typeof ${p} == "string"`,()=>u(),()=>t.error(!1,{discrError:il.DiscrError.Tag,tag:p,tagName:a})),t.ok(l);function u(){let g=f();e.if(!1);for(let b in g)e.elseIf((0,jr._)`${p} === ${b}`),e.assign(l,d(g[b]));e.else(),t.error(!1,{discrError:il.DiscrError.Mapping,tag:p,tagName:a}),e.endIf()}function d(g){let b=e.name("valid"),v=t.subschema({keyword:"oneOf",schemaProp:g},b);return t.mergeEvaluated(v,jr.Name),b}function f(){var g;let b={},v=P(o),x=!0;for(let Q=0;Q<i.length;Q++){let U=i[Q];if(U?.$ref&&!(0,Ox.schemaHasRulesButRef)(U,s.self.RULES)){let Ee=U.$ref;if(U=qh.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Ee),U instanceof qh.SchemaEnv&&(U=U.schema),U===void 0)throw new Ix.default(s.opts.uriResolver,s.baseId,Ee)}let je=(g=U?.properties)===null||g===void 0?void 0:g[a];if(typeof je!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);x=x&&(v||P(U)),N(je,Q)}if(!x)throw new Error(`discriminator: "${a}" must be required`);return b;function P({required:Q}){return Array.isArray(Q)&&Q.includes(a)}function N(Q,U){if(Q.const)D(Q.const,U);else if(Q.enum)for(let je of Q.enum)D(je,U);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function D(Q,U){if(typeof Q!="string"||Q in b)throw new Error(`discriminator: "${a}" values must be unique strings`);b[Q]=U}}}};al.default=jx});var Bh=j((TI,zx)=>{zx.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 ll=j((ue,cl)=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.MissingRefError=ue.ValidationError=ue.CodeGen=ue.Name=ue.nil=ue.stringify=ue.str=ue._=ue.KeywordCxt=ue.Ajv=void 0;var Lx=Df(),Dx=Lh(),Mx=Uh(),Fh=Bh(),qx=["/properties"],Rs="http://json-schema.org/draft-07/schema",zr=class extends Lx.default{_addVocabularies(){super._addVocabularies(),Dx.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Mx.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Fh,qx):Fh;this.addMetaSchema(e,Rs,!1),this.refs["http://json-schema.org/schema"]=Rs}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Rs)?Rs:void 0)}};ue.Ajv=zr;cl.exports=ue=zr;cl.exports.Ajv=zr;Object.defineProperty(ue,"__esModule",{value:!0});ue.default=zr;var Ux=Cn();Object.defineProperty(ue,"KeywordCxt",{enumerable:!0,get:function(){return Ux.KeywordCxt}});var Lr=V();Object.defineProperty(ue,"_",{enumerable:!0,get:function(){return Lr._}});Object.defineProperty(ue,"str",{enumerable:!0,get:function(){return Lr.str}});Object.defineProperty(ue,"stringify",{enumerable:!0,get:function(){return Lr.stringify}});Object.defineProperty(ue,"nil",{enumerable:!0,get:function(){return Lr.nil}});Object.defineProperty(ue,"Name",{enumerable:!0,get:function(){return Lr.Name}});Object.defineProperty(ue,"CodeGen",{enumerable:!0,get:function(){return Lr.CodeGen}});var Bx=cs();Object.defineProperty(ue,"ValidationError",{enumerable:!0,get:function(){return Bx.default}});var Fx=In();Object.defineProperty(ue,"MissingRefError",{enumerable:!0,get:function(){return Fx.default}})});var Yh=j(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.formatNames=gt.fastFormats=gt.fullFormats=void 0;function mt(t,e){return{validate:t,compare:e}}gt.fullFormats={date:mt(Gh,fl),time:mt(ul(!0),hl),"date-time":mt(Hh(!0),Jh),"iso-time":mt(ul(),Wh),"iso-date-time":mt(Hh(),Zh),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Jx,"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:r0,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:Zx,int32:{type:"number",validate:Xx},int64:{type:"number",validate:e0},float:{type:"number",validate:Vh},double:{type:"number",validate:Vh},password:!0,binary:!0};gt.fastFormats={...gt.fullFormats,date:mt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,fl),time:mt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,hl),"date-time":mt(/^\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,Jh),"iso-time":mt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Wh),"iso-date-time":mt(/^\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,Zh),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};gt.formatNames=Object.keys(gt.fullFormats);function Hx(t){return t%4===0&&(t%100!==0||t%400===0)}var Kx=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Vx=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Gh(t){let e=Kx.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&Hx(r)?29:Vx[n])}function fl(t,e){if(t&&e)return t>e?1:t<e?-1:0}var dl=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function ul(t){return function(r){let n=dl.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],l=n[5]==="-"?-1:1,p=+(n[6]||0),u=+(n[7]||0);if(p>23||u>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-u*l,f=o-p*l-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&i<61}}function hl(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 Wh(t,e){if(!(t&&e))return;let r=dl.exec(t),n=dl.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 pl=/t|\s/i;function Hh(t){let e=ul(t);return function(n){let o=n.split(pl);return o.length===2&&Gh(o[0])&&e(o[1])}}function Jh(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function Zh(t,e){if(!(t&&e))return;let[r,n]=t.split(pl),[o,s]=e.split(pl),i=fl(r,o);if(i!==void 0)return i||hl(n,s)}var Gx=/\/|:/,Wx=/^(?:[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 Jx(t){return Gx.test(t)&&Wx.test(t)}var Kh=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function Zx(t){return Kh.lastIndex=0,Kh.test(t)}var Yx=-(2**31),Qx=2**31-1;function Xx(t){return Number.isInteger(t)&&t<=Qx&&t>=Yx}function e0(t){return Number.isInteger(t)}function Vh(){return!0}var t0=/[^\\]\\Z/;function r0(t){if(t0.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Qh=j(Dr=>{"use strict";Object.defineProperty(Dr,"__esModule",{value:!0});Dr.formatLimitDefinition=void 0;var n0=ll(),lt=V(),Ut=lt.operators,Ps={formatMaximum:{okStr:"<=",ok:Ut.LTE,fail:Ut.GT},formatMinimum:{okStr:">=",ok:Ut.GTE,fail:Ut.LT},formatExclusiveMaximum:{okStr:"<",ok:Ut.LT,fail:Ut.GTE},formatExclusiveMinimum:{okStr:">",ok:Ut.GT,fail:Ut.LTE}},o0={message:({keyword:t,schemaCode:e})=>(0,lt.str)`should be ${Ps[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,lt._)`{comparison: ${Ps[t].okStr}, limit: ${e}}`};Dr.formatLimitDefinition={keyword:Object.keys(Ps),type:"string",schemaType:"string",$data:!0,error:o0,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let l=new n0.KeywordCxt(s,a.RULES.all.format.definition,"format");l.$data?p():u();function p(){let f=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),g=e.const("fmt",(0,lt._)`${f}[${l.schemaCode}]`);t.fail$data((0,lt.or)((0,lt._)`typeof ${g} != "object"`,(0,lt._)`${g} instanceof RegExp`,(0,lt._)`typeof ${g}.compare != "function"`,d(g)))}function u(){let f=l.schema,g=a.formats[f];if(!g||g===!0)return;if(typeof g!="object"||g instanceof RegExp||typeof g.compare!="function")throw new Error(`"${o}": format "${f}" does not define "compare" function`);let b=e.scopeValue("formats",{key:f,ref:g,code:i.code.formats?(0,lt._)`${i.code.formats}${(0,lt.getProperty)(f)}`:void 0});t.fail$data(d(b))}function d(f){return(0,lt._)`${f}.compare(${r}, ${n}) ${Ps[o].fail} 0`}},dependencies:["format"]};var s0=t=>(t.addKeyword(Dr.formatLimitDefinition),t);Dr.default=s0});var rm=j((Vn,tm)=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});var Mr=Yh(),i0=Qh(),ml=V(),Xh=new ml.Name("fullFormats"),a0=new ml.Name("fastFormats"),gl=(t,e={keywords:!0})=>{if(Array.isArray(e))return em(t,e,Mr.fullFormats,Xh),t;let[r,n]=e.mode==="fast"?[Mr.fastFormats,a0]:[Mr.fullFormats,Xh],o=e.formats||Mr.formatNames;return em(t,o,r,n),e.keywords&&(0,i0.default)(t),t};gl.get=(t,e="full")=>{let n=(e==="fast"?Mr.fastFormats:Mr.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function em(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,ml._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}tm.exports=Vn=gl;Object.defineProperty(Vn,"__esModule",{value:!0});Vn.default=gl});function c0(){let t=new nm.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,om.default)(t),t}var nm,om,As,sm=O(()=>{nm=Tl(ll(),1),om=Tl(rm(),1);As=class{constructor(e){this._ajv=e??c0()}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 Cs,im=O(()=>{_r();Cs=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(u=>u.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,l=a?Array.isArray(a.content)?a.content:[a.content]:[],p=l.some(u=>u.type==="tool_use");if(i){if(s.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!p)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(p){let u=new Set(l.filter(f=>f.type==="tool_use").map(f=>f.id)),d=new Set(s.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(u.size!==d.size||![...u].every(f=>d.has(f)))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},mn,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},vr,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 am(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 cm(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 lm=O(()=>{});var Is,dm=O(()=>{up();_r();sm();on();im();lm();Is=class extends Jo{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(hn.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new As,this.setRequestHandler(Ai,n=>this._oninitialize(n)),this.setNotificationHandler(Ci,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Di,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=hn.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Cs(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=dp(this._capabilities,e)}setRequestHandler(e,r){let o=At(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=mr(o);if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(l,p)=>{let u=Pt(wr,l);if(!u.success){let b=u.error instanceof Error?u.error.message:String(u.error);throw new z(M.InvalidParams,`Invalid tools/call request: ${b}`)}let{params:d}=u.data,f=await Promise.resolve(r(l,p));if(d.task){let b=Pt(yr,f);if(!b.success){let v=b.error instanceof Error?b.error.message:String(b.error);throw new z(M.InvalidParams,`Invalid task creation result: ${v}`)}return b.data}let g=Pt(Lo,f);if(!g.success){let b=g.error instanceof Error?g.error.message:String(g.error);throw new z(M.InvalidParams,`Invalid tools/call result: ${b}`)}return g.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){cm(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&am(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:lu.includes(r)?r:xi,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"},_o)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(p=>p.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],l=a.some(p=>p.type==="tool_use");if(s){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(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let p=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),u=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(p.size!==u.size||![...p].every(d=>u.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Mi,r):this.request({method:"sampling/createMessage",params:e},mn,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},vr,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},vr,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new z(M.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof z?i:new z(M.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},qi,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 yl(t){return!!t&&typeof t=="object"&&pm in t}function fm(t){return t[pm]?.complete}var pm,um,hm=O(()=>{pm=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(um||(um={}))});var mm=O(()=>{});function d0(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"),!l0.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function u0(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 bl(t){let e=d0(t);return u0(t,e.warnings),e.isValid}var l0,gm=O(()=>{l0=/^[A-Za-z0-9._-]{1,128}$/});var Os,ym=O(()=>{Os=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}}});import{ZodOptional as p0}from"zod";function vm(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function _m(t){return"_def"in t||"_zod"in t||vm(t)}function wl(t){return typeof t!="object"||t===null||_m(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(vm)}function bm(t){if(t){if(wl(t))return Zt(t);if(!_m(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function h0(t){let e=At(t);return e?Object.entries(e).map(([r,n])=>{let o=au(n),s=cu(n);return{name:r,description:o,required:!s}}):[]}function Bt(t){let r=At(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=mr(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function wm(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Ns,f0,Gn,Sm=O(()=>{dm();on();$a();_r();hm();mm();gm();ym();Ns=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 Is(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Os(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Bt(zo)),this.server.assertCanSetRequestHandler(Bt(wr)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(zo,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=hr(r.inputSchema);return o?va(o,{strictUnions:!0,pipeStrategy:"input"}):f0})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=hr(r.outputSchema);o&&(n.outputSchema=va(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(wr,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new z(M.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new z(M.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new z(M.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new z(M.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),l=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,l,e.params.name),l}catch(n){if(n instanceof z&&n.code===M.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=hr(e.inputSchema)??e.inputSchema,i=await go(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",l=yo(a);throw new z(M.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${l}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new z(M.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=hr(e.outputSchema),s=await go(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=yo(i);throw new z(M.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),l=a.task.taskId,p=a.task,u=p.pollInterval??5e3;for(;p.status!=="completed"&&p.status!=="failed"&&p.status!=="cancelled";){await new Promise(f=>setTimeout(f,u));let d=await n.taskStore.getTask(l);if(!d)throw new z(M.InternalError,`Task ${l} not found during polling`);p=d}return await n.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Bt(Do)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Do,async e=>{switch(e.params.ref.type){case"ref/prompt":return xu(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Tu(e),this.handleResourceCompletion(e,e.params.ref);default:throw new z(M.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new z(M.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new z(M.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Gn;let s=At(n.argsSchema)?.[e.params.argument.name];if(!yl(s))return Gn;let i=fm(s);if(!i)return Gn;let a=await i(e.params.argument.value,e.params.context);return wm(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 Gn;throw new z(M.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return Gn;let s=await o(e.params.argument.value,e.params.context);return wm(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Bt(Co)),this.server.assertCanSetRequestHandler(Bt(Io)),this.server.assertCanSetRequestHandler(Bt(Oo)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Co,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(Io,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Oo,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new z(M.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new z(M.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Bt(No)),this.server.assertCanSetRequestHandler(Bt(jo)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(No,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?h0(r.argsSchema):void 0}))})),this.server.setRequestHandler(jo,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new z(M.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new z(M.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=hr(n.argsSchema),s=await go(o,e.params.arguments);if(!s.success){let l="error"in s?s.error:"Unknown error",p=yo(l);throw new z(M.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${p}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:p=>{typeof p.name<"u"&&p.name!==e&&(delete this._registeredResourceTemplates[e],p.name&&(this._registeredResourceTemplates[p.name]=i)),typeof p.title<"u"&&(i.title=p.title),typeof p.template<"u"&&(i.resourceTemplate=p.template),typeof p.metadata<"u"&&(i.metadata=p.metadata),typeof p.callback<"u"&&(i.readCallback=p.callback),typeof p.enabled<"u"&&(i.enabled=p.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(p=>!!n.completeCallback(p))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:Zt(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=Zt(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(l=>{let p=l instanceof p0?l._def?.innerType:l;return yl(p)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,l,p){bl(e);let u={title:r,description:n,inputSchema:bm(o),outputSchema:bm(s),annotations:i,execution:a,_meta:l,handler:p,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&bl(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=u)),typeof d.title<"u"&&(u.title=d.title),typeof d.description<"u"&&(u.description=d.description),typeof d.paramsSchema<"u"&&(u.inputSchema=Zt(d.paramsSchema)),typeof d.outputSchema<"u"&&(u.outputSchema=Zt(d.outputSchema)),typeof d.callback<"u"&&(u.handler=d.callback),typeof d.annotations<"u"&&(u.annotations=d.annotations),typeof d._meta<"u"&&(u._meta=d._meta),typeof d.enabled<"u"&&(u.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let l=r[0];if(wl(l))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!wl(r[0])&&(i=r.shift());else if(typeof l=="object"&&l!==null){if(Object.values(l).some(p=>typeof p=="object"&&p!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:l,_meta:p}=r;return this._createRegisteredTool(e,o,s,i,a,l,{taskSupport:"forbidden"},p,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},f0={type:"object",properties:{}};Gn={completion:{values:[],hasMore:!1}}});function g0(t){return yu.parse(JSON.parse(t))}function $m(t){return JSON.stringify(t)+`
|
|
891
|
+
`}var m0,js,km=O(()=>{_r();m0=10*1024*1024,js=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??m0}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
892
|
+
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),g0(r)}clear(){this._buffer=void 0}}});import xm from"node:process";var zs,Tm=O(()=>{km();zs=class{constructor(e=xm.stdin,r=xm.stdout,n){this._stdin=e,this._stdout=r,this._started=!1,this._ondata=o=>{try{this._readBuffer.append(o),this.processReadBuffer()}catch(s){this.onerror?.(s),this.close().catch(()=>{})}},this._onerror=o=>{this.onerror?.(o)},this._readBuffer=new js({maxBufferSize:n?.maxBufferSize})}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=$m(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var Em,Rm=O(()=>{Em=[]});var Lm={};xl(Lm,{AUTHORING_MCP_SERVER_NAME:()=>Om,AUTHORING_MCP_SERVER_VERSION:()=>Nm,AUTHORING_RESOURCES:()=>v0,AUTHORING_TOOLS:()=>w0,AUTHORING_TOOLS_PUBLIC:()=>zm,buildAuthoringMcpServer:()=>jm,runAuthoringMcpServer:()=>_0});import{promises as y0}from"node:fs";import{resolve as Pm}from"node:path";import{z as H}from"zod";function Im(){return Cm??=import("../mcp/grounding.js").then(e=>e,()=>null),Cm}function Se(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function b0(t,e={}){let r=e.fetchImpl??fetch;try{let n=await r(`${t.baseUrl.replace(/\/+$/,"")}/v1/extensions`,{headers:{Authorization:`Bearer ${t.token}`,Accept:"application/json"}});return n.ok?((await n.json()).extensions??[]).map(s=>s.hookId).filter(s=>typeof s=="string"):null}catch{return null}}async function jm(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let d=await dt(t.baseUrl);if(!d)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:d.baseUrl,token:d.token}}let r=t.grounding??{},n=await Im(),o=null;if(n)try{let d=await e();o={surface:"mcp-authoring",baseUrl:d.baseUrl,token:d.token}}catch{o=null}let s=n&&o?await n.loadActiveSources(o,r):[],i={...r,loadActiveSourcesImpl:async()=>s},a=[],l=[];if(n&&o){try{a=await n.listMcpPromptSkills(o,i)}catch{a=[]}try{l=(await n.listRecipesForSurface(o,i)).map(d=>({id:d.id,record_type:d.record_type,intent:d.intent}))}catch{l=[]}}let p=o?await b0(o,r):null,u=new Ns({name:Om,version:Nm},n?{instructions:n.renderAuthoringInstructions({baseUrl:o?.baseUrl??t.baseUrl??"this instance",sources:s,recipeIntents:l,promptNames:a.map(d=>d.id),deployedExtensions:p,docsToken:r.docsToken??n.docsPublicToken()})}:void 0);if(n&&o){let d=o;for(let f of a)u.registerPrompt(f.id,{title:f.name,description:f.description},async()=>{let g=await n.getMcpPromptSkill(d,f.id,r);if(!g)throw new Error(`unknown prompt: ${f.id}`);return{description:g.description,messages:[{role:"user",content:{type:"text",text:(g.prompts??[]).join(`
|
|
893
|
+
|
|
894
|
+
`)}}]}})}return u.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:d,token:f}=await e(),g=await fetch(`${d}/v1/catalog/records`,{headers:{Authorization:`Bearer ${f}`,Accept:"application/json"}});if(!g.ok)throw new Error(`catalog fetch failed: ${g.status}`);return Se(await g.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:H.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".')}},async({recordType:d})=>{let{baseUrl:f,token:g}=await e(),b=await fetch(`${f}/v1/catalog/records/${encodeURIComponent(d)}`,{headers:{Authorization:`Bearer ${g}`,Accept:"application/json"}});if(b.status===404)throw new Error(`unknown record type "${d}" \u2014 list them with catalog_get.`);if(!b.ok)throw new Error(`record anatomy fetch failed: ${b.status}`);return Se(await b.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:H.array(H.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].')}},async({recordTypes:d})=>{let{baseUrl:f,token:g}=await e(),b=new URLSearchParams({types:d.join(",")}),v=await fetch(`${f}/v1/catalog/columns?${b}`,{headers:{Authorization:`Bearer ${g}`,Accept:"application/json"}});if(v.status===404)throw new Error(`none of those record types resolved: ${d.join(", ")} \u2014 list them with catalog_get.`);if(!v.ok)throw new Error(`common columns fetch failed: ${v.status}`);return Se(await v.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:d,token:f}=await e(),g=await fetch(`${d}/v1/catalog/census`,{headers:{Authorization:`Bearer ${f}`,Accept:"application/json"}});if(!g.ok)throw new Error(`catalog census failed: ${g.status}`);return Se(await g.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:H.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:H.enum(Am).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:H.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:d,kind:f,limit:g})=>{let{baseUrl:b,token:v}=await e(),x=new URLSearchParams({q:d});f&&x.set("kind",f),g!==void 0&&x.set("limit",String(g));let P=await fetch(`${b}/v1/catalog/objects?${x}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});if(!P.ok)throw new Error(`catalog object search failed: ${P.status}`);return Se(await P.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:H.enum(Am),externalId:H.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:d,externalId:f})=>{let{baseUrl:g,token:b}=await e(),v=await fetch(`${g}/v1/catalog/objects/${encodeURIComponent(d)}/${encodeURIComponent(f)}`,{headers:{Authorization:`Bearer ${b}`,Accept:"application/json"}});if(v.status===404)throw new Error(`unknown object ${d}:${f} \u2014 find it with search_catalog.`);if(!v.ok)throw new Error(`catalog object fetch failed: ${v.status}`);return Se(await v.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:H.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:H.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:d,limit:f})=>{let{baseUrl:g,token:b}=await e(),v=new URLSearchParams({q:d});f!==void 0&&v.set("limit",String(f));let x=await fetch(`${g}/v1/kb/search?${v}`,{headers:{Authorization:`Bearer ${b}`,Accept:"application/json"}});if(!x.ok)throw new Error(`kb search failed: ${x.status}`);return Se(await x.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:H.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:d})=>{let{baseUrl:f,token:g}=await e(),b=await fetch(`${f}/v1/kb/document/${encodeURIComponent(d)}`,{headers:{Authorization:`Bearer ${g}`,Accept:"application/json"}});if(!b.ok&&b.status!==404)throw new Error(`kb document fetch failed: ${b.status}`);return Se(await b.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:H.boolean().optional()}},async({recordsOnly:d})=>{let{baseUrl:f,token:g}=await e();return{content:[{type:"text",text:await kt({baseUrl:f,token:g,recordsOnly:d})}]}}),u.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:H.string(),event:H.string().optional(),template:H.enum(["require-field","enforce-format","blank"]).optional(),field:H.string().optional(),regex:H.string().optional(),source:H.string().optional(),id:H.string().optional()}},async d=>{let f=pr("hook",{recordType:d.recordType,event:d.event,template:d.template,field:d.field,regex:d.regex,source:d.source,id:d.id});return Se({path:f.relativePath,content:f.content})}),u.registerTool("scaffold_conduit",{title:"Scaffold a conduit",description:"Generate a conduit file body that bridges a canonical record from one source into another (does not write to disk; returns path + content).",inputSchema:{source:H.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:H.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:H.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:H.string().optional().describe("Target record type (defaults to the trigger record type)."),event:H.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:H.string().optional()}},async d=>{let f=pr("conduit",{recordType:d.recordType,source:d.source,to:d.to,toRecordType:d.toRecordType,event:d.event,id:d.id});return Se({path:f.relativePath,content:f.content})}),u.registerTool("mock_test",{title:"Dry-run an extension against samples",description:"Bundle the given source through the production sandbox and run it against samples/ fixtures.",inputSchema:{source:H.string().describe("The extension TS source."),samplesDir:H.string().optional().describe('Samples directory (default "samples").')}},async({source:d,samplesDir:f})=>{let g=Pm(process.cwd(),f??"samples"),b=await Wr(g),v=await io(d,b.map(P=>P.fixture)),x=v.filter(P=>!P.pass).length;return Se({total:v.length,passed:v.length-x,results:v})}),u.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:H.string(),recordType:H.string(),event:H.string(),source:H.string().describe('Adapter id or "standalone".'),sourceCode:H.string().describe("The verbatim extension TS."),extensionKind:H.string().optional()}},async d=>{let{baseUrl:f,token:g}=await e(),v=await new le({baseUrl:f,token:g}).deploy({id:d.id,recordType:d.recordType,event:d.event,source:d.source,sourceCode:d.sourceCode,extensionKind:d.extensionKind});return Se(v)}),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:H.string(),limit:H.number().int().positive().optional()}},async({id:d,limit:f})=>{let{baseUrl:g,token:b}=await e(),v=new le({baseUrl:g,token:b});return Se({id:d,logs:await v.logs(d,f)})}),u.registerTool("apps_list",{title:"List hosted apps",description:"Every hosted app on this instance with its slug, whether it's deployed, and its latest source revision. `sourceRev: null` means the app has no source of record yet (deployed dist only) \u2014 pull will 404 until something is pushed. GET /v1/apps.",inputSchema:{}},async()=>{let{baseUrl:d,token:f}=await e(),g=new le({baseUrl:d,token:f});return Se(await g.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:H.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:H.string().optional().describe("Display name (defaults to the slug)."),description:H.string().optional().describe("Short description.")}},async({slug:d,name:f,description:g})=>{let{baseUrl:b,token:v}=await e(),x=new le({baseUrl:b,token:v});return Se(await x.appsCreate({slug:d,name:f,description:g}))}),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:H.string().describe("App slug or id.")}},async({app:d})=>{let{baseUrl:f,token:g}=await e(),b=new le({baseUrl:f,token:g});return Se(await b.appsPull(d))}),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:H.string().describe("App slug or id."),files:H.record(H.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:H.string().optional().describe("Short note stored with the revision.")}},async({app:d,files:f,note:g})=>{let{baseUrl:b,token:v}=await e(),x=new le({baseUrl:b,token:v});return Se(await x.appsPush(d,f,{note:g}))}),u.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async d=>{let{baseUrl:f,token:g}=await e(),v=await(await fetch(`${f}/v1/catalog/records`,{headers:{Authorization:`Bearer ${g}`,Accept:"application/json"}})).text();return{contents:[{uri:d.href,mimeType:"application/json",text:v}]}}),u.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async d=>{let{baseUrl:f,token:g}=await e(),b=await kt({baseUrl:f,token:g});return{contents:[{uri:d.href,mimeType:"text/plain",text:b}]}}),u.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async d=>{let f=Pm(process.cwd(),"samples"),g=[];try{g=(await y0.readdir(f)).filter(v=>v.endsWith(".json"))}catch{g=[]}let b=await Wr(f);return{contents:[{uri:d.href,mimeType:"application/json",text:JSON.stringify({files:g,samples:b.map(v=>v.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 d=>{let f=await Im(),g=[];if(f){let{baseUrl:b,token:v}=await e();g=await f.listRecipesForSurface({surface:"mcp-authoring",baseUrl:b,token:v},r)}return{contents:[{uri:d.href,mimeType:"application/json",text:JSON.stringify({recipes:g})}]}}),u}async function _0(t={}){let e=await jm(t),r=new zs;await e.connect(r)}var Am,Cm,Om,Nm,zm,w0,v0,Dm=O(()=>{Sm();Tm();Js();no();Vr();oi();ui();Rm();Am=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];Om="turbobase-authoring",Nm="0.1.0";zm=["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"],w0=[...zm,...Em],v0=["catalog:///","types://all","samples:///","recipes:///"]});Js();no();Vr();oi();import{spawn as Um}from"node:child_process";import{promises as se}from"node:fs";import{homedir as S0}from"node:os";import{basename as Bm,dirname as Wn,join as cr,relative as vl,resolve as ae,sep as Mm}from"node:path";import{Command as $0}from"commander";ri();import{promises as Jl}from"node:fs";function Gl(t,e){return e===t?"same-type-merge":"different-type-mint"}var Zl=4;function si(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=ur(t,"id"),r=ur(t,"on"),n=ur(t,"source"),o=ur(t,"recordType"),s=/to\s*:\s*\{([^}]*)\}/.exec(t)?.[1]??"",i=ur(s,"source"),a=ur(s,"recordType"),l=/cycleBudget\s*:\s*(\d+)/.exec(t);if(!e||!n||!o||!i||!a)throw new Error("could not parse id/from.{source,recordType}/to.{source,recordType} \u2014 is it a reference-shape defineConduit({...})?");return{id:e,on:r,fromSource:n,fromRecordType:o,toSource:i,toRecordType:a,cycleBudget:l?Number(l[1]):Zl}}function ur(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function wg(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 Yl(t,e,r="fixture"){let n=e.name??r,o=[],s;try{s=si(t)}catch(l){return{fixtureName:n,conduit:_g(),guards:o,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],logs:[],error:l instanceof Error?l.message:String(l)}}let i=wg(e),a=Object.entries(e.atlasLinks??{}).map(([l,p])=>({key:l,resolved:p}));try{let l=await so(t),u=!!(await Gr(l,i,{member:"when",timeoutMs:200})).whenResult;o.push({name:"from.when",status:u?"passed":"failed",detail:u?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let d=e.hop??0;if(o.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${d} vs cycleBudget=${s.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),o.push({name:"opposite-direction-loop",status:"skipped-offline",detail:"reads committed conduit_event rows for the reverse leg \u2014 requires live sandbox state (skipped in fixture mode)"}),o.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!u)return{fixtureName:n,conduit:s,guards:o,whenPassed:u,atlasResolutions:a,wouldWriteBindings:[],logs:[]};let f=await Gr(l,i,{member:"transform",timeoutMs:200}),g=f.effects.logs,b=f.effects.result;if(!b||typeof b!="object")throw new Error(`conduit ${s.id} transform returned no result (expected { patch, createdFrom? })`);let v=b,x=Gl(s.fromRecordType,s.toRecordType),{wouldWriteBindings:P,masterAction:N}=vg(s,x,e);return{fixtureName:n,conduit:s,guards:o,whenPassed:u,atlasResolutions:a,transformResult:v,applyBranch:x,wouldWriteBindings:P,masterAction:N,logs:g}}catch(l){return{fixtureName:n,conduit:s,guards:o,whenPassed:!1,atlasResolutions:a,wouldWriteBindings:[],logs:[],error:l instanceof Error?l.message:String(l)}}}function vg(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 _g(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",cycleBudget:Zl}}async function Ql(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 Xl(t){let e=await Jl.readFile(t,"utf8");return JSON.parse(e)}function ed(t){return Jl.readFile(t,"utf8")}function td(t,e){let r=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;if(!e)return t.whenPassed?`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`:`replay ${t.fixtureName} [${r.id}]: WHEN-FAILED (conduit short-circuited)`;let n=[];n.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),n.push(`conduit: ${r.id}`),n.push(`route: ${r.fromSource}.${r.fromRecordType} \u2192 ${r.toSource}.${r.toRecordType}${r.on?` on=${r.on}`:""}`),n.push(""),n.push("guards (dispatch order):");for(let o of t.guards){let s=o.status==="passed"?"\u2713":o.status==="failed"?"\u2717":"\u2298";n.push(` ${s} ${o.name} [${o.status}] \u2014 ${o.detail}`)}if(n.push(""),n.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)n.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let o of t.atlasResolutions)n.push(` ${o.key} \u2192 ${o.resolved===null?"null (no Atlas link \u2014 noted)":o.resolved}`);if(!t.whenPassed)return n.push(""),n.push("transform: SKIPPED (from.when gate did not fire)."),n.join(`
|
|
895
|
+
`);if(n.push(""),n.push("transform \u2192 patch:"),n.push(Sg(JSON.stringify(t.transformResult?.patch??{},null,2)," ")),t.transformResult?.createdFrom&&n.push(` createdFrom: ${JSON.stringify(t.transformResult.createdFrom)}`),t.logs.length>0){n.push(""),n.push("conduit logs:");for(let o of t.logs)n.push(` [${o.level}] ${o.message}${o.meta?` ${JSON.stringify(o.meta)}`:""}`)}n.push(""),n.push(`apply-branch: ${t.applyBranch}`),n.push(` ${t.masterAction}`),n.push(""),n.push("bindings that WOULD be written (txn_source_link):");for(let o of t.wouldWriteBindings)n.push(` ${o.source} role=${o.role} external_id=${o.externalId??"null"} \u2014 ${o.why}`);return n.join(`
|
|
896
|
+
`)}function Sg(t,e){return t.split(`
|
|
897
|
+
`).map(r=>e+r).join(`
|
|
898
|
+
`)}var $g="2026-01-01",rd="2026-01-01T00:00:00.000Z";function kg(t,e){let r=t.trim().toLowerCase();return r==="boolean"||r==="bool"?!1:r==="smallint"||r==="integer"||r==="int"||r==="int2"||r==="int4"||r==="int8"||r==="bigint"||r==="serial"||r==="bigserial"?1:r==="numeric"||r==="decimal"||r==="real"||r==="double precision"||r==="float4"||r==="float8"||r==="money"?0:r==="date"?$g:r.startsWith("timestamp")?rd:r.startsWith("time")?"00:00:00":r==="json"||r==="jsonb"?e&&/^cf_[a-z]{2}_/.test(e)?1074:e==="raw"||e==="attrs"?{id:"1074",lastModifiedDate:rd}:{}:r==="uuid"?"00000000-0000-0000-0000-000000000000":r==="array"||r.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function xg(t){let e={};for(let r of t.columns)e[r.name]=kg(r.pgType,r.name);return e}function Tg(t,e={}){let r=e.event??"before_save";return{name:`${t.recordType} ${r} (generated)`,context:{recordType:t.recordType,event:r,source:t.source,payload:xg(t)},expect:e.expect??"pass"}}function nd(t,e={}){return t.map(r=>({recordType:r.recordType,fixture:Tg(r,e)}))}import{promises as od}from"node:fs";import{join as sd,relative as Eg,sep as Rg}from"node:path";var Pg=67324752,Ag=33639248,Cg=101010256,Ig=(()=>{let t=new Uint32Array(256);for(let e=0;e<256;e++){let r=e;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;t[e]=r>>>0}return t})();function Og(t){let e=4294967295;for(let r=0;r<t.length;r++)e=Ig[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}async function Ng(t){let e=[];async function r(n){let o=await od.readdir(n,{withFileTypes:!0});for(let s of o){let i=sd(n,s.name);s.isDirectory()?await r(i):s.isFile()&&e.push(Eg(t,i).split(Rg).join("/"))}}return await r(t),e.sort(),e}async function id(t){let e=await Ng(t),r=[],n=[],o=0;for(let a of e){let l=Buffer.from(a,"utf8"),p=await od.readFile(sd(t,a)),u=Og(p),d=Buffer.alloc(30+l.length);d.writeUInt32LE(Pg,0),d.writeUInt16LE(20,4),d.writeUInt16LE(0,6),d.writeUInt16LE(0,8),d.writeUInt32LE(u,14),d.writeUInt32LE(p.length,18),d.writeUInt32LE(p.length,22),d.writeUInt16LE(l.length,26),l.copy(d,30),r.push(d,p);let f=Buffer.alloc(46+l.length);f.writeUInt32LE(Ag,0),f.writeUInt16LE(20,4),f.writeUInt16LE(20,6),f.writeUInt16LE(0,10),f.writeUInt32LE(u,16),f.writeUInt32LE(p.length,20),f.writeUInt32LE(p.length,24),f.writeUInt16LE(l.length,28),f.writeUInt32LE(o,42),l.copy(f,46),n.push(f),o+=d.length+p.length}let s=Buffer.concat(n),i=Buffer.alloc(22);return i.writeUInt32LE(Cg,0),i.writeUInt16LE(e.length,8),i.writeUInt16LE(e.length,10),i.writeUInt32LE(s.length,12),i.writeUInt32LE(o,16),{buffer:Buffer.concat([...r,s,i]),fileCount:e.length}}function jg(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":"hook"}function ao(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function zg(t){let e=ad(t,"from"),r=ad(t,"to");return{fromSource:e?ao(e,"source"):void 0,fromRecordType:e?ao(e,"recordType"):void 0,toSource:r?ao(r,"source"):void 0,toRecordType:r?ao(r,"recordType"):void 0}}function ad(t,e){let r=new RegExp(`\\b${e}\\s*:\\s*\\{`).exec(t);if(!r)return null;let n=0,o=r.index+r[0].length-1;for(let s=o;s<t.length;s+=1){let i=t[s];if(i==="{")n+=1;else if(i==="}"&&(n-=1,n===0))return t.slice(o+1,s)}return null}function Lg(t){let e=/idempotencyKey\s*:/.exec(t);if(!e)return null;let r=e.index+e[0].length,n=0,o=null,s=r;for(;s<t.length;s+=1){let l=t[s];if(o){l==="\\"?s+=1:l===o&&(o=null);continue}if(l==="'"||l==='"'||l==="`"){o=l;continue}if(l==="("||l==="{"||l==="[")n+=1;else if(l===")"||l==="}"||l==="]"){if(n===0)break;n-=1}else if(l===","&&n===0)break}let i=t.slice(r,s),a=i.indexOf("=>");return a>=0?i.slice(a+2):i}function Dg(t,e){let r=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return r?Number(r[1]):void 0}function Mg(t){return/\bcreatedFrom\b/.test(t)}function cd(t){let e=jg(t),r=[];if(e==="hook")return{kind:e,warnings:r};let{fromSource:n,toSource:o,fromRecordType:s,toRecordType:i}=zg(t);n&&o&&n===o&&r.push({rule:"same-source-conduit",message:`from.source and to.source are both '${n}' \u2014 a conduit that doesn't cross sources isn't a conduit.`,fix:`Make 'to.source' a DIFFERENT source than 'from.source', or rewrite this as a hook (\`turbobase ext new hook --record ${s??"<type>"}\`) \u2014 a same-source transform belongs on the write path, not the cross-source bridge.`});let a=Lg(t);if(a!==null){let p=/\bexternalId\b/.test(a),u=/\bfromSource\b/.test(a);!p&&!u&&r.push({rule:"weak-idempotency-key",message:"idempotencyKey omits both ctx.externalId and ctx.fromSource \u2014 two distinct re-fires (different records, or the same record from different sources) collapse onto one conduit_event ledger row and one of them is silently dropped as a duplicate.",fix:"Include `ctx.externalId` (and, for multi-source triggers, `ctx.fromSource`) in the key, e.g. `idempotencyKey: (ctx) => `${ctx.fromSource}:${ctx.externalId}``."})}s&&i&&s!==i&&!Mg(t)&&r.push({rule:"missing-created-from",message:`this conduit bridges '${s}' \u2192 '${i}' (different record types) but its transform never returns 'createdFrom' \u2014 the created ${i} won't carry a lineage pointer back to its origin, so the reverse leg can't find it.`,fix:"Return `createdFrom: { source: ctx.fromSource, recordType: ctx.recordType, externalId: ctx.externalId }` from the transform so the counterpart is bound to the master by construction."});let l=Dg(t,"cycleBudget");return l!==void 0&&(l<1?r.push({rule:"cycle-budget-too-low",message:`cycleBudget=${l} is below 1 \u2014 the cycle fuse trips before the first hop (hop 0 >= budget), so this conduit can never fire.`,fix:"Set cycleBudget to at least 1 (the engine default is 4, a sane range is 1\u201320)."}):l>20&&r.push({rule:"cycle-budget-too-high",message:`cycleBudget=${l} is far above the 20 ceiling \u2014 the max-hop safety fuse is effectively disarmed, so a misconfigured conduit pair can bounce a record dozens of times before anything stops it.`,fix:"Lower cycleBudget into the 1\u201320 range (the engine default is 4); a legitimate chain rarely needs more than a handful of hops."})),{kind:e,warnings:r}}function ld(t,e,r={}){let n=r.warn??(a=>a),o=r.ok??(a=>a),s=r.dim??(a=>a),i=[];if(i.push(`lint: ${t} (${e.kind})`),e.warnings.length===0)return i.push(` ${o("ok")} \u2014 no warnings.`),i.join(`
|
|
899
|
+
`);for(let a of e.warnings)i.push(` ${n("WARN")} ${s(`[${a.rule}]`)} ${a.message}`),i.push(` ${s("\u2192 fix:")} ${a.fix}`);return i.push(`
|
|
900
|
+
lint: ${n(`${e.warnings.length} warning(s).`)}`),i.join(`
|
|
901
|
+
`)}function dd(t){return t.cases.filter(e=>e.status==="failed").length}function Zr(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function qg(t){let e=dd(t),r=[];r.push('<?xml version="1.0" encoding="UTF-8"?>'),r.push(`<testsuite name="${Zr(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let n of t.cases){let o=` <testcase name="${Zr(n.name)}"`;if(n.status==="passed"){r.push(`${o} />`);continue}r.push(`${o}>`);let s=n.detail??"failed",i=n.type?` type="${Zr(n.type)}"`:"";r.push(` <failure${i} message="${Zr(s)}">${Zr(s)}</failure>`),r.push(" </testcase>")}return r.push("</testsuite>"),`${r.join(`
|
|
902
|
+
`)}
|
|
903
|
+
`}function Ug(t){let e={suite:t.name,tests:t.cases.length,failures:dd(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
|
|
904
|
+
`}function co(t,e){return e==="junit"?qg(t):Ug(t)}var ze={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"},Ue={hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",clearLine:"\x1B[2K",clearToEnd:"\x1B[0J",col0:"\r",cursorUp:t=>`\x1B[${t}A`},lo=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ge={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},ud=/\x1b\[[0-9;]*m/g;function yt(t){return t.replace(ud,"").length}function ii(t,e){return e<=0?1:Math.max(1,Math.ceil(yt(t)/e))}function Bg(){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 ai=Bg();function Be(){return ai}function ci(t){ai=t}function Kt(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function We(t,e){return ai?`${t}${e}${ze.reset}`:e}var R={bold:t=>We(ze.bold,t),dim:t=>We(ze.dim,t),red:t=>We(ze.red,t),green:t=>We(ze.green,t),yellow:t=>We(ze.yellow,t),blue:t=>We(ze.blue,t),magenta:t=>We(ze.magenta,t),cyan:t=>We(ze.cyan,t),grey:t=>We(ze.grey,t)};var Fe={success:t=>`${R.green("\u2713")} ${t}`,error:t=>`${R.red("\u2716")} ${t}`,warn:t=>`${R.yellow("\u26A0")} ${t}`,info:t=>`${R.dim("\xB7")} ${t}`,step:t=>`${R.cyan("\u25B8")} ${t}`},Tt={add:t=>R.green(`+ ${t}`),change:t=>R.yellow(`~ ${t}`),destroy:t=>R.red(`- ${t}`)},Fg=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),Hg=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),Kg=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function Yr(t){let e=t.toLowerCase();return Fg.has(e)?R.green(t):Hg.has(e)?R.red(t):Kg.has(e)?R.yellow(t):t}function Et(t,e=[]){let r=Math.max(yt(t),...e.map(yt),0),n=r+2,o=R.cyan(Ge.v),s=a=>` ${a}${" ".repeat(r-yt(a))} `,i=[R.cyan(`${Ge.tl}${Ge.h.repeat(n)}${Ge.tr}`),`${o}${R.bold(s(t))}${o}`];if(e.length){i.push(`${R.cyan(Ge.ml)}${R.dim(Ge.h.repeat(n))}${R.cyan(Ge.mr)}`);for(let a of e)i.push(`${o}${s(a)}${o}`)}return i.push(R.cyan(`${Ge.bl}${Ge.h.repeat(n)}${Ge.br}`)),i.join(`
|
|
905
|
+
`)}function uo(t,e={}){let r=e.indent??" ",n=e.gap??" ",o=e.head?[e.head,...t]:t,s=Math.max(0,...o.map(p=>p.length)),i=[];for(let p=0;p<s;p+=1)i[p]=Math.max(0,...o.map(u=>yt(u[p]??"")));let a=p=>{let u=p.map((d,f)=>{let g=d??"";return f===p.length-1?g:g+" ".repeat(Math.max(0,i[f]-yt(g)))});return r+u.join(n)},l=[];e.head&&(l.push(a(e.head.map(p=>R.bold(p)))),l.push(a(e.head.map((p,u)=>R.dim("\u2500".repeat(i[u]??yt(p)))))));for(let p of t)l.push(a(p));return l.join(`
|
|
906
|
+
`)}function li(t="extension authoring CLI"){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`${Be()?e.map(n=>We(ze.cyan,n)).join(`
|
|
907
|
+
`):e.join(`
|
|
908
|
+
`)}
|
|
909
|
+
${R.dim(` ${t}`)}`}var Qr=t=>{process.stderr.write(t)};function di(){return Be()&&process.stderr.isTTY===!0}async function pe(t,e){let r=di(),n=0,o;r&&(Qr(Ue.hideCursor),o=setInterval(()=>{Qr(`${Ue.col0}${Ue.clearLine}${R.magenta(lo[n++%lo.length])} ${t}`)},80));let s=()=>{o&&clearInterval(o),r&&Qr(`${Ue.col0}${Ue.clearLine}${Ue.showCursor}`)};try{let i=await e();return s(),r&&Qr(`${Fe.success(t)}
|
|
910
|
+
`),i}catch(i){throw s(),r&&Qr(`${Fe.error(t)}
|
|
911
|
+
`),i}}function Vt(t,e,r={}){return new Promise((n,o)=>{let s=e.findIndex(v=>!v.disabled);if(s===-1){o(new Error("no selectable options"));return}let i=r.defaultIndex!==void 0&&!e[r.defaultIndex]?.disabled?r.defaultIndex:s,a=v=>{process.stderr.write(v)},l=process.stdin,p=l.isRaw;l.setRawMode?.(!0),l.resume(),a(`${R.bold(R.cyan("?"))} ${R.bold(t)}
|
|
912
|
+
`),a(`${R.dim(" (\u2191/\u2193 to move, enter to select, ctrl+c to abort)")}
|
|
913
|
+
`),a(Ue.hideCursor);let u=0,d=()=>{let v=process.stderr.columns??process.stdout.columns??80;u>0&&(a(Ue.cursorUp(u)),a(Ue.clearToEnd));let x=0;for(let P=0;P<e.length;P+=1){let N=e[P],D=P===i,Q=D?R.cyan("\u25B6"):" ",U=N.disabled?R.grey(N.label):D?R.bold(R.cyan(N.label)):N.label,je=N.description?` ${R.dim(N.description)}`:"",Ee=` ${Q} ${U}${je}`;a(`\r${Ee}
|
|
914
|
+
`),x+=ii(Ee,v)}u=x},f=()=>{l.removeListener("data",b),l.setRawMode?.(p??!1),l.pause(),a(Ue.showCursor)},g=v=>{let x=i;for(let P=0;P<e.length;P+=1)if(x=(x+v+e.length)%e.length,!e[x].disabled){i=x;return}},b=v=>{let x=v.toString("utf8");if(x===""||x==="q"){f(),a(`
|
|
915
|
+
`),o(new Error("aborted"));return}if(x==="\r"||x===`
|
|
916
|
+
`){let N=e[i];if(N.disabled)return;f(),n(N.value);return}if(x==="\x1B[A"||x==="k"){g(-1),d();return}if(x==="\x1B[B"||x==="j"){g(1),d();return}let P=Number(x);Number.isFinite(P)&&P>=1&&P<=e.length&&!e[P-1].disabled&&(i=P-1,d())};l.on("data",b),d()})}function fd(t,e){return`${Yr(t)}${" ".repeat(Math.max(0,e-t.length))}`}var Gg=t=>new Promise(e=>setTimeout(e,t));function pd(t){let e=t.toRecordType?`${t.toSource}/${t.toRecordType}`:t.toSource,r=t.reason?` reason="${t.reason}"`:"",n=t.fromExternalId?` ext=${t.fromExternalId}`:"",o=t.toMasterTable&&t.toMasterRowId?` master=${t.toMasterTable}/${t.toMasterRowId}`:"";return`[${t.updatedAt}] ${fd(t.state,9)} ${t.conduitId} \u2192 ${e}${n} hop=${t.hop}${o}${r}`}async function hd(t,e,r={}){let n=r.sink??(u=>{process.stdout.write(`${u}
|
|
917
|
+
`)}),o=r.sleep??Gg,s=r.intervalMs??2e3,i=await t.conduitEvents(e,{limit:r.limit??100});if(i.length===0&&!r.follow)return n(`logs: no conduit_event rows for ${e}.`),0;let a=0,l="";for(let u of[...i].reverse())n(pd(u)),a+=1,u.updatedAt>l&&(l=u.updatedAt);if(!r.follow)return a;let p=r.maxPolls??Number.POSITIVE_INFINITY;for(let u=0;u<p;u+=1){await o(s);let d=await t.conduitEvents(e,{since:l||void 0,limit:200});for(let f of[...d].reverse())n(pd(f)),a+=1,f.updatedAt>l&&(l=f.updatedAt)}return a}function Wg(t){let e=t.externalId??"\u2014",r=t.createdByConduit?` via=${t.createdByConduit}`:"",n=t.lastError?` last_error="${t.lastError}"`:"";return`${t.id} ${fd(t.writeStatus,9)} ${t.sourceSystem}/${e} role=${t.role} master=${t.masterTable}/${t.masterRowId}${r}${n}`}async function md(t,e={}){let r=e.sink??(o=>{process.stdout.write(`${o}
|
|
918
|
+
`)});if(e.retry){let o=await t.retryBinding(e.retry);return r(`binding: re-enqueued fan-out for ${o.id} \u2192 ${o.sourceSystem} (master ${o.masterTable}/${o.masterRowId}).`),{mode:"retry",id:o.id,retried:o.retried}}let n=await t.bindings({status:e.status,limit:e.limit});if(n.length===0)return r(e.status?`binding: no bindings with write_status='${e.status}'.`:"binding: no bindings."),{mode:"list",count:0};for(let o of n)r(Wg(o));return r(`
|
|
919
|
+
binding: ${n.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:n.length}}ui();function yd(t){return t.learningIngestError?{level:"warn",message:`warning: learning ingest was not queued (${t.learningIngestError}). The version is live, but the findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT read. Re-deploy to retry.`}:t.learningIngestTaskId?{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}).`}:null}var Qg=[".mcp.json"];function wd(t,e=Qg){let r=i=>i.replace(/^\//,""),n=new Set(t.split(`
|
|
920
|
+
`).map(i=>i.trim()).filter(i=>i!==""&&!i.startsWith("#")).map(r)),o=e.filter(i=>!n.has(r(i)));return o.length===0?null:`${t===""||t.endsWith(`
|
|
921
|
+
`)?t:`${t}
|
|
922
|
+
`}
|
|
923
|
+
# Added by the TurboBase scaffold.
|
|
924
|
+
${o.join(`
|
|
925
|
+
`)}
|
|
926
|
+
`}var Xg=`# TurboBase Extensions \u2014 extension project
|
|
927
|
+
|
|
928
|
+
This directory authors **TurboBase extensions** (hooks today; conduits later)
|
|
929
|
+
against a live instance. The \`turbobase\` CLI is the engine; Claude Code drives it
|
|
930
|
+
through the local MCP server (\`.mcp.json\`) and the skills under \`.claude/skills/\`.
|
|
931
|
+
|
|
932
|
+
## Layout
|
|
933
|
+
|
|
934
|
+
- \`hooks/\` \u2014 your hook files (one self-contained \`defineHook({...})\` per file).
|
|
935
|
+
- \`samples/\` \u2014 JSON fixtures \`turbobase ext test\` runs each hook against.
|
|
936
|
+
- \`types.ts\` \u2014 generated record + PostgREST types (\`turbobase project types\`); refreshed
|
|
937
|
+
automatically on each Claude Code session start.
|
|
938
|
+
|
|
939
|
+
## Workflow
|
|
940
|
+
|
|
941
|
+
1. \`turbobase auth login\` \u2014 sign in as an instance admin; stores a personal access token (PAT).
|
|
942
|
+
2. \`turbobase project types\` \u2014 regenerate \`types.ts\` from the instance catalog.
|
|
943
|
+
3. \`turbobase ext new hook --record=<type> --event=before_save --field=<name>\` \u2014 scaffold.
|
|
944
|
+
4. Edit the hook; add fixtures under \`samples/\`.
|
|
945
|
+
5. \`turbobase ext test hooks/<...>.ts\` \u2014 dry-run against the fixtures (same isolate as prod).
|
|
946
|
+
6. \`turbobase ext deploy hooks/<...>.ts\` \u2014 deploy (lands active).
|
|
947
|
+
7. \`turbobase ext logs <id>\` \u2014 tail the deployed hook's logs.
|
|
948
|
+
|
|
949
|
+
## Rules
|
|
950
|
+
|
|
951
|
+
- A hook is **pure and credentials-free**: no secrets, no network, no Node
|
|
952
|
+
builtins. The sandbox fences every import except \`@turbobase/extensions\`.
|
|
953
|
+
- One concern per file. Do not factor shared logic into a \`lib/\` \u2014 inline it.
|
|
954
|
+
|
|
955
|
+
## Record what you learn about THIS customer \u2014 continuously
|
|
956
|
+
|
|
957
|
+
**\`INSTANCE-LEARNINGS.md\`** is the standing write-up of how this instance's
|
|
958
|
+
source system is actually set up \u2014 which is exactly the knowledge a hook has to
|
|
959
|
+
be right about: which field a rule must really read, which records arrive with
|
|
960
|
+
it empty, what a status code means in this account, whether a link lives on the
|
|
961
|
+
header or only on the line. It feeds the knowledge base, so every claim in it
|
|
962
|
+
carries the record ids it was verified against.
|
|
963
|
+
|
|
964
|
+
Add to it whenever you establish a fact about the CUSTOMER'S SETUP that was not
|
|
965
|
+
already written down \u2014 especially when real rows contradicted an assumption
|
|
966
|
+
(yours, the catalog's, the knowledge base's, or a field label's). A hook you had
|
|
967
|
+
to write defensively is a fact about the data worth recording, not just a
|
|
968
|
+
\`?? null\`.
|
|
969
|
+
|
|
970
|
+
**Both halves, in the same change.** The numbered sections hold the finding;
|
|
971
|
+
\`## Suggested KB edits\` holds what to DO about it \u2014 the knowledge-base page to
|
|
972
|
+
change, or "new page for \`<record>\`". When the data contradicts a PUBLISHED
|
|
973
|
+
knowledge-base claim, the row goes in \`## Knowledge-base corrections\` instead
|
|
974
|
+
(KB claim / Live value / Verdict); that is the only way a stale published fact
|
|
975
|
+
gets caught. A finding added without its entry is half-done. Neither waits for
|
|
976
|
+
the end of a task, and neither waits to be asked.
|
|
977
|
+
|
|
978
|
+
## Feed problems back to TurboBase \u2014 continuously
|
|
979
|
+
|
|
980
|
+
Keep **\`TURBOBASE-FEEDBACK.md\`** up to date AS YOU WORK. It is the channel to the
|
|
981
|
+
TurboBase product team, and the entries worth most are the ones written the
|
|
982
|
+
moment they cost you time \u2014 they evaporate from memory otherwise.
|
|
983
|
+
|
|
984
|
+
Append an entry whenever the PLATFORM itself (not your own code) causes trouble:
|
|
985
|
+
a fixture shape that did not match the live event payload, an import the sandbox
|
|
986
|
+
fenced with no hint of what to use instead, a hook that passed \`turbobase ext test\`
|
|
987
|
+
and behaved differently deployed, a misleading CLI error, a type the generator
|
|
988
|
+
did not emit, a confusing default. For each, note: what you expected, what
|
|
989
|
+
happened, the concrete cost, and the fix or workaround. Skip anything that is
|
|
990
|
+
just your own bug. Keep \`## What would have helped most, in order\` ranked \u2014 the
|
|
991
|
+
order is the signal, and it is the part the product team reads first.
|
|
992
|
+
|
|
993
|
+
Do this WITHOUT being asked \u2014 treat it as part of finishing a task, like
|
|
994
|
+
updating a test. It is checked into the repo so the whole team sees it.
|
|
995
|
+
`,ey=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)+`
|
|
996
|
+
`;function ty(t){return`---
|
|
997
|
+
name: generate-types
|
|
998
|
+
description: Regenerate ${t} from the signed-in instance's catalog. Use before authoring or whenever the schema may have changed.
|
|
999
|
+
---
|
|
1000
|
+
|
|
1001
|
+
Run \`turbobase project types -o ${t}\` to fetch the instance's record shapes
|
|
1002
|
+
(/v1/catalog/records) and PostgREST operations (/v1/catalog/openapi.json) and
|
|
1003
|
+
write \`${t}\`. Import the generated record interfaces for typed rows.
|
|
1004
|
+
|
|
1005
|
+
The OpenAPI half is cookie-session-gated, so a headless run with a stored token
|
|
1006
|
+
degrades to record shapes only and says so \u2014 that is expected, not a failure.
|
|
1007
|
+
`}var ry=`---
|
|
1008
|
+
name: mock-test
|
|
1009
|
+
description: Dry-run a hook against samples/ fixtures using the production sandbox. Use after editing a hook, before deploy.
|
|
1010
|
+
---
|
|
1011
|
+
|
|
1012
|
+
Run \`turbobase ext test hooks/<file>.ts\`. It bundles the hook through the same
|
|
1013
|
+
self-contained-fence esbuild + isolated-vm the live runtime uses, then runs it
|
|
1014
|
+
against every \`samples/*.json\` fixture and reports pass/reject per sample. Add a
|
|
1015
|
+
fixture for each branch (a passing record and a rejecting record).
|
|
1016
|
+
`,ny=`---
|
|
1017
|
+
name: deploy
|
|
1018
|
+
description: Deploy a hook to your instance. Use only after mock-test is green.
|
|
1019
|
+
---
|
|
1020
|
+
|
|
1021
|
+
Run \`turbobase ext deploy hooks/<file>.ts\`. It POSTs the hook source to
|
|
1022
|
+
/v1/extensions with the stored admin PAT; the hook lands **active**. Re-deploying
|
|
1023
|
+
the same id overwrites it (idempotent). Tail with \`turbobase ext logs <id>\`.
|
|
1024
|
+
`;function oy(t){return`# ${t} \u2014 TurboBase app
|
|
1025
|
+
|
|
1026
|
+
This directory is a **hosted TurboBase app**: a Vite + React + TS SPA served
|
|
1027
|
+
same-origin by the instance at \`/a/${t}\`. The \`turbobase\` CLI ships it; you
|
|
1028
|
+
(Claude Code) reach the instance through the two MCP servers in \`.mcp.json\`.
|
|
1029
|
+
|
|
1030
|
+
## Know the instance before you write code
|
|
1031
|
+
|
|
1032
|
+
Ground first, code second \u2014 the instance already knows this business.
|
|
1033
|
+
|
|
1034
|
+
- **\`INSTANCE.md\`** \u2014 the grounding brief (source primer, record anatomy,
|
|
1035
|
+
knowledge-base retrieval), refreshed each session. READ IT FIRST. Once you
|
|
1036
|
+
know which records the app is about, widen it:
|
|
1037
|
+
\`turbobase project grounding --records purchaseOrder,itemReceipt -o INSTANCE.md\` \u2014
|
|
1038
|
+
the session hook keeps that focus on later refreshes.
|
|
1039
|
+
- \`record_anatomy\` (authoring MCP) \u2014 ONE record in depth: field meanings,
|
|
1040
|
+
sublists, gotchas, authored display contracts. Read it before building UI
|
|
1041
|
+
over a record.
|
|
1042
|
+
- \`search_documentation\` / \`read_document\` (authoring MCP) \u2014 the published
|
|
1043
|
+
knowledge base: how this business runs its processes. For a CUSTOM record
|
|
1044
|
+
the KB + \`search_catalog\`/\`explain_object\` are the only spec that exists.
|
|
1045
|
+
- \`list_records\` / \`get_record\` (data MCP) \u2014 real rows, through the signed-in
|
|
1046
|
+
user's row-level security. What you can't see here, the app can't see either.
|
|
1047
|
+
|
|
1048
|
+
Read the catalog BEFORE writing a query. A column that doesn't exist fails at
|
|
1049
|
+
runtime, not at build \u2014 \`npm run build\` will happily compile it. And RENDER
|
|
1050
|
+
display columns, not identifiers: \`src/types.ts\` marks each column's role and
|
|
1051
|
+
its id\u2194display twin ("identifier \u2014 render entity_name instead"). A table cell
|
|
1052
|
+
showing \`entity_id\` where \`entity_name\` exists is wrong.
|
|
1053
|
+
|
|
1054
|
+
## What the mirror does NOT look like
|
|
1055
|
+
|
|
1056
|
+
Five facts that produce a WORKING BUILD and a WRONG SCREEN. Each one fails
|
|
1057
|
+
silently \u2014 the query succeeds, the page renders, the data is absent or wrong.
|
|
1058
|
+
Check them before you trust a result.
|
|
1059
|
+
|
|
1060
|
+
1. **A \`jsonb\` custom field holds a BARE id, not \`{value, text}\`.**
|
|
1061
|
+
\`cf_ns_custrecord_vendor\` is \`1074\`, not \`{value: 1074, text: "FedEx"}\`.
|
|
1062
|
+
There is NO display twin for custom fields \u2014 resolve the id yourself. Build
|
|
1063
|
+
on the envelope assumption and every cell renders empty, which is
|
|
1064
|
+
indistinguishable from an empty table.
|
|
1065
|
+
2. **The obvious lookup table is often the wrong one.** A List/Record field
|
|
1066
|
+
named after a custom record may point somewhere else entirely (a carrier
|
|
1067
|
+
field pointing at \`entity\` \u2014 vendors \u2014 not \`customrecord_carrier\`). Confirm
|
|
1068
|
+
the target by checking that real ids resolve, not by the name.
|
|
1069
|
+
3. **Some tables mix kinds in one id space.** \`entity\` holds customers AND
|
|
1070
|
+
vendors; the same id is a valid row of each. \`order\` holds every connector's
|
|
1071
|
+
orders. The catalog marks these (\`sharedTable\`) \u2014 apply the discriminator
|
|
1072
|
+
(\`entity_type=eq.vendor\`, \`source_system=eq.netsuite\`) or you will label a
|
|
1073
|
+
vendor with a customer's name.
|
|
1074
|
+
4. **\`created_at\` / \`updated_at\` / \`synced_at\` / \`last_modified_pg\` are MIRROR
|
|
1075
|
+
timestamps** \u2014 when TurboBase wrote the row. After a bulk sync they are
|
|
1076
|
+
identical across the table, so ordering by one gives sync batch order, not
|
|
1077
|
+
business order. Use \`source_modified\`, or the source's own date in \`raw\`.
|
|
1078
|
+
5. **A column can exist and be empty on every row.** \`currency_name\` and
|
|
1079
|
+
\`subsidiary_name\` are often NULL while \`currency_id\` / \`subsidiary_id\` carry
|
|
1080
|
+
the data. Check one real row before rendering a column, not just the schema.
|
|
1081
|
+
|
|
1082
|
+
## Reading efficiently (and not tripping the edge)
|
|
1083
|
+
|
|
1084
|
+
- **Never select bare \`raw\`** on a wide table \u2014 it is the entire source
|
|
1085
|
+
document and the response can be big enough to fail at the edge (502).
|
|
1086
|
+
Project the ONE key you need: \`select=external_id,ship:raw->custbody_x\`.
|
|
1087
|
+
- **Cap your concurrency.** A page that fans out ~25 parallel reads on load will
|
|
1088
|
+
trip rate limiting (HTTP 429). Keep a handful in flight, space them slightly,
|
|
1089
|
+
and retry on 429 honouring \`retry_after\`. Load what the first screen needs;
|
|
1090
|
+
fetch the rest on demand.
|
|
1091
|
+
- **PostgREST fails the WHOLE request on one unknown column** (\`42703\`), so a
|
|
1092
|
+
single wrong name in a \`select\` loses the entire table. Transaction tables are
|
|
1093
|
+
NOT uniform \u2014 \`memo\`, \`total\`, \`created_from_id\`, even \`pg_row_id\` are missing
|
|
1094
|
+
from some. Verify each column against the catalog per table rather than
|
|
1095
|
+
assuming a shared shape.
|
|
1096
|
+
|
|
1097
|
+
## Layout
|
|
1098
|
+
|
|
1099
|
+
- \`src/App.tsx\` \u2014 the app. Start here.
|
|
1100
|
+
- \`src/lib/turbobase.ts\` \u2014 the auth-wired client. Don't rewrite it; import from it.
|
|
1101
|
+
- \`src/types.ts\` \u2014 generated record types (\`turbobase project types -o src/types.ts\`),
|
|
1102
|
+
refreshed at the start of every Claude Code session.
|
|
1103
|
+
- \`INSTANCE.md\` \u2014 the grounding brief (\`turbobase project grounding\`), refreshed
|
|
1104
|
+
each session; instance-specific, don't hand-edit.
|
|
1105
|
+
- \`vite.config.ts\` \u2014 \`base\` is pinned to \`/a/${t}/\` and MUST stay that way, or
|
|
1106
|
+
every asset 404s and the page renders blank with no console error. The
|
|
1107
|
+
\`server.proxy\` block is dev-only.
|
|
1108
|
+
|
|
1109
|
+
## Reads and writes are different surfaces
|
|
1110
|
+
|
|
1111
|
+
- **Read** with \`select('<table>?select=...')\` \u2192 PostgREST, row-level-security scoped.
|
|
1112
|
+
- **Write** with \`write('<recordType>', { parent, lines })\` \u2192 \`POST /v1/data/:recordType\`,
|
|
1113
|
+
the canonical write boundary. **Never** write a table directly through PostgREST.
|
|
1114
|
+
|
|
1115
|
+
Both are same-origin and carry the session cookie. There are no app-owned keys,
|
|
1116
|
+
no Bearer tokens to manage, and no sign-in page to build \u2014 the instance handles
|
|
1117
|
+
auth before your SPA loads.
|
|
1118
|
+
|
|
1119
|
+
**Reading data yourself, without a browser.** The PAT in \`.mcp.json\` authenticates
|
|
1120
|
+
the authoring MCP, but PostgREST rejects it outright (\`PGRST301 \u2026 Expected 3
|
|
1121
|
+
parts; got 1\`) \u2014 it is an opaque bearer, not a JWT. To read rows from a script or
|
|
1122
|
+
a terminal, trade it for a short-lived session first:
|
|
1123
|
+
|
|
1124
|
+
\`\`\`sh
|
|
1125
|
+
curl -sX POST "$INSTANCE/auth/pat-exchange" -H "Authorization: Bearer $PAT"
|
|
1126
|
+
# \u2192 { "token": "<15-min session JWT>", ... }
|
|
1127
|
+
curl -s "$INSTANCE/rest/v1/<table>?select=..." \\
|
|
1128
|
+
-H "Authorization: Bearer $SESSION" -H "apikey: $SESSION"
|
|
1129
|
+
\`\`\`
|
|
1130
|
+
|
|
1131
|
+
The PAT must carry the \`data:read\` scope (Settings \u203A Tokens) \u2014 it is opt-in, so
|
|
1132
|
+
a token minted without it gets \`403 insufficient_scope\`. PostgREST wants the JWT
|
|
1133
|
+
in BOTH the \`Authorization\` and \`apikey\` positions.
|
|
1134
|
+
|
|
1135
|
+
**\`permission denied for table <x>\` usually means NOT SIGNED IN.** With no
|
|
1136
|
+
session, PostgREST answers as the anonymous role and every table denies \u2014 it
|
|
1137
|
+
reads like an RLS problem and is not one. Check the session before the grants.
|
|
1138
|
+
|
|
1139
|
+
## Workflow
|
|
1140
|
+
|
|
1141
|
+
1. \`npm install && npm run dev\` \u2014 the app is at **http://localhost:3000/a/${t}/**,
|
|
1142
|
+
NOT \`/\` (Vite serves under \`base\`; \`/\` 302s there). The dev server proxies
|
|
1143
|
+
\`/rest\`, \`/realtime\`, \`/v1\`, \`/auth\`, \`/login\` and \`/_app\` to the instance, so
|
|
1144
|
+
localhost behaves same-origin. Sign in through the proxy on first load.
|
|
1145
|
+
(\`/_app\` carries the sign-in page's own JS/CSS \u2014 without it the login form
|
|
1146
|
+
renders but never hydrates, and you stay signed out silently.)
|
|
1147
|
+
2. Build the thing. Verify in the browser \u2014 a green \`npm run build\` proves the
|
|
1148
|
+
code is well-formed, not that it runs.
|
|
1149
|
+
3. \`turbobase apps push ${t} .\` \u2014 record the source on the instance (source of
|
|
1150
|
+
record lives there, not on this laptop). Nothing goes live.
|
|
1151
|
+
4. \`turbobase apps deploy ${t}\` \u2014 build + go live at \`/a/${t}\`.
|
|
1152
|
+
|
|
1153
|
+
Push and deploy are separate on purpose: push often while iterating, deploy when
|
|
1154
|
+
it's ready.
|
|
1155
|
+
|
|
1156
|
+
## Rules
|
|
1157
|
+
|
|
1158
|
+
- \`.mcp.json\` holds a live access token. It is gitignored \u2014 keep it that way.
|
|
1159
|
+
- Don't add a sign-in page, a login route, or token handling. The instance owns auth.
|
|
1160
|
+
- Don't hardcode an instance hostname; the app is served same-origin.
|
|
1161
|
+
|
|
1162
|
+
## Record what you learn about THIS customer \u2014 continuously
|
|
1163
|
+
|
|
1164
|
+
**\`INSTANCE-LEARNINGS.md\`** is the standing write-up of how this instance's
|
|
1165
|
+
source system is actually set up: which custom field carries which link, which
|
|
1166
|
+
half of a paired document holds the parent id, where a parent id really lives,
|
|
1167
|
+
what a custom record's columns mean, which column is present on every row and
|
|
1168
|
+
populated on none. It feeds the knowledge base, so every claim in it carries the
|
|
1169
|
+
record ids it was verified against.
|
|
1170
|
+
|
|
1171
|
+
Add to it whenever you establish a fact about the CUSTOMER'S SETUP that was not
|
|
1172
|
+
already written down \u2014 especially when the data contradicted an assumption
|
|
1173
|
+
(yours, the catalog's, the knowledge base's, or a field label's). The most
|
|
1174
|
+
valuable entries are the ones that produced a working build and a wrong screen,
|
|
1175
|
+
because nothing else in the system will ever announce them.
|
|
1176
|
+
|
|
1177
|
+
**Both halves, in the same change.** The numbered sections hold the finding;
|
|
1178
|
+
\`## Suggested KB edits\` holds what to DO about it \u2014 the knowledge-base page to
|
|
1179
|
+
change, or "new page for \`<record>\`". When the data contradicts a PUBLISHED
|
|
1180
|
+
knowledge-base claim, the row goes in \`## Knowledge-base corrections\` instead
|
|
1181
|
+
(KB claim / Live value / Verdict); that is the only way a stale published fact
|
|
1182
|
+
gets caught. The lists are what the knowledge base actually consumes, so a
|
|
1183
|
+
finding added without its entry is half-done. Neither waits for the end of a
|
|
1184
|
+
task, and neither waits to be asked.
|
|
1185
|
+
|
|
1186
|
+
Same discipline as the feedback file, different audience: that one is about the
|
|
1187
|
+
platform, this one is about the business.
|
|
1188
|
+
|
|
1189
|
+
## Feed problems back to TurboBase \u2014 continuously
|
|
1190
|
+
|
|
1191
|
+
Keep **\`TURBOBASE-FEEDBACK.md\`** up to date AS YOU WORK. It is the channel to the
|
|
1192
|
+
TurboBase product team, and the entries worth most are the ones written the
|
|
1193
|
+
moment they cost you time \u2014 they evaporate from memory otherwise.
|
|
1194
|
+
|
|
1195
|
+
Append an entry whenever the PLATFORM itself (not your own code) causes trouble:
|
|
1196
|
+
a scaffold gap, a misleading error, a query that compiled but returned the wrong
|
|
1197
|
+
shape, a catalog fact that produced a working build and a wrong screen, a missing
|
|
1198
|
+
tool, a confusing default, a rate limit you had to discover by hitting it. For
|
|
1199
|
+
each, note: what you expected, what happened, the concrete cost, and the fix or
|
|
1200
|
+
workaround. Skip anything that is just your own bug. Keep
|
|
1201
|
+
\`## What would have helped most, in order\` ranked \u2014 the order is the signal, and
|
|
1202
|
+
it is the part the product team reads first.
|
|
1203
|
+
|
|
1204
|
+
Do this WITHOUT being asked \u2014 treat it as part of finishing a task, like updating
|
|
1205
|
+
a test. \`turbobase apps deploy\` reads both files and queues what it finds for
|
|
1206
|
+
review, so what you write reaches the knowledge base and the product team instead
|
|
1207
|
+
of evaporating at the end of the session. Keep the section headings exactly as
|
|
1208
|
+
they are \u2014 the ingest finds entries by heading, not by filename.
|
|
1209
|
+
`}var sy="---\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",iy=`---
|
|
1210
|
+
name: ship-app
|
|
1211
|
+
description: Push the app's source to the instance and deploy it live. Use once the app has been previewed and works.
|
|
1212
|
+
---
|
|
1213
|
+
|
|
1214
|
+
Two verbs, deliberately separate:
|
|
1215
|
+
|
|
1216
|
+
1. \`turbobase apps push <slug> .\` \u2014 records the local tree as a new source
|
|
1217
|
+
revision on the instance. Nothing is built, nothing changes for users. Skip it
|
|
1218
|
+
and the changes exist only on this laptop: the next \`apps pull\`, from any
|
|
1219
|
+
machine, returns the version before them.
|
|
1220
|
+
2. \`turbobase apps deploy <slug>\` \u2014 builds locally and uploads the result. THIS
|
|
1221
|
+
is what goes live, at \`/a/<slug>\`.
|
|
1222
|
+
|
|
1223
|
+
Push freely while iterating; deploy when it's ready. Deploy runs the build, so a
|
|
1224
|
+
broken build fails the deploy rather than shipping a blank page.
|
|
1225
|
+
|
|
1226
|
+
**When someone else has to approve the change, deploy it as a preview first:**
|
|
1227
|
+
|
|
1228
|
+
\`\`\`
|
|
1229
|
+
turbobase apps deploy <slug> --preview --label "what changed"
|
|
1230
|
+
\`\`\`
|
|
1231
|
+
|
|
1232
|
+
That builds and uploads exactly as \`deploy\` does, but serves the result at its
|
|
1233
|
+
own URL and leaves \`/a/<slug>\` untouched. Send the URL to whoever asked for the
|
|
1234
|
+
change \u2014 it opens for anyone who can already open the app, so no new access is
|
|
1235
|
+
granted. Then:
|
|
1236
|
+
|
|
1237
|
+
- \`turbobase apps promote <slug> <preview-id>\` makes it live. The reviewed bytes
|
|
1238
|
+
go live as-is; nothing is rebuilt, so what ships is what was approved.
|
|
1239
|
+
- \`turbobase apps preview discard <slug> <preview-id>\` closes it.
|
|
1240
|
+
- \`turbobase apps preview list <slug>\` shows what's open.
|
|
1241
|
+
|
|
1242
|
+
Previews expire after 7 days. Several can be open at once, each with its own URL.
|
|
1243
|
+
|
|
1244
|
+
Note \`--preview\` needs the CLI to run the build (it sets the bundle's asset
|
|
1245
|
+
paths); it is refused with \`--no-build\` rather than shipping a blank page.
|
|
1246
|
+
|
|
1247
|
+
Text files only \u2014 \`push\` skips \`node_modules/\`, \`dist/\`, \`build/\`, \`.git/\`,
|
|
1248
|
+
\`.claude/\` (agent state, and any nested worktrees under it) and anything
|
|
1249
|
+
non-text, so images and fonts belong in the build pipeline or object storage, not
|
|
1250
|
+
the source tree. \`INSTANCE-LEARNINGS.md\` and \`TURBOBASE-FEEDBACK.md\` sit at the
|
|
1251
|
+
project root and DO travel \u2014 deploy reads them.
|
|
1252
|
+
`;function ay(t){return`---
|
|
1253
|
+
name: record-learning
|
|
1254
|
+
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.
|
|
1255
|
+
---
|
|
1256
|
+
|
|
1257
|
+
Two standing files at the project root, two audiences. Both are updated in the
|
|
1258
|
+
SAME change that produced the fact. Batching them to the end of a task is how
|
|
1259
|
+
they end up empty: a finding that is not written down while it is still
|
|
1260
|
+
surprising gets normalised into the code and lost.
|
|
1261
|
+
|
|
1262
|
+
**\`INSTANCE-LEARNINGS.md\` \u2014 about the CUSTOMER.** How this instance's source
|
|
1263
|
+
system is actually set up. Append a numbered section when a field holds something
|
|
1264
|
+
other than its name suggests, when a link between two records is found (or found
|
|
1265
|
+
to be ABSENT \u2014 the expensive kind, since nothing in the schema announces it), or
|
|
1266
|
+
when real rows contradict an assumption. Every claim carries the record ids it
|
|
1267
|
+
was checked against; if a fact could not be verified against rows, label it
|
|
1268
|
+
inferred and say from what.
|
|
1269
|
+
|
|
1270
|
+
Then, in the same edit, add the other half:
|
|
1271
|
+
|
|
1272
|
+
- \`## Suggested KB edits\` \u2014 the knowledge-base page to change because of the
|
|
1273
|
+
finding, or "new page for \`<record>\`". One entry per numbered section; a
|
|
1274
|
+
finding with no entry has not been handed to the knowledge base.
|
|
1275
|
+
- \`## Knowledge-base corrections\` \u2014 one table row when a PUBLISHED
|
|
1276
|
+
knowledge-base claim disagrees with the live data: the claim, the live value,
|
|
1277
|
+
and a verdict (stale / refuted / confirmed / rule broken).
|
|
1278
|
+
|
|
1279
|
+
**\`TURBOBASE-FEEDBACK.md\` \u2014 about the PLATFORM.** Where TurboBase itself cost you
|
|
1280
|
+
time \u2014 never your own bugs. Each entry records what you expected, what happened
|
|
1281
|
+
(the error verbatim, because a misleading message IS the finding), the concrete
|
|
1282
|
+
cost, and the fix or workaround. Typical entries:
|
|
1283
|
+
|
|
1284
|
+
${t?`- a scaffold gap, or a default that had to be undone;
|
|
1285
|
+
- a misleading error \u2014 one that named the wrong cause;
|
|
1286
|
+
- a query that compiled and returned the wrong shape;
|
|
1287
|
+
- a limit you only found by hitting it in production.`:`- a fixture shape that did not match the live event payload;
|
|
1288
|
+
- an import the sandbox fenced with no hint of what to use instead;
|
|
1289
|
+
- a hook that passed \`turbobase ext test\` and behaved differently deployed;
|
|
1290
|
+
- a type the generator never emitted, or a deploy error that named nothing.`}
|
|
1291
|
+
|
|
1292
|
+
Then re-rank \`## What would have helped most, in order\`; the ordering is the part
|
|
1293
|
+
the product team acts on first, so it is maintained with the entries.
|
|
1294
|
+
|
|
1295
|
+
Do not reword the three headings. The deploy-side ingest recognises entries by
|
|
1296
|
+
heading, not by filename, so a renamed section is a finding nobody receives.
|
|
1297
|
+
`}function cy(t){return`# What this instance's source system actually does
|
|
1298
|
+
|
|
1299
|
+
Findings from ${t?`building the ${t.slug} app against the live mirror`:"authoring extensions against the live instance"}.
|
|
1300
|
+
Written for the knowledge base, and **everything here is verified against real
|
|
1301
|
+
rows** \u2014 record ids and numbers are included so an editor can re-check rather
|
|
1302
|
+
than take it on trust. Where the knowledge base and the data disagree, the data
|
|
1303
|
+
is what is recorded.
|
|
1304
|
+
|
|
1305
|
+
Companion file: \`TURBOBASE-FEEDBACK.md\` is about the PLATFORM (catalog, sync,
|
|
1306
|
+
CLI, MCP). This file is about the CUSTOMER (how their source system is set up).
|
|
1307
|
+
|
|
1308
|
+
## How this file is maintained
|
|
1309
|
+
|
|
1310
|
+
It is updated **in the same change that establishes the fact** \u2014 not at the end
|
|
1311
|
+
of a task, and never "later". A finding that is not written down while it is
|
|
1312
|
+
still surprising gets normalised into the code and lost.
|
|
1313
|
+
|
|
1314
|
+
Add an entry whenever any of these happens:
|
|
1315
|
+
|
|
1316
|
+
- a field turns out to hold something other than its name suggests, or to be
|
|
1317
|
+
empty where it should be populated;
|
|
1318
|
+
- a link between two records is found \u2014 or found to be absent, which is just as
|
|
1319
|
+
important and much harder to rediscover;
|
|
1320
|
+
- an assumption (yours, the catalog's, the knowledge base's, or a field label's)
|
|
1321
|
+
is contradicted by real rows;
|
|
1322
|
+
- a business rule becomes visible in the data (a naming convention, a subsidiary
|
|
1323
|
+
split, a document that is never used for something).
|
|
1324
|
+
|
|
1325
|
+
Every claim carries the ids it was checked against. If a fact could not be
|
|
1326
|
+
verified against rows, label it as inferred and say from what.
|
|
1327
|
+
|
|
1328
|
+
**A finding is only half an entry.** The numbered sections say what is true;
|
|
1329
|
+
\`## Suggested KB edits\` says what to change in the knowledge base because of it,
|
|
1330
|
+
naming the page. \`## Knowledge-base corrections\` is the sharper case \u2014 a
|
|
1331
|
+
PUBLISHED claim the live data contradicts. Both are written at the same time as
|
|
1332
|
+
the finding, never batched up for later.
|
|
1333
|
+
|
|
1334
|
+
Keep the two headings below exactly as they are: a deploy reads this file and
|
|
1335
|
+
queues each entry for review, and it finds entries by heading.
|
|
1336
|
+
|
|
1337
|
+
---
|
|
1338
|
+
|
|
1339
|
+
<!-- Findings go here, newest last, as numbered sections:
|
|
1340
|
+
|
|
1341
|
+
## 1. <what is actually true, stated as a claim>
|
|
1342
|
+
|
|
1343
|
+
What the data shows, with the ids it was checked against, and the consequence
|
|
1344
|
+
for anything reading it.
|
|
1345
|
+
|
|
1346
|
+
-->
|
|
1347
|
+
|
|
1348
|
+
---
|
|
1349
|
+
|
|
1350
|
+
## Suggested KB edits
|
|
1351
|
+
|
|
1352
|
+
<!-- One entry per numbered section above. Name the page to change \u2014 an existing
|
|
1353
|
+
knowledge-base page, or "new page for <record>" \u2014 and what to say on it. -->
|
|
1354
|
+
|
|
1355
|
+
Each numbered section above should have an entry here. If one does not, the
|
|
1356
|
+
finding has not been handed to the knowledge base yet.
|
|
1357
|
+
|
|
1358
|
+
## Knowledge-base corrections
|
|
1359
|
+
|
|
1360
|
+
<!-- A PUBLISHED knowledge-base claim that the live data contradicts. Quote the
|
|
1361
|
+
claim, give the live value with the ids behind it, and a verdict of
|
|
1362
|
+
stale / refuted / confirmed / rule broken. -->
|
|
1363
|
+
|
|
1364
|
+
| KB claim | Live value | Verdict |
|
|
1365
|
+
|---|---|---|
|
|
1366
|
+
`}function ly(t){return`# Feedback for the TurboBase team \u2014 what ${t?`building the ${t.slug} app`:"authoring extensions here"} actually hit
|
|
1367
|
+
|
|
1368
|
+
Everything below cost time or produced a wrong result. Not speculation, and not
|
|
1369
|
+
a wishlist. This file is about the PLATFORM \u2014 scaffold, catalog, CLI, MCP, API.
|
|
1370
|
+
Facts about this customer's own setup belong in \`INSTANCE-LEARNINGS.md\`.
|
|
1371
|
+
|
|
1372
|
+
## How this file is maintained
|
|
1373
|
+
|
|
1374
|
+
Written **as the problem happens** \u2014 not at the end of a task, and not when
|
|
1375
|
+
asked. An entry written a day later has lost the part that made it useful: what
|
|
1376
|
+
you expected, what you tried, and how long it took to see through.
|
|
1377
|
+
|
|
1378
|
+
Append a numbered section (\`## N. <one-line symptom>\`) whenever the PLATFORM
|
|
1379
|
+
itself, not your own code, causes trouble:
|
|
1380
|
+
|
|
1381
|
+
${t?`- a scaffold gap, a missing tool, or a default that had to be undone;
|
|
1382
|
+
- a misleading error \u2014 one that named the wrong cause and sent you the wrong way;
|
|
1383
|
+
- a query that compiled and returned the wrong shape, or the wrong rows;
|
|
1384
|
+
- a catalog fact that produced a working build and a WRONG SCREEN;
|
|
1385
|
+
- a limit you only found by hitting it in production.`:`- a fixture shape that did not match the live event payload;
|
|
1386
|
+
- an import the sandbox fenced with no hint of what to use instead;
|
|
1387
|
+
- a hook that passed \`turbobase ext test\` and behaved differently deployed;
|
|
1388
|
+
- a misleading CLI error, or a type the generator did not emit.`}
|
|
1389
|
+
|
|
1390
|
+
Each entry records four things:
|
|
1391
|
+
|
|
1392
|
+
- what you expected;
|
|
1393
|
+
- what actually happened \u2014 paste the error verbatim, because a misleading message
|
|
1394
|
+
is itself the finding;
|
|
1395
|
+
- the concrete cost (an investigation, a wrong screen shipped, a wrong answer
|
|
1396
|
+
given to a user);
|
|
1397
|
+
- the fix, or the workaround you had to use.
|
|
1398
|
+
|
|
1399
|
+
Then re-rank \`## What would have helped most, in order\`. The ordering is the part
|
|
1400
|
+
the product team acts on first, so it is maintained with the entries rather than
|
|
1401
|
+
written once.
|
|
1402
|
+
|
|
1403
|
+
Skip anything that is just your own bug. Keep the heading below exactly as it is:
|
|
1404
|
+
a deploy reads this file and reports each finding, and it finds them by heading.
|
|
1405
|
+
|
|
1406
|
+
---
|
|
1407
|
+
|
|
1408
|
+
<!-- Findings go here, newest last:
|
|
1409
|
+
|
|
1410
|
+
## 1. <one-line symptom, stated as what goes wrong>
|
|
1411
|
+
|
|
1412
|
+
Expected / happened / cost / fix.
|
|
1413
|
+
|
|
1414
|
+
-->
|
|
1415
|
+
|
|
1416
|
+
---
|
|
1417
|
+
|
|
1418
|
+
## What would have helped most, in order
|
|
1419
|
+
|
|
1420
|
+
<!-- Rank the findings above by how much time each would have saved. Position is
|
|
1421
|
+
the signal \u2014 1 is the biggest win. -->
|
|
1422
|
+
`}function dy(t,e){let r=e?`
|
|
1423
|
+
# INSTANCE.md \u2014 the instance's grounding brief (see CLAUDE.md). Reuse the
|
|
1424
|
+
# --records focus a previous run stamped into the file, so a refresh never
|
|
1425
|
+
# narrows what an agent deliberately widened.
|
|
1426
|
+
records=$(grep -o 'records=[a-zA-Z0-9_,]*' INSTANCE.md 2>/dev/null | head -1 | cut -d= -f2 || true)
|
|
1427
|
+
turbobase project grounding \${records:+--records "$records"} --query ${JSON.stringify(e.slug)} -o INSTANCE.md >/dev/null 2>&1 \\
|
|
1428
|
+
|| echo "turbobase: grounding refresh skipped (not signed in?)" >&2
|
|
1429
|
+
`:"";return`#!/usr/bin/env bash
|
|
1430
|
+
# SessionStart hook \u2014 refresh ${t} against the current instance schema at
|
|
1431
|
+
# the start of every Claude Code session. Non-fatal: a signed-out / offline
|
|
1432
|
+
# session still starts (types just won't refresh).
|
|
1433
|
+
set -euo pipefail
|
|
1434
|
+
turbobase project types -o ${t} >/dev/null 2>&1 || echo "turbobase: types refresh skipped (not signed in?)" >&2
|
|
1435
|
+
${r}`}var uy=JSON.stringify({hooks:{SessionStart:[{hooks:[{type:"command",command:"bash .claude/hooks/session-start-refresh-types.sh"}]}]}},null,2)+`
|
|
1436
|
+
`,bd="",py=t=>`node_modules/
|
|
1437
|
+
|
|
1438
|
+
# Holds a live personal access token (written by \`turbobase ${t?"apps":"project"} init\`).
|
|
1439
|
+
.mcp.json
|
|
1440
|
+
|
|
1441
|
+
.DS_Store
|
|
1442
|
+
`;function pi(t={}){let e=ey.replace(/__BASE_URL__/g,t.baseUrl??"https://<slug>.turbobase.app").replace(/__PAT__/g,t.token??"tb_pat_\u2026"),r=!!t.appSlug,n=r?"src/types.ts":"types.ts",o=r?{slug:t.appSlug}:void 0,s=[{path:".mcp.json",content:e,mode:384},{path:".gitignore",content:py(r)},{path:"INSTANCE-LEARNINGS.md",content:cy(o)},{path:"TURBOBASE-FEEDBACK.md",content:ly(o)},{path:".claude/settings.json",content:uy},{path:".claude/skills/generate-types/SKILL.md",content:ty(n)},{path:".claude/skills/record-learning/SKILL.md",content:ay(o)},{path:".claude/hooks/session-start-refresh-types.sh",content:dy(n,o),executable:!0}];return r?[{path:"CLAUDE.md",content:oy(t.appSlug)},...s,{path:".claude/skills/preview-app/SKILL.md",content:sy},{path:".claude/skills/ship-app/SKILL.md",content:iy}]:[{path:"CLAUDE.md",content:Xg},...s,{path:".claude/skills/mock-test/SKILL.md",content:ry},{path:".claude/skills/deploy/SKILL.md",content:ny},{path:"hooks/.gitkeep",content:bd},{path:"samples/.gitkeep",content:bd}]}import{promises as _d}from"node:fs";import{resolve as fy}from"node:path";no();Vr();var k=t=>{process.stdout.write(`${t}
|
|
1443
|
+
`)},ye=t=>{process.stderr.write(`${t}
|
|
1444
|
+
`)};function $(t){ye(R.red(`turbobase: ${t}`)),process.exit(1)}var Xr=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function vd(t,e){let r=e.json===!0||typeof e.reporter=="string";(t.color===!1||r)&&ci(!1)}async function fe(t){let e=await dt(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let r=await xt();if(t){let n=r.length?` Stored instances: ${r.map(o=>o.baseUrl).join(", ")}.`:"";$(`not signed in to ${Ve(t)}.${n} Run \`turbobase auth login --base-url ${Ve(t)} --token tb_pat_\u2026\`.`)}if(r.length===0&&$("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Kt())try{let n=await Vt("Multiple instances stored \u2014 pick the active one:",r.map(s=>({value:s.baseUrl,label:s.baseUrl,description:`updated ${s.updatedAt}`})));await ro(n);let o=await dt();if(o)return{baseUrl:o.baseUrl,token:o.token}}catch{}$(`multiple instances stored (${r.map(n=>n.baseUrl).join(", ")}) and no active default. Run \`turbobase auth use <base-url>\` to pick one, or pass --base-url.`)}function Gt(t,e,r){if(!(t instanceof ge)||t.status!==403)return;t.body?.error==="approval_required"&&$(`${r} denied (403): an approval-gated deploy needs a recorded approval \u2014 pass --approved-by <email>.`),$(`${r} forbidden (403) \u2014 the stored PAT lacks the '${e}' scope. Re-run \`turbobase auth login\` with a token that has it.`)}var hy=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function my(t){try{let e=await _d.readFile(t,"utf8");return hy.exec(e)?.[1]??null}catch{return null}}function Sd(t){t.command("adopt").description("Write the instance's app-developer adopt notes (what changed that this project must act on) to a file.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--since <version>","Only notes newer than this version. Defaults to the version recorded in ADOPT.md; omit both to get everything.").option("-o, --out <file>","Output file","ADOPT.md").action(async e=>{let{baseUrl:r,token:n}=await fe(e.baseUrl),o=fy(process.cwd(),e.out),s=e.since?.trim()||await my(o),i=new URLSearchParams;s&&i.set("since",s);let a=i.toString(),l=await fetch(`${r}/v1/catalog/adopt-notes${a?`?${a}`:""}`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/json"}});l.ok||$(`adopt fetch failed: GET /v1/catalog/adopt-notes \u2192 ${l.status}`);let p=await l.json();if(!p.available){k(`${r} ships no release notes to adopt from (nothing written).`);return}let u=p.releases.reduce((g,b)=>g+b.items.length,0);if(u===0){k(`up to date${s?` since v${s.replace(/^v/,"")}`:""}${p.currentVersion?` (instance is on v${p.currentVersion})`:""} \u2014 ${o} left untouched.`);return}let d=p.currentVersion??p.releases[0]?.version??"",f=`<!-- GENERATED by \`turbobase project adopt\` against ${r} \u2014 adopted-through=${d}. Re-run to refresh; delete this file once every line is done. -->
|
|
1445
|
+
|
|
1446
|
+
`;await _d.writeFile(o,f+p.markdown,"utf8"),k(`wrote ${o} \u2014 ${u} item(s) across ${p.releases.length} release(s)${s?` since v${s.replace(/^v/,"")}`:""}.`)})}Vr();var en=["suggested_kb_edit","kb_correction"],gy=[{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}];function yy(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var kE=new Map(gy.map(t=>[yy(t.heading),t]));function by(t){return t.diff??!!t.dryRun}var wy={update_page:"append to the existing page",new_page:"create a NEW page"},fr=(t,e)=>` ${R.dim(t.padEnd(11))}${e}`,kd=t=>t.ownerEmail??t.ownerId,po=t=>R.green(t?` + ${t}`:" +"),vy=t=>R.red(t?` - ${t}`:" -"),Wt=t=>R.dim(` ${t}`),_y=` ${R.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,fi=80;function Sy(t){let e=[_y];t.target?(e.push(Wt(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(vy(`visibility: ${t.target.visibility}`)),e.push(po("visibility: admin"))):e.push(Wt(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(Wt("title, slug, evidence: untouched")),e.push(Wt("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(Wt("turbobase.document \xB7 new")),e.push(po(`title: ${t.pageTitle}`)),e.push(po("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(Wt('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(Wt('appended under "## From app developers":'));let r=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
|
|
1447
|
+
`);for(let n of r.slice(0,fi))e.push(po(n?` ${n}`:""));return r.length>fi&&e.push(R.yellow(` \u2026 ${r.length-fi} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function $y(t,e={}){let r=[];return t.forEach((n,o)=>{let{target:s,entries:i}=n;r.push(`${String(o+1).padStart(2)}. ${R.bold(n.pageTitle)}`),r.push(fr("page",s?`${s.title} (${s.slug}) [${s.visibility}]`:R.dim("new \u2014 no existing page matches"))),r.push(fr("action",wy[n.action])),r.push(fr("findings",`${i.length} ${i.length===1?"finding":"findings"} from ${[...new Set(i.map(a=>a.app_slug))].join(", ")}`)),i.forEach(a=>{let l=a.verdict?` ${R.dim(`\xB7 ${a.verdict}`)}`:"",p=a.kb_page_ref?` ${R.dim(`(${a.kb_page_ref})`)}`:"";r.push(` ${R.dim("\xB7")} ${a.title.trim()}${p}${l}`)}),r.push(fr("confidence",n.withdraws?R.red("WITHDRAWN from readers (text untouched)"):R.dim("untouched"))),n.blockedBy&&r.push(fr("blocked",R.red(`unpublished work on this page belongs to ${kd(n.blockedBy)} \u2014 this page will be SKIPPED`))),n.alsoMatched.length>0&&r.push(fr("ambiguous",R.yellow(`${n.alsoMatched.length} other page(s) match this ref: ${n.alsoMatched.map(a=>a.slug).join(", ")}`))),e.diff&&r.push(...Sy(n)),r.push("")}),r}function ky(t){let e=l=>t.filter(l).length,r=t.reduce((l,p)=>l+p.entries.length,0),n=e(l=>l.withdraws),o=e(l=>l.blockedBy!=null),s=[`${r} finding${r===1?"":"s"}`,`${t.length} page(s)`,`${e(l=>l.action==="update_page")} appended`,`${e(l=>l.action==="new_page")} created (unpublished)`],i=n>0?R.red(`${n} page(s) WITHDRAWN from readers`):R.dim("no page withdrawn"),a=o>0?` \xB7 ${R.red(`${o} page(s) BLOCKED by another editor`)}`:"";return`${s.join(" \xB7 ")} \xB7 ${i}${a}`}function xy(t,e){let r=new Map(e.map(o=>[o.key,o])),n=[];for(let o of t){let s=r.get(o.key),i=o.pageTitle||s?.pageTitle||o.key;if(o.skipped==="blocked_by_draft_owner"){n.push(`${R.yellow("skipped")} ${i} \u2014 unpublished work belongs to ${o.blockedBy?kd(o.blockedBy):"another editor"}; its findings stay pending`);continue}if(o.skipped){n.push(`${R.yellow("skipped")} ${i} \u2014 ${o.skipped.replace(/_/g," ")}`);continue}let a=o.created?R.green("created "):R.green("appended");n.push(`${a} ${i} \u2014 ${o.appliedEntryIds.length} finding(s) \u2192 page ${R.bold(o.documentId??"?")}`+(o.created?R.dim(" (unpublished)"):"")),o.confidence==="downgraded"?n.push(` ${R.red("withdrawn from readers:")} ${i}`):o.confidence==="already_withdrawn"?n.push(` ${R.dim("page was already unpublished \u2014 left as is")}`):o.confidence==="missing"&&n.push(` ${R.yellow("page vanished between plan and push \u2014 nothing withdrawn")}`)}return n}function $d(t){if(t instanceof ge){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.")}Gt(t,"extensions:deploy","learnings push-kb")}async function xd(t,e=r=>new le(r)){t.section&&!en.includes(t.section.trim())&&$(`unknown --section "${t.section}" \u2014 expected one of ${en.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&$("--limit must be a positive integer.");let r=await fe(t.baseUrl),n=e(r),o={...t.app?{app:t.app}:{},...t.section?{section:t.section.trim()}:{},...t.limit!==void 0?{limit:t.limit}:{}},s;try{s=await pe("reading the pending queue",()=>n.learningsPending(o))}catch(a){$d(a),$(`could not read the pending queue: ${a instanceof Error?a.message:String(a)}`)}if(s.items.length===0){ye(s.pendingTotal===0?"nothing pending \u2014 no ingested findings are waiting on a knowledge-base decision.":`nothing matched \u2014 ${s.pendingTotal} pending finding(s) exist but not under these filters.`);return}if(k($y(s.items,{diff:by(t)}).join(`
|
|
1448
|
+
`)),k(ky(s.items)),t.dryRun){ye(R.dim("dry run \u2014 nothing was written."));return}let i=s.items.reduce((a,l)=>a+l.entries.length,0);if(!t.yes){if(!Kt()){ye(R.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 Vt(`Push ${i} finding(s) into the knowledge base as ${s.items.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"){ye("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{let a=await pe("writing pages",()=>n.learningsPushKb(s.planToken,o));k(xy(a.applied,s.items).join(`
|
|
1449
|
+
`))}catch(a){if(a instanceof ge&&a.status===409){ye(R.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),ye(`re-run \`${Xr} kb push\` to review the current plan.`),process.exitCode=2;return}$d(a),ye(R.red(`turbobase: ${a instanceof Error?a.message:String(a)}`)),process.exitCode=2}}import{promises as Td}from"node:fs";import{join as Ty,relative as Ey,resolve as Ry,sep as Py}from"node:path";var Ay=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),Cy=new Set([".mcp.json",".env"]);function Iy(t){return Cy.has(t)||t.startsWith(".env.")&&t!==".env.example"}function Oy(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function Ny(t){return t.includes(0)}async function Ed(t){let e=Ry(t),r={},n=[],o=[],s=[];async function i(a){let l=await Td.readdir(a,{withFileTypes:!0});for(let p of l){let u=Ty(a,p.name);if(p.isDirectory()){if(Ay.has(p.name))continue;await i(u);continue}if(!p.isFile())continue;let d=Ey(e,u).split(Py).join("/");if(Iy(p.name)){o.push(d);continue}let f=await Td.readFile(u);if(!Oy(f)){n.push(d);continue}Ny(f)&&s.push(d),r[d]=f.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as jy}from"node:crypto";var zy="/_tb/app-assets",Ly=16,Dy=/^[0-9a-f]{32}$/;function Rd(){return jy(Ly).toString("hex")}function My(t){return Dy.test(t)}function Pd(t){if(!My(t))throw new Error(`not a build id: ${t}`);return`${zy}/${t}/`}var Ad=7;var hi=".github/workflows/turbobase-release-deploy.yml",qy=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1450
|
+
# TurboBase release deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR repo)
|
|
1451
|
+
#
|
|
1452
|
+
# Epic #775 "GitHub is just a link": TurboBase hosts nothing and clones nothing.
|
|
1453
|
+
# This workflow runs in YOUR GitHub repo, on YOUR runner. On every merge to your
|
|
1454
|
+
# default branch it ships your SDF customization project to TurboBase by running
|
|
1455
|
+
# the \`turbobase\` CLI, which UPLOADS the bytes from this checkout. TurboBase
|
|
1456
|
+
# never fetches your code, never holds a GitHub App key, and never mints an
|
|
1457
|
+
# installation token \u2014 the ONLY credential is a personal access token (PAT) that
|
|
1458
|
+
# YOU mint and store as a GitHub Actions secret (one-time setup below).
|
|
1459
|
+
#
|
|
1460
|
+
# \u2500\u2500 One-time setup \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1461
|
+
# 1. Mint a \`releases:write\` PAT (you, in your TurboBase app):
|
|
1462
|
+
# Settings \u2192 Access tokens \u2192 "New token"
|
|
1463
|
+
# Scope: releases:write (the only scope this workflow needs)
|
|
1464
|
+
# Copy the token \u2014 it starts with \`tb_pat_\u2026\` and is shown only once.
|
|
1465
|
+
#
|
|
1466
|
+
# 2. Store the PAT as a GitHub Actions SECRET in this repo (you, in GitHub):
|
|
1467
|
+
# Repo \u2192 Settings \u2192 Secrets and variables \u2192 Actions \u2192 "New repository secret"
|
|
1468
|
+
# Name: TURBOBASE_RELEASE_PAT
|
|
1469
|
+
# Value: <the tb_pat_\u2026 token from step 1>
|
|
1470
|
+
# The PAT lives ONLY in your GitHub secret store. TurboBase never sees your
|
|
1471
|
+
# GitHub credentials, and you never paste a TurboBase secret into this file.
|
|
1472
|
+
#
|
|
1473
|
+
# 3. Store your instance base URL as a repo VARIABLE (not a secret \u2014 it isn't
|
|
1474
|
+
# sensitive) so the workflow knows which instance to deploy to:
|
|
1475
|
+
# Repo \u2192 Settings \u2192 Secrets and variables \u2192 Actions \u2192 Variables \u2192 "New"
|
|
1476
|
+
# Name: TURBOBASE_BASE_URL
|
|
1477
|
+
# Value: https://<your-slug>.turbobase.app
|
|
1478
|
+
#
|
|
1479
|
+
# 4. Put this file at \`.github/workflows/turbobase-release-deploy.yml\` (or run
|
|
1480
|
+
# \`turbobase project ci\`, which writes it there for you), commit, and merge.
|
|
1481
|
+
# The next merge to your default branch deploys.
|
|
1482
|
+
#
|
|
1483
|
+
# \u2500\u2500 What it deliberately does NOT do \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1484
|
+
# \u2022 No GitHub App, no installation token, no server-side clone \u2014 TurboBase
|
|
1485
|
+
# receives ONLY the bytes this checkout uploads.
|
|
1486
|
+
# \u2022 Defaults to \`--target auto\`. An approval-gated deploy is a guarded,
|
|
1487
|
+
# human-approved action (\`--target approved --approved-by you@co.com\`) and is
|
|
1488
|
+
# intentionally NOT wired to fire automatically on merge.
|
|
1489
|
+
# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1490
|
+
name: TurboBase release deploy
|
|
1491
|
+
|
|
1492
|
+
on:
|
|
1493
|
+
push:
|
|
1494
|
+
# Change \`main\` to your repo's default branch if it differs (e.g. master).
|
|
1495
|
+
branches: [main]
|
|
1496
|
+
|
|
1497
|
+
# Least privilege: this workflow only READS your checkout to upload it. It never
|
|
1498
|
+
# writes to your repo, and it does NOT use GITHUB_TOKEN to reach TurboBase \u2014 the
|
|
1499
|
+
# PAT secret is the only credential that leaves the runner.
|
|
1500
|
+
permissions:
|
|
1501
|
+
contents: read
|
|
1502
|
+
|
|
1503
|
+
# One deploy at a time per branch; a newer merge supersedes any in-flight run.
|
|
1504
|
+
concurrency:
|
|
1505
|
+
group: turbobase-release-\${{ github.ref }}
|
|
1506
|
+
cancel-in-progress: false
|
|
1507
|
+
|
|
1508
|
+
jobs:
|
|
1509
|
+
deploy:
|
|
1510
|
+
runs-on: ubuntu-latest
|
|
1511
|
+
steps:
|
|
1512
|
+
# The checkout IS the upload source. \`turbobase release deploy\` reads the
|
|
1513
|
+
# SDF project's src/ from this working tree and uploads those bytes;
|
|
1514
|
+
# nothing is fetched server-side.
|
|
1515
|
+
- name: Check out the merged commit
|
|
1516
|
+
uses: actions/checkout@v4
|
|
1517
|
+
|
|
1518
|
+
- name: Set up Node
|
|
1519
|
+
uses: actions/setup-node@v4
|
|
1520
|
+
with:
|
|
1521
|
+
node-version: '20'
|
|
1522
|
+
|
|
1523
|
+
# Install the \`turbobase\` CLI. The package is scoped; the command it
|
|
1524
|
+
# installs is plain \`turbobase\`. Pin a version (\`@turbobase/cli@1.2.3\`)
|
|
1525
|
+
# if you would rather CI not track the current release.
|
|
1526
|
+
- name: Install the turbobase CLI
|
|
1527
|
+
run: npm install -g @turbobase/cli
|
|
1528
|
+
|
|
1529
|
+
# Authenticate headlessly: store the PAT for this instance. The token is read
|
|
1530
|
+
# from the GitHub secret via env (never interpolated into the command line,
|
|
1531
|
+
# so it can't leak into the run logs).
|
|
1532
|
+
- name: Authenticate to TurboBase
|
|
1533
|
+
env:
|
|
1534
|
+
TURBOBASE_RELEASE_PAT: \${{ secrets.TURBOBASE_RELEASE_PAT }}
|
|
1535
|
+
run: |
|
|
1536
|
+
turbobase auth login \\
|
|
1537
|
+
--base-url "\${{ vars.TURBOBASE_BASE_URL }}" \\
|
|
1538
|
+
--token "$TURBOBASE_RELEASE_PAT"
|
|
1539
|
+
|
|
1540
|
+
# Ship it. \`--ref \${{ github.sha }}\` records the exact commit these bytes
|
|
1541
|
+
# were built from (a provenance LINK only \u2014 TurboBase never fetches it).
|
|
1542
|
+
# \`--project .\` uploads this checkout's SDF src/; \`--follow\` waits for the
|
|
1543
|
+
# server-side deploy job and fails the run if the deploy fails.
|
|
1544
|
+
- name: Deploy the release
|
|
1545
|
+
run: |
|
|
1546
|
+
turbobase release deploy \\
|
|
1547
|
+
--target auto \\
|
|
1548
|
+
--ref "\${{ github.sha }}" \\
|
|
1549
|
+
--project . \\
|
|
1550
|
+
--follow
|
|
1551
|
+
`;function Cd(){return[{path:hi,content:qy}]}import fo from"node:fs/promises";import tn from"node:path";var mi={esbuild:"0.28.1","isolated-vm":"6.1.2"},gi="@turbobase/isolated-vm-prebuilds";function yi(t,e){return`${t}-${e}`}function bi(t=process.versions){return`abi${t.modules}`}var Id=["darwin-x64","win32-arm64"];async function Od(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=yi(e,r),o=tn.join(t.home,"node_modules"),s=tn.join(o,...gi.split("/"),"prebuilds",n),i=tn.join(o,"isolated-vm","prebuilds",n),a;try{a=await fo.readdir(s)}catch{return[]}let l=[];await fo.mkdir(i,{recursive:!0});for(let p of a){if(!p.endsWith(".node"))continue;let u=tn.join(i,p);try{await fo.copyFile(tn.join(s,p),u,fo.constants?.COPYFILE_EXCL??1),l.push(p)}catch{}}return l}import{homedir as Uy}from"node:os";import{join as Nd}from"node:path";import{promises as wi}from"node:fs";function zd(){let t=process.env.TURBOBASE_HOME??Nd(Uy(),".turbobase");return{dir:t,file:Nd(t,"sandboxes.json")}}var By={s:1e3,m:6e4,h:36e5,d:864e5};function Fy(t){let e=/^\s*(\d+)\s*([smhd])\s*$/.exec(t);if(!e)throw new Error(`invalid --ttl '${t}': expected <number><unit> where unit is s|m|h|d (e.g. 72h, 30m, 7d).`);let r=Number(e[1]);if(!Number.isFinite(r)||r<=0)throw new Error(`invalid --ttl '${t}': duration must be a positive integer.`);return r*By[e[2]]}function Hy(t,e=Date.now()){return new Date(e+Fy(t)).toISOString()}function Ky(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function Vy(t){let e=/^\s*(\d+(?:\.\d+)?)\s*%?\s*$/.exec(t);if(!e)throw new Error(`invalid --sample '${t}': expected a percent like 2% (or a bare number).`);let r=Number(e[1]);if(!Number.isFinite(r)||r<0||r>100)throw new Error(`invalid --sample '${t}': percent must be between 0 and 100.`);return r/100}function Gy(t,e){if(e>=1)return[...t];if(e<=0||t.length===0)return[];let r=Math.max(1,Math.round(1/e)),n=[];for(let o=0;o<t.length;o+=r)n.push(t[o]);return n}var Wy="[REDACTED]",vi=class extends Error{table;column;constructor(e,r,n){super(`Refusing to copy ${e}.${r} into a sandbox: ${n}. A sandbox must never hold un-redacted PII \u2014 classify the column 'safe' (non-PII) or let redaction mask it, then retry.`),this.name="UnredactedPiiError",this.table=e,this.column=r}};function Jy(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new vi(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:Wy:n[o]=s}return n}function Zy(t,e,r){return e.map(n=>Jy(t,n,r))}var jd=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),Yy=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function Qy(t){let e=t.trim();try{let o=new URL(e);if(o.hostname)return o.hostname.toLowerCase()}catch{}let r=e.replace(/^[a-z]+:\/\//i,""),n=(r.split("/")[0]??r).split("@").pop()??r;return(n.split(":")[0]??n).toLowerCase()}function Xy(t){if(!t||!t.trim())throw new Error("local-only guard: empty database target \u2014 refusing to proceed.");let e=t.toLowerCase();for(let n of Yy)if(e.includes(n))throw new Error(`local-only guard: target '${t}' looks like a cloud/prod context (matched '${n}'). \`turbobase sandbox create\` is LOCAL-ONLY and will never touch a cloud database.`);let r=Qy(t);if(!jd.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...jd].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function eb(t,e=tb){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function tb(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function rb(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function nb(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function _i(){let{file:t}=zd();try{let e=await wi.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function Ld(t){let{dir:e,file:r}=zd();await wi.mkdir(e,{recursive:!0}),await wi.writeFile(r,`${JSON.stringify(t,null,2)}
|
|
1552
|
+
`,{mode:384})}async function ob(t){let e=await _i();e.push(t),await Ld(e)}async function Dd(t){let e=await _i(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Ld(e),n??null}async function ho(){return _i()}function Si(t,e=Date.now()){let r=[],n=[];for(let o of t)Ky(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function Md(t,e){Xy(t.target());let r=Vy(e.sample),n=e.now??Date.now(),o=(e.nameGen??(l=>eb(l)))(e.fromTenant),s=rb(o);await t.createDatabase(s),await t.replayMigrations(s);let i=await t.readSourceTables(e.fromTenant);for(let l of i){let p=Gy(l.rows,r),u=Zy(l.table,p,l.classification);u.length>0&&await t.copyRows(s,l.table,u)}let a={name:o,fromTenant:e.fromTenant,database:s,createdAt:new Date(n).toISOString(),expiresAt:Hy(e.ttl,n),sampleFraction:r,url:nb(o,e.baseUrl)};return await ob(a),a}async function qd(t,e){let n=(await ho()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await Dd(e),n):null}async function $i(t,e=Date.now()){let r=await ho(),{expired:n}=Si(r,e);for(let o of n){try{await t.dropDatabase(o.database)}catch{}await Dd(o.name)}return n}var rn={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","data:read"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},HE=Object.keys(rn).filter(t=>rn[t].mintable);var GE=rn.pat.prefix,sb=Object.entries(rn).map(([t,e])=>[e.prefix,t]),ib=/^[A-Za-z0-9_-]{20,}$/;function ab(t){if(typeof t!="string")return null;for(let[e,r]of sb)if(t.startsWith(e)&&ib.test(t.slice(e.length)))return r;return null}function Ud(t){return ab(t)==="pat"}var nn="bundle.json",mo="turbobase";function Fd(t){let e;try{e=JSON.parse(t)}catch(l){throw new Error(`bundle.json is not valid JSON: ${l instanceof Error?l.message:String(l)}`)}if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("bundle.json must be a JSON object");let r=e,n=typeof r.version=="number"?r.version:0;if(n!==1)throw new Error(`bundle.json version ${n} is unsupported (expected 1)`);let o=l=>Array.isArray(l)?l:[],s=r.sync??{},i=r.guardrails??{},a={version:1,...typeof r.tenant=="string"?{tenant:r.tenant}:{},hooks:o(r.hooks),conduits:o(r.conduits),sync:{fields:o(s.fields),tables:o(s.tables)},guardrails:{validationHooks:o(i.validationHooks),fieldRules:o(i.fieldRules),conduits:o(i.conduits)},schedules:o(r.schedules)};return cb(a)}function cb(t){let e=r=>(n,o)=>r(n)<r(o)?-1:r(n)>r(o)?1:0;return{version:1,...t.tenant?{tenant:t.tenant}:{},hooks:[...t.hooks].sort(e(r=>r.id)),conduits:[...t.conduits].sort(e(r=>r.id)),sync:{fields:[...t.sync.fields].sort(e(Bd)),tables:[...t.sync.tables].sort(e(r=>r.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(Bd)),conduits:[...t.guardrails.conduits].sort(e(r=>r.conduitId))},schedules:[...t.schedules].sort(e(r=>r.name))}}function Bd(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function Hd(t,e){let r=(e??"").trim();if(!r)return{ok:!1,reason:"target instance slug is unknown \u2014 cannot confirm a promote"};let n=(t??"").trim();return n?n!==r?{ok:!1,reason:`--confirm "${n}" does not match the target instance "${r}" \u2014 refusing to apply`}:{ok:!0}:{ok:!1,reason:`--confirm <slug> is required for promote (expected "${r}")`}}async function k0(t,e){try{let r=await fetch(`${t.replace(/\/+$/,"")}/auth/pat-exchange`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)return null;let n=await r.json();return typeof n.token=="string"&&n.token.length>0?n.token:null}catch{return null}}async function x0(t){let e=await xt();e.length===0&&$("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Kt()||$("this command needs an explicit <base-url> in a non-interactive shell.");try{return await Vt(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{$("cancelled.")}}async function T0(t,e){let r;try{r=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(o){return{ok:!1,kind:"unreachable",detail:o instanceof Error?o.message:String(o)}}let n=(r.headers.get("content-type")??"").includes("application/json");return r.status===200||r.status===403?{ok:!0}:r.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${r.status}`}:n?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${r.status}`}}async function E0(t,e,r){let n=await Fl({baseUrl:t,token:e}),o=(await xt()).length-1;if(k(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),!r)return;let s=await T0(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(ye(`warning: ${n.baseUrl} did not respond to the TurboBase API (/v1) \u2014 got ${s.detail}.`),ye(" In local dev the TurboBase API is on :4100, not the app dev-server port (e.g. :5173)."),ye(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?ye(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):ye(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function R0(t){let e=await Jr(t),r=l=>{let p=new RegExp(`${l}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(e);return p?p[2]:void 0},n=/\bdefineConduit\s*[<(]/.test(e),o=r("id");if(n){let l=r("on"),p=r("recordType"),u=r("source");return(!o||!p||!l||!u)&&$(`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`),{id:o,recordType:p,event:l,source:u,sourceCode:e,extensionKind:"conduit"}}let s=r("recordType"),i=r("event"),a=r("source")??"standalone";return(!o||!s||!i)&&$(`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`),{id:o,recordType:s,event:i,source:a,sourceCode:e,extensionKind:"hook"}}async function qr(t,e,r,n){try{return await se.access(t),"skipped"}catch{}return await se.mkdir(Wn(t),{recursive:!0}),await se.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await se.chmod(t,n),"wrote"}async function qm(t,e){if(Bm(t)!==".gitignore")return qr(t,e.content,e.executable,e.mode);let r=await se.readFile(t,"utf8").catch(()=>null);if(r===null)return qr(t,e.content,e.executable,e.mode);let n=wd(r);return n===null?"skipped":(await se.writeFile(t,n,"utf8"),"merged")}function _l(t){if(t!==void 0){if(t==="junit"||t==="json")return t;$(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function P0(t){return{name:"turbobase ext test",cases:t.map(r=>{if(r.pass)return{name:r.name,status:"passed"};let n=r.error?"error":r.rejection?.code??"mismatch",o=r.error?`error: ${r.error}`:r.observed!==r.expected?`expected ${r.expected}, observed ${r.observed}`+(r.rejection?` (rejected: ${r.rejection.code??"rejected"}${r.rejection.message?` \u2014 ${r.rejection.message}`:""})`:""):`rejected: ${r.rejection?.code??"rejected"}${r.rejection?.message?` \u2014 ${r.rejection.message}`:""}`;return{name:r.name,status:"failed",detail:o,type:n}})}}function A0(t,e){let r=e.warnings.length===0?[{name:`${t} (${e.kind})`,status:"passed"}]:e.warnings.map(n=>({name:`${t}: ${n.rule}`,status:"failed",type:n.rule,detail:`${n.message} \u2192 fix: ${n.fix}`}));return{name:`turbobase ext lint ${t}`,cases:r}}function C0(t){let e=[];if(t.error)return e.push({name:`replay ${t.fixtureName}`,status:"failed",type:"error",detail:t.error}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e};for(let r of t.guards)e.push(r.status==="failed"?{name:`guard: ${r.name}`,status:"failed",type:r.name,detail:r.detail}:{name:`guard: ${r.name}`,status:"passed",detail:r.status==="skipped-offline"?`skipped-offline: ${r.detail}`:void 0});return t.whenPassed&&t.applyBranch&&e.push({name:`apply-branch: ${t.applyBranch}`,status:"passed",detail:`${t.masterAction??""} (${t.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e}}function kl({includeInternal:t=!0}={}){let e=new $0;e.name("turbobase").description("Author, test, and deploy TurboBase extensions against your instance.").version("1.1.7").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",h=>h.command.parent?"":`${li()}
|
|
1553
|
+
`),e.hook("preAction",(h,m)=>{vd(e.opts(),m.opts())});let r=e.command("auth").description("Sign in to an instance and manage stored credentials."),n=e.command("project").description("Set up the local project and the files an agent session reads."),o=e.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),s=e.command("kb").description("Write into the instance's knowledge base.");r.command("login").description("Sign in to an instance by pasting a personal access token (PAT), stored in ~/.turbobase/credentials.").requiredOption("--base-url <url>","Instance base URL, e.g. https://acme.turbobase.app").option("--token <tb_pat_\u2026>","The PAT to store. Mint one in your app under Settings \u203A Access tokens.").option("--no-verify","Skip the post-login connectivity/token probe.").action(async h=>{let m=Ve(h.baseUrl);h.token||$(`auth login needs --token. Mint a PAT in your TurboBase app (Settings \u203A Access tokens), then:
|
|
1554
|
+
${Xr} auth login --base-url ${m} --token tb_pat_\u2026`),Ud(h.token)||$("--token does not look like a TurboBase PAT (tb_pat_\u2026)."),await E0(m,h.token,h.verify)}),r.command("status").description("Show the active instance (the no-`--base-url` default) and every stored sign-in.").action(async()=>{let h=await xt();if(h.length===0){k("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`.");return}let m=await dt(),y=w=>!!m&&w.baseUrl===m.baseUrl;if(Be())k(uo(h.map(w=>[y(w)?R.green("*"):" ",R.bold(w.baseUrl),R.dim(w.updatedAt)]),{head:["","instance","updated"]}));else for(let w of h)k(`${y(w)?"* ":" "}${w.baseUrl} (updated ${w.updatedAt})`);m||ye("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}),r.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async h=>{let m=h??await x0("Pick the active instance:"),y=await ro(m);if(!y){let w=await xt();$(`no stored sign-in for ${Ve(m)}.`+(w.length?` Stored: ${w.map(_=>_.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${Ve(m)} --token tb_pat_\u2026\`.`)}k(`active instance \u2192 ${y.baseUrl}.`)}),r.command("logout").description("Remove a stored sign-in (defaults to the active instance).").option("--base-url <url>","Which instance to remove (defaults to the active/single one).").option("--all","Remove every stored sign-in.").action(async h=>{if(h.all){let w=await xt();for(let _ of w)await Qs(_.baseUrl);k(`removed ${w.length} stored sign-in${w.length===1?"":"s"}.`);return}let m=await Qs(h.baseUrl);m||$(h.baseUrl?`no stored sign-in for ${Ve(h.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let y=await dt();k(`signed out of ${m}.`+(y?` Active instance \u2192 ${y.baseUrl}.`:""))}),n.command("types").description("Generate types.ts from the signed-in instance's catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("-o, --out <file>","Output file","types.ts").option("--records-only","Emit only record-shape interfaces (skip the OpenAPI half).").action(async h=>{let{baseUrl:m,token:y}=await fe(h.baseUrl),w;try{w=await kt({baseUrl:m,token:y,recordsOnly:h.recordsOnly})}catch(S){let T=S instanceof Error?S.message:String(S);if(!h.recordsOnly&&/openapi\.json failed \(401/.test(T)){let E=await k0(m,y);if(E)try{w=await kt({baseUrl:m,token:E,recordsOnly:!1});let A=ae(process.cwd(),h.out);await se.writeFile(A,w,"utf8"),k(`wrote ${A} (${w.split(`
|
|
1555
|
+
`).length} lines).`);return}catch{}ye("types-gen: /v1/catalog/openapi.json needs a session \u2014 emitting record shapes only. To get the OpenAPI half headlessly, mint a PAT with the `data:read` scope (Settings \u203A Tokens); the CLI then exchanges it for a short-lived session automatically.");try{w=await kt({baseUrl:m,token:y,recordsOnly:!0})}catch(A){$(`types generation failed: ${A instanceof Error?A.message:String(A)}`)}}else $(`types generation failed: ${T}`)}let _=ae(process.cwd(),h.out);await se.writeFile(_,w,"utf8"),k(`wrote ${_} (${w.split(`
|
|
1556
|
+
`).length} lines).`)}),Sd(n),n.command("grounding").description("Write the instance's grounding brief (source primer + record anatomy + KB retrieval) to a file for agent sessions.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--records <list>","Comma-separated record types to focus, e.g. purchaseOrder,itemReceipt.").option("--query <text>","Retrieval question for the knowledge base (e.g. what the app is about).").option("-o, --out <file>","Output file","INSTANCE.md").action(async h=>{let{baseUrl:m,token:y}=await fe(h.baseUrl),w=new URLSearchParams;h.records&&w.set("records",h.records),h.query&&w.set("query",h.query);let _=w.toString(),S=await fetch(`${m}/v1/catalog/grounding${_?`?${_}`:""}`,{headers:{Authorization:`Bearer ${y}`,Accept:"application/json"}});S.ok||$(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${S.status}`);let E=((await S.json()).markdown??"").trim(),A=ae(process.cwd(),h.out),C=h.records?` records=${h.records}`:"",I=`<!-- GENERATED by \`turbobase project grounding\` against ${m}${C} \u2014 do not edit; re-run to refresh. -->
|
|
1557
|
+
|
|
1558
|
+
`;await se.writeFile(A,I+(E?`${E}
|
|
1559
|
+
`:`(no grounding available yet)
|
|
1560
|
+
`),"utf8"),k(`wrote ${A}${E?"":" (instance returned no grounding \u2014 connect a source first?)"}`)}),s.command("push").description("Write pending app-dev findings into the knowledge base, grouped one page at a time. Shows the plan and asks first; pages land unpublished.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--section <section>",`Only this section (${en.join(" | ")}).`).option("--limit <n>","Cap how many findings to act on.",h=>Number.parseInt(h,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("--yes","Skip the confirmation (for scripted runs).").action(h=>xd(h));let i=o.command("new").description("Scaffold a new extension file.");i.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 h=>{let m;try{m=pr("hook",{recordType:h.record,event:h.event,template:h.template,field:h.field,regex:h.regex,source:h.source,id:h.id})}catch(_){$(_ instanceof Error?_.message:String(_))}let y=ae(process.cwd(),m.relativePath);await qr(y,m.content)==="skipped"&&$(`refusing to overwrite existing file: ${y}`),k(`wrote ${y}`)}),i.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 h=>{let m;try{m=pr("conduit",{recordType:h.record,source:h.source,to:h.to,toRecordType:h.toRecord,event:h.event,id:h.id})}catch(_){$(_ instanceof Error?_.message:String(_))}let y=ae(process.cwd(),m.relativePath);await qr(y,m.content)==="skipped"&&$(`refusing to overwrite existing file: ${y}`),k(`wrote ${y}`)}),o.command("test").argument("<file>","The extension file to dry-run").description("Dry-run an extension against samples/ fixtures (production sandbox parity).").option("--samples <dir>","Samples directory","samples").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").option("--ci","CI mode \u2014 alias for the non-zero-on-failure exit (always on for `test`).").action(async(h,m)=>{let y=_l(m.reporter),w=await Jr(ae(process.cwd(),h)),_=ae(process.cwd(),m.samples),S=await Wr(_);S.length===0&&!y&&k(`no samples found under ${_} \u2014 add JSON fixtures to dry-run against.`);let T;try{T=await io(w,S.map(C=>C.fixture))}catch(C){$(`bundle failed: ${C instanceof Error?C.message:String(C)}`)}if(y){let C=P0(T);k(co(C,y)),C.cases.some(I=>I.status==="failed")&&process.exit(1);return}let E=0;for(let C of T){let I=C.pass?R.green("PASS"):R.red("FAIL");C.pass||(E+=1);let Z=C.error?` (error: ${C.error})`:C.observed!==C.expected?` (expected ${C.expected}, observed ${C.observed})`:C.rejection?` (rejected: ${C.rejection.code??"rejected"})`:"";k(` ${I} ${C.name}${Z}`)}let A=`${T.length-E}/${T.length} sample(s) passed.`;k(`
|
|
1561
|
+
${E===0?R.green(A):R.yellow(A)}`),E>0&&process.exit(1)}),o.command("deploy").argument("[file]","The extension file to deploy (single-file mode; omit with --to).").description("Deploy one extension (POST /v1/extensions) or the whole bundle (--to \u2192 /v1/config/apply).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--to <env>","Deploy the WHOLE bundle (turbobase/bundle.json) to this env (sandbox|prod).").action(async(h,m)=>{if(m.to){let T=await Sl(),{baseUrl:E,token:A}=await fe(m.baseUrl),C=new le({baseUrl:E,token:A});try{let I=await pe(`applying bundle to ${m.to}`,()=>C.configApply(T));k(`applied bundle to ${m.to}: +${I.applied.add} ~${I.applied.change} -${I.applied.destroy}`+(I.backfillsQueued.length?` (${I.backfillsQueued.length} backfill(s) queued)`:""))}catch(I){I instanceof ge&&I.status===403&&$("apply forbidden (403) \u2014 the stored PAT is not for an admin."),$(`bundle apply failed: ${I instanceof Error?I.message:String(I)}`)}return}h||$("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:y,token:w}=await fe(m.baseUrl),_=await R0(ae(process.cwd(),h)),S=new le({baseUrl:y,token:w});try{let T=await pe(`deploying ${Bm(h)}`,()=>S.deploy(_));Be()?k(Et("Deployed",[`${R.bold(T.id)} ${Yr(T.status)} ${R.dim(T.outcome)}`])):k(`deployed ${T.id} \u2192 status=${T.status} (${T.outcome}).`)}catch(T){T instanceof ge&&T.status===403&&$("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),$(`deploy failed: ${T instanceof Error?T.message:String(T)}`)}});let a=e.command("apps").description("Manage hosted apps served in your TurboBase app.");a.command("deploy").description("Build the app (if needed) and deploy it \u2014 cuts a new live version at /a/<slug>.").argument("<app>","App slug or id.").argument("[dir]","Source or built directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--no-build","Upload the directory as-is; it is already a built bundle.").option("--no-install","Skip `npm install` (assume deps are present).").option("--no-pull","Do not pull generated source even when the dir has no package.json.").option("--entry <file>","SPA entrypoint served for unknown routes.","index.html").option("--create","Create the app first if it does not exist yet.").option("--proposal <id>","Widget proposal this ship realizes (defaults to .turbobase/proposal.json).").option("--preview","Deploy to a preview URL instead of going live. Nothing about /a/<slug> changes until you `apps promote` it.").option("--label <text>","Label for the preview, so several open previews are tellable apart.").action(async(h,m,y)=>{let w=ae(process.cwd(),m??".");await se.mkdir(w,{recursive:!0});let _=y.proposal??await b(w),{baseUrl:S,token:T}=await fe(y.baseUrl),E=new le({baseUrl:S,token:T}),A=!1;try{A=(await E.appsList()).some(W=>W.slug===h||W.id===h)}catch(W){Gt(W,"extensions:deploy","deploy"),$(`could not reach ${S}: ${W instanceof Error?W.message:String(W)}`)}if(!A){y.create||$(`no app "${h}" on ${S} \u2014 create it with \`turbobase apps create ${h}\`, or pass --create.`);let W=await pe(`creating app ${h}`,()=>p(S,T,{slug:h},{tolerateExisting:!0}));W.existed||k(`created ${W.slug??h}.`)}let C=W=>se.stat(cr(w,W)).then(()=>!0).catch(()=>!1),I=h,Z=w,F=y.build!==!1;if(F&&!await C("package.json"))if(await C("index.html"))k("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),F=!1;else if(y.pull===!1)$(`${w} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let W=await pe(`pulling ${h}`,()=>u(S,T,h));I=W.slug??h,await d(w,W.files,!0),k(`pulled generated source (rev ${W.rev}).`)}let me;if(F){let W=Rd();if(me={buildId:W,assetBase:Pd(W)},y.install!==!1&&!await C("node_modules")){k("installing dependencies\u2026");try{await x(["install"],w)}catch(Ke){$(`npm install failed: ${Ke instanceof Error?Ke.message:String(Ke)}`)}}k("building\u2026");try{await x(["run","build"],w,{TURBOBASE_ASSET_BASE:me.assetBase})}catch(Ke){$(`build failed: ${Ke instanceof Error?Ke.message:String(Ke)}`)}await C("dist")||$(`no dist/ after build in ${w} \u2014 check the app's build script.`),Z=cr(w,"dist")}y.preview&&!me&&$(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${I}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let X=await Q(S,T,I,Z,y.entry,_,me,y.preview?{label:y.label}:void 0);if(y.preview){let W=X.previewUrl??"(no url returned)",Ke=X.expiresAt?new Date(X.expiresAt).toLocaleDateString():`${Ad} days`;Be()?k(Et("Preview deployed",[`${R.bold(I)} ${R.green(`v${X.version??"?"}`)} ${R.dim("not live")}`,`${R.bold(W)}`,R.dim(`expires ${Ke}`)])):k(`preview ${I} v${X.version??"?"} \u2192 ${W} (expires ${Ke}; /a/${I} unchanged).`),k(`next: turbobase apps promote ${I} ${X.previewId??"<preview-id>"} # make it live`),k(` turbobase apps preview discard ${X.previewId??"<preview-id>"}`);return}Be()?k(Et("Deployed",[`${R.bold(I)} ${R.green(`v${X.version??"?"}`)} ${R.dim(X.url??`/a/${I}`)}`])):k(`deployed ${I} \u2192 v${X.version??"?"} (${X.url??`/a/${I}`}).`),U(X)}),a.command("promote").description("Make a preview the live version at /a/<slug>. Promotes the exact reviewed bytes \u2014 no rebuild.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to promote (from `apps preview list`).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(h,m,y)=>{let{baseUrl:w,token:_}=await fe(y.baseUrl),S=await pe(`promoting ${m}`,()=>N(w,_,h,"promote",{previewId:m}));Be()?k(Et("Promoted",[`${R.bold(h)} ${R.green(`v${S.version??"?"}`)} ${R.dim(S.url??`/a/${h}`)}`])):k(`promoted ${h} \u2192 v${S.version??"?"} is now live at ${S.url??`/a/${h}`}.`),U(S)});let l=a.command("preview").description("Inspect and manage an app's open previews.");l.command("list").description("List an app's open previews (newest first).").argument("<app>","App slug or id.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(h,m)=>{let{baseUrl:y,token:w}=await fe(m.baseUrl),_=await D(y,w,h);if(_.previews.length===0){k(`no open previews for ${h}.`);return}for(let S of _.previews){let T=S.label?` ${S.label}`:"",E=S.expiresAt?new Date(S.expiresAt).toLocaleDateString():"?";k(`v${S.version} ${S.previewId}${T} ${S.url} (expires ${E})`)}}),l.command("discard").description("Close a preview. The URL stops resolving; the version stays in deploy history.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to discard.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(h,m,y)=>{let{baseUrl:w,token:_}=await fe(y.baseUrl);await pe(`discarding ${m}`,()=>N(w,_,h,"discard",{previewId:m})),k(`discarded ${m}.`)}),a.command("create").description("Create a new hosted app (a bare app row) so a build can be shipped to it.").argument("<slug>","URL slug the app is served under: /a/<slug>.").option("--name <name>","Display name (defaults to the slug).").option("--description <text>","Optional description.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(h,m)=>{let{baseUrl:y,token:w}=await fe(m.baseUrl),_=await pe(`creating ${h}`,()=>p(y,w,{slug:h,name:m.name,description:m.description})),S=_.slug??h;Be()?k(Et("Created",[`${R.bold(S)} ${R.dim(_.url??`/a/${S}`)}`])):k(`created ${S} (${_.url??`/a/${S}`}).`),k(`next: turbobase apps push ${S} . # store the source`),k(` turbobase apps deploy ${S} # build + go live`)});async function p(h,m,y,w={}){let _=`${h.replace(/\/+$/,"")}/v1/apps`,S;try{S=await fetch(_,{method:"POST",headers:{Authorization:`Bearer ${m}`,"content-type":"application/json"},body:JSON.stringify({slug:y.slug,name:y.name??y.slug,description:y.description})})}catch(T){$(`create request failed: ${T instanceof Error?T.message:String(T)}`)}if(S.status===401&&$("create unauthorized (401) \u2014 re-run `turbobase auth login`."),S.status===403&&$("create forbidden (403) \u2014 the PAT is not for an admin."),S.status===409){if(w.tolerateExisting)return{slug:y.slug,existed:!0};$(`an app with slug "${y.slug}" already exists.`)}return S.ok||$(`create failed: HTTP ${S.status} ${(await S.text().catch(()=>"")).slice(0,200)}`),await S.json().catch(()=>({}))}async function u(h,m,y){let w=`${h.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(y)}/pull`,_;try{_=await fetch(w,{headers:{Authorization:`Bearer ${m}`}})}catch(S){$(`pull request failed: ${S instanceof Error?S.message:String(S)}`)}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 "${y}" \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 d(h,m,y){let w=ae(h),_=0;for(let[S,T]of Object.entries(m)){let E=ae(w,S);E!==w&&!E.startsWith(w+Mm)&&$(`refusing to write outside ${w}: ${S}`),y||await se.stat(E).then(()=>!0).catch(()=>!1)&&$(`${E} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await se.mkdir(Wn(E),{recursive:!0}),await se.writeFile(E,T,"utf8"),_+=1}return _}function f(h){let m=h.indexOf(","),y=h.startsWith("data:")?m>=0?h.slice(m+1):"":h;if(!y)return null;try{let w=Buffer.from(y,"base64");return w.length>0?new Uint8Array(w):null}catch{return null}}async function g(h,m,y){let w=ae(h),_=async(T,E)=>{let A=ae(w,T);A!==w&&!A.startsWith(w+Mm)&&$(`refusing to write outside ${w}: ${T}`),y||await se.stat(A).then(()=>!0).catch(()=>!1)&&$(`${A} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await se.mkdir(Wn(A),{recursive:!0}),await se.writeFile(A,E)},S=`# ${m.title||"App change request"}
|
|
1562
|
+
|
|
1563
|
+
> Widget proposal \`${m.proposalId}\` \u2014 build this change, then ship it with
|
|
1564
|
+
> \`turbobase apps deploy ${m.appSlug}\`. The deploy stamps this proposal complete.
|
|
1565
|
+
|
|
1566
|
+
${m.bodyMarkdown||"_No description provided._"}
|
|
1567
|
+
|
|
1568
|
+
## Screen context
|
|
1569
|
+
|
|
1570
|
+
`+(m.screenshot?"A screenshot of the screen this request was filed from is saved beside this file as `proposal-screenshot.png`.\n":`No screenshot was captured with this request.
|
|
1571
|
+
`);if(await _("PROPOSAL.md",S),m.screenshot){let T=f(m.screenshot);T&&await _("proposal-screenshot.png",T)}await _(cr(".turbobase","proposal.json"),`${JSON.stringify({proposalId:m.proposalId},null,2)}
|
|
1572
|
+
`)}async function b(h){try{let m=await se.readFile(cr(h,".turbobase","proposal.json"),"utf8"),y=JSON.parse(m);return typeof y.proposalId=="string"&&y.proposalId?y.proposalId:void 0}catch{return}}async function v(h,m,y,w,_,S){let T=new le({baseUrl:h,token:m});try{return await T.appsPush(y,w,{note:_,proposalId:S})}catch(E){if(E instanceof ge){let A=E.body;if(E.status===401&&$("push unauthorized (401) \u2014 re-run `turbobase auth login`."),E.status===403&&A?.error==="admin_required"&&$("push forbidden (403) \u2014 the PAT is not for an admin."),E.status===403&&Gt(E,"extensions:deploy","push app source"),E.status===404&&$(`no app "${y}" on this instance \u2014 create it with \`turbobase apps create ${y}\`.`),E.status===413&&(A?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&$("push rejected: the request body exceeded the instance limit."),$(`push rejected: ${A?.error??"too large"} (limit ${A?.limit??"?"}).`)),E.status===400){let C=A?.path?` in ${A.path}`:"",I=A?.reason?` (${A.reason})`:"";$(`push rejected: ${A?.error??"bad request"}${I}${C}.`)}}$(`push failed: ${E instanceof Error?E.message:String(E)}`)}}function x(h,m,y){return new Promise((w,_)=>{let S=Um("npm",h,{cwd:m,stdio:"inherit",...y?{env:{...process.env,...y}}:{}});S.on("error",_),S.on("exit",T=>T===0?w():_(new Error(`npm ${h.join(" ")} exited ${T??"?"}`)))})}async function P(h,m,y,w){let _=`${h.replace(/\/+$/,"")}${y}`,S;try{S=await fetch(_,{method:w.method,headers:{Authorization:`Bearer ${m}`,...w.body?{"content-type":"application/json"}:{}},...w.body?{body:JSON.stringify(w.body)}:{}})}catch(T){$(`request failed: ${T instanceof Error?T.message:String(T)}`)}if(S.status===401&&$("unauthorized (401) \u2014 re-run `turbobase auth login`."),S.status===403&&$("forbidden (403) \u2014 the PAT is not for an admin."),!S.ok){let T=await S.text().catch(()=>""),E=T.slice(0,300);try{let A=JSON.parse(T);E=A.message??A.error??E}catch{}$(`failed: HTTP ${S.status} ${E}`)}return await S.json().catch(()=>({}))}async function N(h,m,y,w,_){return await P(h,m,`/v1/apps/${encodeURIComponent(y)}/preview/${w}`,{method:"POST",body:_})}async function D(h,m,y){return{previews:(await P(h,m,`/v1/apps/${encodeURIComponent(y)}/previews`,{method:"GET"})).previews??[]}}async function Q(h,m,y,w,_,S,T,E){let A;try{A=await pe(`zipping ${w}`,()=>id(w))}catch(F){$(`could not zip ${w}: ${F instanceof Error?F.message:String(F)}`)}A.fileCount===0&&$(`${w} is empty \u2014 the build produced nothing.`);let C={Authorization:`Bearer ${m}`,"Content-Type":"application/zip"};_&&(C["x-app-entry"]=_),S&&(C["x-proposal-id"]=S),T&&(C["x-app-build-id"]=T.buildId,C["x-app-asset-base"]=T.assetBase),E&&(C["x-app-channel"]="preview",E.label&&(C["x-app-preview-label"]=encodeURIComponent(E.label)));let I=`${h.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(y)}/deploy`,Z;try{Z=await pe(`deploying ${y} (${A.fileCount} file${A.fileCount===1?"":"s"})`,()=>fetch(I,{method:"POST",headers:C,body:new Uint8Array(A.buffer)}))}catch(F){$(`deploy request failed: ${F instanceof Error?F.message:String(F)}`)}if(Z.status===401&&$("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),Z.status===403&&$("deploy forbidden (403) \u2014 the PAT is not for an admin."),Z.status===404&&$(`no app "${y}" on ${h} \u2014 create it with \`turbobase apps create ${y}\`.`),!Z.ok){let F=await Z.text().catch(()=>""),me=F.slice(0,300);try{let X=JSON.parse(F);me=X.message??X.error??me}catch{}$(`deploy failed: HTTP ${Z.status} ${me}`)}return await Z.json().catch(()=>({}))}function U(h){let m=yd(h);m&&k(m.level==="warn"?R.yellow(m.message):R.dim(m.message))}a.command("pull").description("Write an app's generated source tree to disk (from the proposal that generated it).").argument("[app]","App slug or id. Omit when using --proposal (the app is derived from it).").argument("[dir]","Directory to write into (default ./<slug>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--force","Overwrite existing files.").option("--proposal <id>","Pull the app behind a widget proposal + its request context.").action(async(h,m,y)=>{let{baseUrl:w,token:_}=await fe(y.baseUrl);if(y.proposal){let A=new le({baseUrl:w,token:_}),C;try{C=await pe(`fetching proposal ${y.proposal}`,()=>A.appPullContext(y.proposal))}catch(X){Gt(X,"extensions:deploy","pull proposal"),X instanceof ge&&X.status===404&&$(`no widget proposal "${y.proposal}" on ${w}.`),$(`could not fetch proposal ${y.proposal}: ${X instanceof Error?X.message:String(X)}`)}let I=await pe(`pulling ${C.appSlug}`,()=>u(w,_,C.appSlug)),Z=m??h,F=ae(process.cwd(),Z??C.appSlug);await se.mkdir(F,{recursive:!0});let me=await d(F,I.files,!!y.force);await g(F,C,!!y.force),k(`pulled ${me} file${me===1?"":"s"} \u2192 ${F} (rev ${I.rev}), linked to proposal ${C.proposalId}.`),k(`next: cd ${vl(process.cwd(),F)||"."} && turbobase apps deploy ${C.appSlug}`);return}h||$("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let S=await pe(`pulling ${h}`,()=>u(w,_,h)),T=ae(process.cwd(),m??S.slug??h);await se.mkdir(T,{recursive:!0});let E=await d(T,S.files,!!y.force);k(`pulled ${E} file${E===1?"":"s"} \u2192 ${T} (rev ${S.rev}).`),k(`next: cd ${vl(process.cwd(),T)||"."} && turbobase apps deploy ${S.slug}`)}),a.command("init").description("Scaffold a new app project locally, wired to your instance and to Claude Code.").argument("<app>","App slug \u2014 also the /a/<slug> mount path the build is pinned to.").argument("[dir]","Directory to scaffold into (default ./<app>).").option("--title <text>","Display title used in index.html and the starter component.").option("--base-url <url>","Instance to wire the project to (defaults to the active instance).").option("--no-claude","Skip the Claude Code wiring (CLAUDE.md, .mcp.json, .claude/).").option("--force","Overwrite existing files.").action(async(h,m,y)=>{let w=ae(process.cwd(),m??h),_=await dt(y.baseUrl).catch(()=>null),{scaffoldAppFiles:S,starterApp:T}=await Promise.resolve().then(()=>(su(),ou)),E=y.title??h,A=S({slug:h,title:E,appTsx:T(E),instanceOrigin:_?.baseUrl});await se.mkdir(w,{recursive:!0});let C=await d(w,A,!!y.force);if(k(`scaffolded ${C} file${C===1?"":"s"} \u2192 ${w}`),y.claude!==!1){let Z=pi({baseUrl:_?.baseUrl,token:_?.token,appSlug:h}),F=0;for(let me of Z){let X=await qm(cr(w,me.path),me);(X==="wrote"||X==="merged")&&(F+=1)}k(`wired Claude Code: ${F} file${F===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),_||ye("not signed in \u2014 .mcp.json and the dev proxy carry placeholders. Run `turbobase auth login`, then `turbobase apps init` again (existing files are kept).")}let I=vl(process.cwd(),w)||".";k(`next: cd ${I} && npm install && npm run dev`),k(` turbobase apps create ${h}`),k(` turbobase apps push ${h} .`),k(` turbobase apps deploy ${h} .`)}),a.command("list").description("List the hosted apps on your instance.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async h=>{let{baseUrl:m,token:y}=await fe(h.baseUrl),w=new le({baseUrl:m,token:y}),_;try{_=await w.appsList()}catch(S){Gt(S,"extensions:deploy","list apps"),$(`list apps failed: ${S instanceof Error?S.message:String(S)}`)}if(h.json)return k(JSON.stringify(_,null,2));if(_.length===0)return k("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");k(uo(_.map(S=>[S.slug,S.name,S.deployed?"yes":"no",S.sourceRev===null?"\u2014":`rev ${S.sourceRev}`,S.audience]),{head:["SLUG","NAME","LIVE","SOURCE","AUDIENCE"]}))}),a.command("push").description("Record the local source tree as the app's newest source revision (does NOT deploy).").argument("<app>","App slug or id.").argument("[dir]","Source directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--note <text>","Short note stored with the revision.").option("--proposal <id>","Widget proposal this rev works (defaults to .turbobase/proposal.json).").action(async(h,m,y)=>{let w=ae(process.cwd(),m??".");await se.stat(w).then(X=>X.isDirectory()).catch(()=>!1)||$(`${w} is not a directory.`);let{baseUrl:S,token:T}=await fe(y.baseUrl),E=y.proposal??await b(w),{files:A,skipped:C,secrets:I,unstorable:Z}=await Ed(w),F=Object.keys(A).length;if(F===0&&$(`no source files found under ${w} (build output and node_modules are skipped).`),Z.length>0){for(let X of Z)ye(`${X} contains a NUL byte (U+0000), which cannot be stored.`);$(`push aborted: ${Z.length} ${Z.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let X of C)ye(R.dim(`skipped binary file ${X}`));for(let X of I)ye(R.dim(`skipped ${X} (holds credentials \u2014 never pushed)`));let me=await pe(`pushing ${F} file${F===1?"":"s"}`,()=>v(S,T,h,A,y.note,E));k(`pushed ${me.files} file${me.files===1?"":"s"} \u2192 ${me.slug} rev ${me.rev} (source only, nothing deployed).`),k(`next: turbobase apps deploy ${me.slug}`)}),o.command("plan").description("Diff the local bundle (turbobase/bundle.json) against a target env (no writes).").option("--from <env>","Source env the bundle was authored against (advisory).").option("--to <env>","Target env to diff against (sandbox|prod).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async h=>{let m=await Sl(),{baseUrl:y,token:w}=await fe(h.baseUrl),_=new le({baseUrl:y,token:w}),S;try{S=await pe(`planning against ${h.to??y}`,()=>_.configPlan(m))}catch(T){$(`plan failed: ${T instanceof Error?T.message:String(T)}`)}O0(S,h.to??y)}),o.command("promote").description("Promote the bundle from one env to another behind a confirm-slug gate (fail-closed).").requiredOption("--from <env>","Source env (e.g. sandbox).").requiredOption("--to <env>","Target env (e.g. prod).").requiredOption("--confirm <slug>","Type the EXACT target instance slug to confirm (fail-closed).").option("--base-url <url>","Target instance base URL (defaults to the active instance).").action(async h=>{let m=await Sl(),{baseUrl:y,token:w}=await fe(h.baseUrl),_=m.tenant??N0(y),S=Hd(h.confirm,_);S.ok||$(`promote refused (fail-closed): ${S.reason}`);let T=new le({baseUrl:y,token:w});try{let E=await pe(`promoting ${h.from} \u2192 ${h.to} (${_})`,()=>T.configApply(m));if(Be()){let A=[`${R.bold(`${h.from} \u2192 ${h.to}`)} ${R.dim(_??"")}`,`${Tt.add(String(E.applied.add))} ${Tt.change(String(E.applied.change))} ${Tt.destroy(String(E.applied.destroy))}`];E.backfillsQueued.length&&A.push(R.dim(`${E.backfillsQueued.length} backfill(s) queued`)),k(Et("Promoted",A))}else k(`promoted ${h.from} \u2192 ${h.to} (${_}): +${E.applied.add} ~${E.applied.change} -${E.applied.destroy}`+(E.backfillsQueued.length?` (${E.backfillsQueued.length} backfill(s) queued)`:""))}catch(E){E instanceof ge&&E.status===403&&$("promote forbidden (403) \u2014 the stored PAT is not for an admin."),$(`promote failed: ${E instanceof Error?E.message:String(E)}`)}});let je=async(h,m)=>{let{baseUrl:y,token:w}=await fe(m.baseUrl),_=new le({baseUrl:y,token:w}),S=m.limit?Number(m.limit):void 0;if(m.follow){try{await hd(_,h,{follow:!0,limit:S,intervalMs:m.intervalMs?Number(m.intervalMs):void 0,sink:k})}catch(T){$(`logs --follow failed: ${T instanceof Error?T.message:String(T)}`)}return}try{let T=await _.logs(h,S);T.length===0&&k(`no logs for ${h}.`);for(let E of T)k(` [${E.level}] ${E.ts??""} ${E.message}`)}catch(T){$(`logs failed: ${T instanceof Error?T.message:String(T)}`)}};o.command("logs").argument("<id>","Extension id (default) or conduit id (with --follow)").description("Read an extension's logs; with --follow, stream a conduit's run ledger.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--limit <n>","Max log lines").option("--follow","Stream the conduit_event run ledger for the given conduit id.").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(je),o.command("lint").argument("<file>","The hook or conduit definition file to lint").description("Statically lint a hook/conduit for semantic foot-guns (offline).").option("--ci","Exit non-zero when any warning fires (else exit 0).").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").action(async(h,m)=>{let y=_l(m.reporter),w=ae(process.cwd(),h),_=await Jr(w),S=cd(_);y?k(co(A0(h,S),y)):k(ld(h,S,{warn:R.yellow,ok:R.green,dim:R.dim})),m.ci&&S.warnings.length>0&&process.exit(1)}),o.command("replay").argument("<file>","The conduit file to replay").description("Dry-run a conduit through dispatch\u2192transform\u2192apply (offline against a fixture).").option("--fixture <file>","JSON conduit-trigger fixture to replay against.").option("--against <target>","Replay against a running sandbox (online; deferred without a local DB).").option("--trace","Emit the per-stage trace (guards, atlas, apply-branch, bindings).").option("--reporter <fmt>","Emit machine-readable output: junit | json (one case per stage).").action(async(h,m)=>{let y=_l(m.reporter),w=await ed(ae(process.cwd(),h));if(m.against){m.against!=="sandbox"&&$(`unknown --against target '${m.against}' (only 'sandbox' is supported).`);try{await Ql(si(w))}catch(T){$(T instanceof Error?T.message:String(T))}return}m.fixture||$("replay needs a --fixture <file> (offline) or --against sandbox (online).");let _;try{_=await Xl(ae(process.cwd(),m.fixture))}catch(T){$(`could not read fixture ${m.fixture}: ${T instanceof Error?T.message:String(T)}`)}let S=await Yl(w,_,m.fixture);if(y){let T=C0(S);k(co(T,y)),T.cases.some(E=>E.status==="failed")&&process.exit(1);return}k(td(S,!!m.trace)),S.error&&process.exit(1)}),o.command("binding").description("List conduit source bindings (--status divergent) or re-enqueue one (--retry <id>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <status>","Filter by write_status (ok|pending|blocked|divergent|muted).").option("--retry <id>","Re-enqueue the fan-out write for this binding id (admin-only).").option("--limit <n>","Max rows listed").action(async h=>{let{baseUrl:m,token:y}=await fe(h.baseUrl),w=new le({baseUrl:m,token:y});try{await md(w,{status:h.status,retry:h.retry,limit:h.limit?Number(h.limit):void 0,sink:k})}catch(_){_ instanceof ge&&_.status===403&&$("forbidden (403) \u2014 binding --retry requires an admin PAT."),_ instanceof ge&&_.status===409&&$("binding is not retryable (only divergent/blocked bindings can be retried)."),$(`ext binding failed: ${_ instanceof Error?_.message:String(_)}`)}}),o.command("install").argument("<spec>","Extension name, optionally name@version").description("Install an extension from the marketplace into your instance's extension store.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--connection <id>",'Bind this connection id (required when the extension declares a { type:"connection" } input).').action(async(h,m)=>{let y=h.lastIndexOf("@"),w=y>0?h.slice(0,y):h,_=y>0?h.slice(y+1):void 0,S=Xs();S||$(`marketplace not configured \u2014 set ${dr} and ${oo}.
|
|
1573
|
+
Ask TurboBase support to issue a registry token for your instance (it is separate from your PAT).`);let T=ei(S.registryUrl);T&&$(T);let{baseUrl:E,token:A}=await fe(m.baseUrl),C=new Kr(S),I;try{I=await pe(`fetching ${h}`,()=>C.fetchBundle(w,_))}catch(W){$(`marketplace fetch failed for ${h}: ${W instanceof Error?W.message:String(W)}`)}let Z=Yn(I.manifest),F=null;if(Z.length>0){if(!m.connection){let W=Z.map(Ke=>Ke.source_system).join(", ");$(`${I.name}@${I.version} declares a connection input (source: ${W}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}F=m.connection}let me=I0(I.bundle,I.name,I.kind),X=new le({baseUrl:E,token:A});try{let W=await pe(`installing ${I.name}@${I.version}`,()=>X.deploy({...me,provenance:"marketplace",...F?{connectionId:F}:{}}));k(`installed ${I.name}@${I.version} \u2192 ${W.id} (status=${W.status}, ${W.outcome})`+(F?` bound to connection ${F}.`:"."))}catch(W){W instanceof ge&&W.status===403&&$("install forbidden (403) \u2014 the stored PAT is not for an admin."),$(`install failed: ${W instanceof Error?W.message:String(W)}`)}}),o.command("publish").description("Publish an authored extension to the public marketplace (publisher allowlist required).").argument("<file>","The extension file to publish (defineHook/defineConduit source).").requiredOption("--name <name>","Marketplace package name (lowercase, e.g. acme-recipes).").requiredOption("--pkg-version <version>","Semver-ish package version (e.g. 1.0.0).").option("--manifest <file>","Path to a JSON manifest (declared inputs[], capabilities).").action(async(h,m)=>{let y=Xs();y||$(`marketplace not configured \u2014 set ${dr} and ${oo}.
|
|
1574
|
+
Ask TurboBase support to issue a registry token for your instance (it is separate from your PAT).`);let w=ei(y.registryUrl);w&&$(w);let _=ae(process.cwd(),h),S=await Jr(_),T=/\bdefineConduit\s*[<(]/.test(S)?"conduit":"hook",E={};if(m.manifest){let I=ae(process.cwd(),m.manifest),Z;try{Z=await se.readFile(I,"utf8")}catch{$(`manifest not found at ${m.manifest}.`)}let F;try{F=JSON.parse(Z)}catch{$(`manifest is not valid JSON: ${m.manifest}.`)}(typeof F!="object"||F===null||Array.isArray(F))&&$("manifest must be a JSON object."),E=F}try{Ms(E,S)}catch(I){I instanceof $t&&$(I.message),$(`manifest validation failed: ${I instanceof Error?I.message:String(I)}`)}let A=new Kr(y);try{await pe(`publishing ${m.name}@${m.pkgVersion}`,()=>A.publish({name:m.name,version:m.pkgVersion,kind:T,bundle:S,manifest:E}))}catch(I){I instanceof ge&&I.status===403&&$("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),I instanceof ge&&I.status===409&&$(`version already published \u2014 ${m.name}@${m.pkgVersion} exists. Bump the version.`),$(`publish failed: ${I instanceof Error?I.message:String(I)}`)}let C=Yn(E);k(`published ${m.name}@${m.pkgVersion} (kind=${T}) to the marketplace.`),C.length>0&&k(` declares ${C.length} connection input(s): ${C.map(I=>I.source_system).join(", ")} \u2014 bound at install.`)}),n.command("init").description("Scaffold a Claude-Code extension project in the current dir.").option("--base-url <url>","Instance to wire .mcp.json to (defaults to the active instance).").action(async h=>{let m=await dt(h.baseUrl).catch(()=>null),y=pi({baseUrl:m?.baseUrl,token:m?.token}),w=0,_=0,S=0;for(let T of y){let E=ae(process.cwd(),T.path),A=await qm(E,T);A==="wrote"?(w+=1,k(` wrote ${T.path}`)):A==="merged"?(S+=1,k(` merged ${T.path} (added the .mcp.json rule)`)):(_+=1,k(` skipped ${T.path} (exists)`))}k(`
|
|
1575
|
+
project init: ${w} written, ${S} merged, ${_} skipped.`)}),n.command("ci").description(`Write the reusable release-deploy GitHub Action to ${hi} (non-destructive).`).action(async()=>{let h=Cd(),m=0,y=0;for(let w of h){let _=ae(process.cwd(),w.path);await qr(_,w.content,w.executable)==="wrote"?(m+=1,k(` wrote ${w.path}`)):(y+=1,k(` skipped ${w.path} (exists)`))}k(`
|
|
1576
|
+
project ci: ${m} written, ${y} skipped.`),m>0&&(k(`
|
|
1577
|
+
Next: mint a releases:write PAT in your TurboBase app (Settings \u203A Access tokens),`),k("store it as the GitHub Actions secret TURBOBASE_RELEASE_PAT, and set the repo"),k("variable TURBOBASE_BASE_URL \u2014 the workflow header has the step-by-step."))}),n.command("samples").description("Generate samples/<recordType>.json fixtures from the live instance catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Output directory for the fixtures","samples").option("--event <event>","Lifecycle event to stamp on each fixture","before_save").option("--force","Overwrite existing fixture files (default: skip files that exist).").action(async h=>{let{baseUrl:m,token:y}=await fe(h.baseUrl),w=new le({baseUrl:m,token:y}),_;try{_=await w.catalogRecords()}catch(C){C instanceof ge&&(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){k("no records in the instance catalog \u2014 nothing to generate.");return}let S=ae(process.cwd(),h.out),T=nd(_,{event:h.event}),E=0,A=0;for(let{recordType:C,fixture:I}of T){let Z=cr(S,`${C}.json`),F=`${JSON.stringify(I,null,2)}
|
|
1578
|
+
`;h.force?(await se.mkdir(Wn(Z),{recursive:!0}),await se.writeFile(Z,F,{mode:420}),E+=1,k(` wrote ${h.out}/${C}.json`)):await qr(Z,F)==="wrote"?(E+=1,k(` wrote ${h.out}/${C}.json`)):(A+=1,k(` skipped ${h.out}/${C}.json (exists \u2014 use --force to overwrite)`))}k(`
|
|
1579
|
+
samples init: ${E} written, ${A} skipped.`)});let Ee=e.command("sandbox").description("Ephemeral local authoring sandboxes.");Ee.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 h=>{process.env.TURBOBASE_SANDBOX="1";let m=$l(),y;try{y=await Md(m,{fromTenant:h.from,ttl:h.ttl,sample:h.sample,baseUrl:h.baseUrl})}catch(_){$(`sandbox create failed: ${_ instanceof Error?_.message:String(_)}`)}let w=await j0(y.name);k(`sandbox ${y.name} ready.`),k(` source: ${y.fromTenant} (sampled ${Math.round(y.sampleFraction*100)}%, redacted)`),k(` url: ${y.url}`),k(` expires: ${y.expiresAt}`),k(` mounted: ${w.hooks} hook(s), ${w.conduits} conduit(s)`)}),Ee.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async h=>{let m=$l();await $i(m).catch(()=>[]);let y;try{y=await qd(m,h)}catch(w){$(`sandbox destroy failed: ${w instanceof Error?w.message:String(w)}`)}y||$(`no sandbox named '${h}'.`),k(`destroyed sandbox ${y.name} (dropped ${y.database}).`)}),Ee.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let h=$l(),m=await $i(h).catch(()=>[]),y=await ho(),{active:w}=Si(y);if(w.length===0)k("no active sandboxes.");else{for(let _ of w)k(` ${_.name} from=${_.fromTenant} expires=${_.expiresAt} ${_.url}`);k(`
|
|
1580
|
+
${w.length} active sandbox(es).`)}m.length>0&&k(`(reaped ${m.length} expired sandbox(es).)`)}),o.command("export").description("Snapshot the live instance into turbobase/bundle.json.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",mo).action(async h=>{let{baseUrl:m,token:y}=await fe(h.baseUrl),w=new le({baseUrl:m,token:y}),_;try{_=await pe("exporting instance config",()=>w.configExport())}catch(E){E instanceof ge&&(E.status===401||E.status===403)&&$("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),$(`ext export failed: ${E instanceof Error?E.message:String(E)}`)}let S=typeof _.serialized=="string"?_.serialized:`${JSON.stringify(_.manifest??_,null,2)}
|
|
1581
|
+
`,T=ae(process.cwd(),h.out,nn);await se.mkdir(Wn(T),{recursive:!0}),await se.writeFile(T,S,"utf8"),k(`wrote ${h.out}/${nn} (${S.split(`
|
|
1582
|
+
`).length} lines).`)});let lr=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),Ur=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],St=()=>process.env.TURBOBASE_HOME?.trim()||cr(S0(),".turbobase"),Br=()=>"1.1.7",Ft=async()=>Promise.all(Ur.map(async h=>{try{return await import(h.name),{...h,present:!0}}catch{return{...h,present:!1}}}));return lr.command("status").description("Report which optional native packages are installed.").action(async()=>{let h=await Ft();for(let m of h)k(`${m.present?Fe.success("installed"):Fe.warn("missing")} ${R.bold(m.name)} \u2014 ${m.needs}`);h.some(m=>!m.present)&&k(`
|
|
1583
|
+
run \`${Xr} ext extras install\` to fetch them into ${St()}.`)}),lr.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let h=await Ft();if(h.every(A=>A.present)){k(Fe.success("extras already installed \u2014 nothing to do."));return}let m=St();await se.mkdir(m,{recursive:!0});let y=h.filter(A=>!A.present).map(A=>A.name),w=yi(process.platform,process.arch),_=async(A,C)=>{let{code:I,stderr:Z}=await Jn("npm",["install","--prefix",m,"--no-audit","--no-fund",...A]);I!==0&&$(`extras install failed while installing ${C} (npm exited ${I}).
|
|
1584
|
+
${Z.trim()}
|
|
1585
|
+
These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},S=y.filter(A=>A!=="isolated-vm");if(S.length>0){let A=S.map(C=>`${C}@${mi[C]??"latest"}`);k(`installing ${A.join(", ")} \u2192 ${m}/node_modules \u2026`),await _(A,S.join(", "))}if(y.includes("isolated-vm")){let A=`isolated-vm@${mi["isolated-vm"]}`;if(k(`installing ${A} \u2192 ${m}/node_modules \u2026`),await _(["--ignore-scripts",A],"isolated-vm"),Id.includes(w)){let I=`${gi}@${Br()}`;k(`fetching ${I} (no upstream binary for ${w}) \u2026`);let{code:Z}=await Jn("npm",["install","--prefix",m,"--no-audit","--no-fund","--ignore-scripts",I]);Z!==0&&k(Fe.warn(`could not fetch ${I} \u2014 falling back to a source build.`))}let C=await Od({home:m});C.length>0&&k(` ${Fe.success("prebuilt")} ${C.join(", ")} \u2192 isolated-vm/prebuilds/${w}`)}let T=await Ft(),E=T.filter(A=>!A.present).map(A=>A.name);if(E.includes("isolated-vm")){k(Fe.warn(`no prebuilt isolated-vm for ${w} / Node ${process.versions.node} (${bi()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:A}=await Jn("npm",["rebuild","--prefix",m,"isolated-vm"]);A===0&&(T=await Ft(),E=T.filter(C=>!C.present).map(C=>C.name))}E.length>0&&$(`npm succeeded but ${E.join(", ")} still will not load \u2014 no prebuilt binary for ${w} / Node ${process.versions.node} (${bi()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),k(Fe.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))}),e.command("mcp").description("Run the local stdio authoring MCP server (for Claude Code via .mcp.json).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async h=>{let{runAuthoringMcpServer:m}=await Promise.resolve().then(()=>(Dm(),Lm));await m({baseUrl:h.baseUrl})}),e.addHelpText("after",["","Common flows:"," turbobase auth login --base-url https://acme.turbobase.app"," 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)."].join(`
|
|
1586
|
+
`)),t&&void 0,e}function I0(t,e,r){let n=o=>{let s=new RegExp(`${o}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return s?s[2]:void 0};return{id:n("id")??`marketplace:${e}`,recordType:n("recordType")??"*",event:n("event")??"before_save",source:n("source")??"standalone",sourceCode:t,extensionKind:r||"hook"}}async function Sl(){let t=ae(process.cwd(),mo,nn),e;try{e=await se.readFile(t,"utf8")}catch{$(`no bundle found at ${mo}/${nn} \u2014 run \`turbobase ext export\` first.`)}try{return Fd(e)}catch(r){$(`bundle is invalid: ${r instanceof Error?r.message:String(r)}`)}}function O0(t,e){k(`plan against ${e}:`);for(let r of t.add)k(` ${Tt.add(`${r.kind} ${r.id}`)}`);for(let r of t.change)k(` ${Tt.change(`${r.kind} ${r.id}`)}`);for(let r of t.destroy)k(` ${Tt.destroy(`${r.kind} ${r.id}`)}`);k(`
|
|
1587
|
+
${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 N0(t){try{let r=new URL(t).hostname.split(".")[0];return r&&r!=="localhost"?r:void 0}catch{return}}function Jn(t,e,r){return new Promise(n=>{let o=Um(t,e,{stdio:["ignore","inherit","pipe"],env:{...process.env,...r}}),s="";o.stderr?.on("data",i=>{let a=i.toString();s+=a,process.stderr.write(a)}),o.on("error",i=>n({code:-1,stderr:i.message})),o.on("exit",i=>n({code:i??-1,stderr:s}))})}function $l(){let t=process.env.SANDBOX_LOCAL_DATABASE_URL??"postgres://postgres:postgres@127.0.0.1:54322/postgres",e=async(r,n)=>{let o=n?t.replace(/\/[^/]*$/,`/${n}`):t,s=await Jn("psql",[o,"-v","ON_ERROR_STOP=1","-c",r]);if(s.code!==0)throw new Error(`psql failed (exit ${s.code}): ${s.stderr.trim()}`)};return{target:()=>t,createDatabase:async r=>{await e(`CREATE DATABASE ${r};`)},replayMigrations:async r=>{let n=t.replace(/\/[^/]*$/,`/${r}`),o=await Jn("supabase",["migration","up","--db-url",n]);if(o.code!==0)throw new Error(`supabase migration up failed (exit ${o.code}): ${o.stderr.trim()}`)},readSourceTables:async r=>{throw new Error("sandbox data copy requires a live local Supabase (no local Postgres in this environment).")},copyRows:async(r,n,o)=>{let s=Object.keys(o[0]??{});if(s.length===0)return;let i=o.map(a=>`(${s.map(l=>a[l]===null||a[l]===void 0?"NULL":`'${String(a[l]).replace(/'/g,"''")}'`).join(", ")})`).join(", ");await e(`INSERT INTO turbobase.${n} (${s.join(", ")}) VALUES ${i};`,r)},dropDatabase:async r=>{await e(`DROP DATABASE IF EXISTS ${r} WITH (FORCE);`)}}}async function j0(t){let e=async r=>{try{return(await se.readdir(ae(process.cwd(),r))).filter(o=>/\.(ts|js|mjs)$/.test(o)).length}catch{return 0}};return{hooks:await e("hooks"),conduits:await e("conduits")}}var z0=!1;z0&&kl().parseAsync(process.argv).catch(t=>$(t instanceof Error?t.message:String(t)));kl().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
|
|
1588
|
+
`),process.exit(1)});
|