@turbobase/cli 1.35.0 → 1.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/turbobase.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __tbCreateRequire } from 'node:module';
3
3
  const require = __tbCreateRequire(import.meta.url);
4
- var zb=Object.create;var Ui=Object.defineProperty;var Bb=Object.getOwnPropertyDescriptor;var Fb=Object.getOwnPropertyNames;var Hb=Object.getPrototypeOf,Kb=Object.prototype.hasOwnProperty;var j=(t,e)=>()=>(t&&(e=t(t=0)),e);var U=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Yd=(t,e)=>{for(var r in e)Ui(t,r,{get:e[r],enumerable:!0})},Vb=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Fb(e))!Kb.call(t,o)&&o!==r&&Ui(t,o,{get:()=>e[o],enumerable:!(n=Bb(e,o))||n.enumerable});return t};var Xd=(t,e,r)=>(r=t!=null?zb(Hb(t)):{},Vb(e||!t||!t.__esModule?Ui(r,"default",{value:t,enumerable:!0}):r,t));function ur(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var gn=j(()=>{});import{z as pr}from"zod";function Eo(t){let e=Mi.safeParse(t);return e.success?(e.data.inputs??[]).filter(r=>r.type==="connection"):[]}function qi(t,e){let r=Mi.safeParse(t);if(!r.success)throw new Kt(`invalid manifest: ${r.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}`);if(Zd.test(e))throw new Kt('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(Zd.test(n))throw new Kt("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var Qd,eu,Mi,Kt,Zd,tu=j(()=>{Qd=pr.object({type:pr.literal("connection"),source_system:pr.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:pr.string().min(1).max(200).optional()}),eu=pr.discriminatedUnion("type",[Qd]),Mi=pr.object({inputs:pr.array(eu).optional()}).passthrough(),Kt=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};Zd=/\bconnection[_-]?id\b["']?\s*[:=]/i});var Po,zi=j(()=>{Po=["before_read","before_save","after_save","before_delete","after_delete","before_sync","after_sync","on_sync_failure"]});import{z as Fe}from"zod";var Bi,ru,nu=j(()=>{gn();zi();Bi=Fe.object({id:Fe.string().min(1,"hook id must be non-empty"),recordType:Fe.union([Fe.string().min(1),Fe.array(Fe.string().min(1)).min(1),Fe.literal("*")]),event:Fe.enum(Po),source:Fe.string().min(1).optional(),when:Fe.unknown().optional(),run:Fe.unknown(),failClosed:Fe.boolean().optional(),timeoutMs:Fe.number().int().positive().optional(),description:Fe.string().optional(),systemReserved:Fe.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"})}),ru=ur({kind:"hook",schema:Bi,factoryName:"defineHook"})});var ou=j(()=>{nu();zi()});var Ao,Fi=j(()=>{Ao=["after_canonicalize_inbound","after_sync_success_outbound"]});import{z as ge}from"zod";var su,Jb,iu,Hi,au,lu=j(()=>{gn();Fi();su=ge.string().regex(/^[a-z_][a-z0-9_]*$/i,"must be a bare column name (letters, digits, underscore)"),Jb=ge.object({recordType:ge.string().min(1,"reads[].recordType must be non-empty"),source:ge.string().min(1).optional(),columns:ge.array(su).min(1,"reads[].columns must name at least one column"),by:ge.array(su).optional(),maxRows:ge.number().int().positive().max(500,`reads[].maxRows cannot exceed ${500}`).optional()}),iu=ge.object({source:ge.string().min(1,"to.source must be non-empty"),recordType:ge.string().min(1,"to.recordType must be non-empty")}),Hi=ge.object({id:ge.string().min(1,"conduit id must be non-empty"),on:ge.enum(Ao),from:ge.object({source:ge.string().min(1,"from.source must be non-empty"),recordType:ge.string().min(1,"from.recordType must be non-empty"),when:ge.unknown().optional()}),to:iu.optional(),mode:ge.enum(["dual-bind","one-shot"]).optional(),transform:ge.unknown().optional(),sequence:ge.array(ge.object({to:iu,transform:ge.unknown(),awaitSource:ge.boolean().optional()})).optional(),reads:ge.array(Jb).optional(),maxQueriesPerRun:ge.number().int().positive().max(32,`maxQueriesPerRun cannot exceed ${32}`).optional(),idempotencyKey:ge.unknown().optional(),cycleBudget:ge.number().int().positive().optional(),conflictStrategy:ge.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:ge.number().int().positive().optional(),description:ge.string().optional(),systemReserved:ge.boolean().optional()}).superRefine((t,e)=>{let r=t,n=r.to!==void 0||r.transform!==void 0,o=r.sequence!==void 0;n&&o?e.addIssue({code:"custom",path:["sequence"],message:"declare EITHER `to` + `transform` OR `sequence` \u2014 not both"}):!n&&!o?e.addIssue({code:"custom",path:["to"],message:"a conduit needs a target: `to` + `transform`, or an ordered `sequence` of them"}):o?(r.sequence.length===0&&e.addIssue({code:"custom",path:["sequence"],message:"sequence must declare at least one target"}),r.sequence.forEach((d,p)=>{typeof d.transform!="function"&&e.addIssue({code:"custom",path:["sequence",p,"transform"],message:"transform must be a function"}),r.from?.source&&d.to?.source&&r.from.source===d.to.source&&e.addIssue({code:"custom",path:["sequence",p,"to","source"],message:"a conduit must bridge two DIFFERENT sources (from.source === to.source) \u2014 use a hook for an intra-source transform"})})):(r.to===void 0&&e.addIssue({code:"custom",path:["to"],message:"`to` is required beside `transform`"}),typeof r.transform!="function"&&e.addIssue({code:"custom",path:["transform"],message:"transform must be a function"}));let s=t.from?.when;s!==void 0&&typeof s!="function"&&e.addIssue({code:"custom",path:["from","when"],message:"from.when, when present, must be a function"});let i=t.idempotencyKey;i!==void 0&&typeof i!="function"&&e.addIssue({code:"custom",path:["idempotencyKey"],message:"idempotencyKey, when present, must be a function"});let a=r.from,l=r.to;a?.source&&l?.source&&a.source===l.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"})}),au=ur({kind:"conduit",schema:Hi,factoryName:"defineConduit"})});var cu=j(()=>{lu();Fi()});import{z as $e}from"zod";var Ki,du,uu=j(()=>{gn();Ki=$e.object({id:$e.string().min(1,"process id must be non-empty"),input:$e.object({type:$e.literal("object"),properties:$e.record($e.unknown()).optional(),required:$e.array($e.string()).optional()}).passthrough(),steps:$e.array($e.object({id:$e.string().min(1,"step id must be non-empty"),recordType:$e.string().min(1,"step.recordType must be non-empty"),awaitSource:$e.boolean().optional(),build:$e.unknown(),description:$e.string().optional()})).min(1,"a process needs at least one step"),eachRow:$e.object({outstanding:$e.unknown(),key:$e.string().min(1,"eachRow.key must name the column that identifies an outstanding row")}).optional(),onFailure:$e.enum(["stop","rollback"]).optional(),description:$e.string().optional()}).superRefine((t,e)=>{let r=t.eachRow;r&&typeof r.outstanding!="function"&&e.addIssue({code:"custom",path:["eachRow","outstanding"],message:"eachRow.outstanding must be a function returning one PostgREST query for the rows still to migrate"});let n=t.steps;if(!Array.isArray(n))return;let o=new Map;n.forEach((s,i)=>{let a=s;if(typeof a.build!="function"&&e.addIssue({code:"custom",path:["steps",i,"build"],message:"build must be a function"}),typeof a.id=="string"){let l=o.get(a.id);l!==void 0?e.addIssue({code:"custom",path:["steps"],message:`duplicate step id '${a.id}' (steps ${l} and ${i}) \u2014 step ids must be unique within a process`}):o.set(a.id,i)}})}),du=ur({kind:"process",schema:Ki,factoryName:"defineProcess"})});var pu=j(()=>{});var mu=j(()=>{uu();pu()});async function sw(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 Oo(t,e={}){return(e.transform??sw)(t)}var Vi=j(()=>{});function Gi(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 hu(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Wi(t){return`${hu(t.source)}${hu(t.recordType)}`}function iw(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function aw(t){let e=[t.pgType];return t.label&&e.push(`"${t.label}"`),t.role==="display"&&t.displayFor?e.push(`display column for ${t.displayFor} \u2014 render this, filter/join on ${t.displayFor}`):t.role==="identifier"&&t.idFor?e.push(`identifier \u2014 render ${t.idFor} instead`):t.role&&e.push(t.role),t.format&&e.push(`format: ${t.format}`),t.currencyKey&&e.push(`currency from ${t.currencyKey}`),t.description&&e.push(t.description),e.join(" \xB7 ")}function Ji(t){let e=Wi(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]} */`:`/**
4
+ var zb=Object.create;var Ui=Object.defineProperty;var Bb=Object.getOwnPropertyDescriptor;var Fb=Object.getOwnPropertyNames;var Hb=Object.getPrototypeOf,Kb=Object.prototype.hasOwnProperty;var j=(t,e)=>()=>(t&&(e=t(t=0)),e);var U=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Yd=(t,e)=>{for(var r in e)Ui(t,r,{get:e[r],enumerable:!0})},Vb=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Fb(e))!Kb.call(t,o)&&o!==r&&Ui(t,o,{get:()=>e[o],enumerable:!(n=Bb(e,o))||n.enumerable});return t};var Xd=(t,e,r)=>(r=t!=null?zb(Hb(t)):{},Vb(e||!t||!t.__esModule?Ui(r,"default",{value:t,enumerable:!0}):r,t));function ur(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var gn=j(()=>{});import{z as pr}from"zod";function Eo(t){let e=Mi.safeParse(t);return e.success?(e.data.inputs??[]).filter(r=>r.type==="connection"):[]}function qi(t,e){let r=Mi.safeParse(t);if(!r.success)throw new Kt(`invalid manifest: ${r.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}`);if(Zd.test(e))throw new Kt('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(Zd.test(n))throw new Kt("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var Qd,eu,Mi,Kt,Zd,tu=j(()=>{Qd=pr.object({type:pr.literal("connection"),source_system:pr.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:pr.string().min(1).max(200).optional()}),eu=pr.discriminatedUnion("type",[Qd]),Mi=pr.object({inputs:pr.array(eu).optional()}).passthrough(),Kt=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};Zd=/\bconnection[_-]?id\b["']?\s*[:=]/i});var Po,zi=j(()=>{Po=["before_read","before_save","after_save","before_delete","after_delete","before_sync","after_sync","on_sync_failure"]});import{z as Fe}from"zod";var Bi,ru,nu=j(()=>{gn();zi();Bi=Fe.object({id:Fe.string().min(1,"hook id must be non-empty"),recordType:Fe.union([Fe.string().min(1),Fe.array(Fe.string().min(1)).min(1),Fe.literal("*")]),event:Fe.enum(Po),source:Fe.string().min(1).optional(),when:Fe.unknown().optional(),run:Fe.unknown(),failClosed:Fe.boolean().optional(),timeoutMs:Fe.number().int().positive().optional(),description:Fe.string().optional(),systemReserved:Fe.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"})}),ru=ur({kind:"hook",schema:Bi,factoryName:"defineHook"})});var ou=j(()=>{nu();zi()});var Ao,Fi=j(()=>{Ao=["after_canonicalize_inbound","after_sync_success_outbound"]});import{z as ge}from"zod";var su,Jb,iu,Hi,au,lu=j(()=>{gn();Fi();su=ge.string().regex(/^[a-z_][a-z0-9_]*$/i,"must be a bare column name (letters, digits, underscore)"),Jb=ge.object({recordType:ge.string().min(1,"reads[].recordType must be non-empty"),source:ge.string().min(1).optional(),columns:ge.array(su).min(1,"reads[].columns must name at least one column"),by:ge.array(su).optional(),maxRows:ge.number().int().positive().max(500,`reads[].maxRows cannot exceed ${500}`).optional()}),iu=ge.object({source:ge.string().min(1,"to.source must be non-empty"),recordType:ge.string().min(1,"to.recordType must be non-empty")}),Hi=ge.object({id:ge.string().min(1,"conduit id must be non-empty"),on:ge.enum(Ao),from:ge.object({source:ge.string().min(1,"from.source must be non-empty"),recordType:ge.string().min(1,"from.recordType must be non-empty"),when:ge.unknown().optional()}),to:iu.optional(),mode:ge.enum(["dual-bind","one-shot"]).optional(),transform:ge.unknown().optional(),sequence:ge.array(ge.object({to:iu,transform:ge.unknown(),awaitSource:ge.boolean().optional()})).optional(),reads:ge.array(Jb).optional(),maxQueriesPerRun:ge.number().int().positive().max(32,`maxQueriesPerRun cannot exceed ${32}`).optional(),idempotencyKey:ge.unknown().optional(),cycleBudget:ge.number().int().positive().optional(),conflictStrategy:ge.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:ge.number().int().positive().optional(),description:ge.string().optional(),systemReserved:ge.boolean().optional()}).superRefine((t,e)=>{let r=t,n=r.to!==void 0||r.transform!==void 0,o=r.sequence!==void 0;n&&o?e.addIssue({code:"custom",path:["sequence"],message:"declare EITHER `to` + `transform` OR `sequence` \u2014 not both"}):!n&&!o?e.addIssue({code:"custom",path:["to"],message:"a conduit needs a target: `to` + `transform`, or an ordered `sequence` of them"}):o?(r.sequence.length===0&&e.addIssue({code:"custom",path:["sequence"],message:"sequence must declare at least one target"}),r.sequence.forEach((d,p)=>{typeof d.transform!="function"&&e.addIssue({code:"custom",path:["sequence",p,"transform"],message:"transform must be a function"}),r.from?.source&&d.to?.source&&r.from.source===d.to.source&&e.addIssue({code:"custom",path:["sequence",p,"to","source"],message:"a conduit must bridge two DIFFERENT sources (from.source === to.source) \u2014 use a hook for an intra-source transform"})})):(r.to===void 0&&e.addIssue({code:"custom",path:["to"],message:"`to` is required beside `transform`"}),typeof r.transform!="function"&&e.addIssue({code:"custom",path:["transform"],message:"transform must be a function"}));let s=t.from?.when;s!==void 0&&typeof s!="function"&&e.addIssue({code:"custom",path:["from","when"],message:"from.when, when present, must be a function"});let i=t.idempotencyKey;i!==void 0&&typeof i!="function"&&e.addIssue({code:"custom",path:["idempotencyKey"],message:"idempotencyKey, when present, must be a function"});let a=r.from,l=r.to;a?.source&&l?.source&&a.source===l.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"})}),au=ur({kind:"conduit",schema:Hi,factoryName:"defineConduit"})});var cu=j(()=>{lu();Fi()});import{z as $e}from"zod";var Ki,du,uu=j(()=>{gn();Ki=$e.object({id:$e.string().min(1,"process id must be non-empty"),input:$e.object({type:$e.literal("object"),properties:$e.record($e.unknown()).optional(),required:$e.array($e.string()).optional()}).passthrough(),steps:$e.array($e.object({id:$e.string().min(1,"step id must be non-empty"),recordType:$e.string().min(1,"step.recordType must be non-empty"),awaitSource:$e.boolean().optional(),build:$e.unknown(),description:$e.string().optional()})).min(1,"a process needs at least one step"),eachRow:$e.object({outstanding:$e.unknown(),key:$e.string().min(1,"eachRow.key must name the column that identifies an outstanding row")}).optional(),onFailure:$e.enum(["stop","rollback"]).optional(),description:$e.string().optional()}).superRefine((t,e)=>{let r=t.eachRow;r&&typeof r.outstanding!="function"&&e.addIssue({code:"custom",path:["eachRow","outstanding"],message:"eachRow.outstanding must be a function returning one PostgREST query for the rows still to migrate"});let n=t.steps;if(!Array.isArray(n))return;let o=new Map;n.forEach((s,i)=>{let a=s;if(typeof a.build!="function"&&e.addIssue({code:"custom",path:["steps",i,"build"],message:"build must be a function"}),typeof a.id=="string"){let l=o.get(a.id);l!==void 0?e.addIssue({code:"custom",path:["steps"],message:`duplicate step id '${a.id}' (steps ${l} and ${i}) \u2014 step ids must be unique within a process`}):o.set(a.id,i)}})}),du=ur({kind:"process",schema:Ki,factoryName:"defineProcess"})});var pu=j(()=>{});var hu=j(()=>{uu();pu()});async function sw(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 Oo(t,e={}){return(e.transform??sw)(t)}var Vi=j(()=>{});function Gi(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 mu(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Wi(t){return`${mu(t.source)}${mu(t.recordType)}`}function iw(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function aw(t){let e=[t.pgType];return t.label&&e.push(`"${t.label}"`),t.role==="display"&&t.displayFor?e.push(`display column for ${t.displayFor} \u2014 render this, filter/join on ${t.displayFor}`):t.role==="identifier"&&t.idFor?e.push(`identifier \u2014 render ${t.idFor} instead`):t.role&&e.push(t.role),t.format&&e.push(`format: ${t.format}`),t.currencyKey&&e.push(`currency from ${t.currencyKey}`),t.description&&e.push(t.description),e.join(" \xB7 ")}function Ji(t){let e=Wi(t),r=[`${t.source}:${t.recordType}`+(t.table?` \u2192 turbobase.${t.table}`:" (no backing table)")+`${t.listOnly?" (list-only)":""} \u2014 origin: ${t.origin}.`];t.description&&r.push(t.description);let n=r.length===1?`/** ${r[0]} */`:`/**
5
5
  * ${r.join(`
6
6
  * `)}
7
7
  */`;if(t.columns.length===0)return`${n}
@@ -16,14 +16,14 @@ ${o.join(`
16
16
  }`}function No(t){return[...t.records].sort((n,o)=>`${n.source}:${n.recordType}`.localeCompare(`${o.source}:${o.recordType}`)).map(Ji).join(`
17
17
 
18
18
  `)}function fu(t){let e=new Map,r=(o,s)=>{let i=e.get(o);i||e.set(o,i=new Map);for(let a of s)i.set(a.name,(i.get(a.name)??!0)&&a.nullable)};for(let o of t.records){o.table&&r(o.table,o.columns);for(let s of o.lines??[])r(s.table,s.columns)}let n={};for(let[o,s]of[...e].sort(([i],[a])=>i.localeCompare(a))){let i=["line_index","line_number"].find(a=>s.get(a)===!1);if(s.get("parent_pg_row_id")===!1&&i){n[o]=["parent_pg_row_id",i];continue}if(s.get("pg_row_id")===!1){n[o]="pg_row_id";continue}if(s.get("external_id")===!1){n[o]="external_id";continue}}return n}function lw(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function Yi(t){let e=fu(t);return["/**"," * The seek key each table can be keyset-paged on \u2014 pass it to `selectPage`:"," *"," * selectPage(`vendor_credit?select=*`, { sortKey: SEEK_KEYS.vendor_credit })"," *"," * A seek key must be NOT NULL and UNIQUE. Hard-coding one instead goes stale"," * silently: a table that gains `pg_row_id` has its `external_id` made"," * nullable in the same change, and seeking on a nullable column drops rows",' * with no error \u2014 the column still exists, so an "is it there?" check on the'," * override stays green. Read it from here and regenerating types fixes it."," *"," * An entry may be a TUPLE, and it is passed exactly the same way. A line"," * table is keyed `(parent_pg_row_id, line_index)` and has no correct single"," * column \u2014 every line of one parent shares `parent_pg_row_id`, and"," * `line_index` is unique only within a parent \u2014 so `selectPage` seeks the"," * pair with a row-wise comparison."," *"," * A table with no entry has no keyset-safe key at all; page it by filtering"," * to a bounded subset rather than seeking across the whole table."," */","export const SEEK_KEYS = {",...Object.entries(e).map(([n,o])=>{let s=Array.isArray(o)?`[${o.map(i=>`'${i}'`).join(", ")}]`:`'${o}'`;return` ${lw(n)}: ${s},`}),"} as const satisfies Record<string, string | readonly string[]>;","","/** Tables with a keyset-safe seek key. */","export type SeekableTable = keyof typeof SEEK_KEYS;"].join(`
19
- `)}var Xi=j(()=>{});function cw(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function gu(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 mr(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let r=cw(t.baseUrl),n=await gu(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=No(n),s=[dw,"// ----- Record shapes (from /v1/catalog/records) -----",o,"// ----- Keyset seek keys (derived from column nullability) -----",Yi(n)];if(!t.recordsOnly){let i=await gu(r.openapi,t.token,e),a=await Oo(i,t.openApi);s.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return s.join(`
19
+ `)}var Xi=j(()=>{});function cw(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function gu(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 hr(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let r=cw(t.baseUrl),n=await gu(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=No(n),s=[dw,"// ----- Record shapes (from /v1/catalog/records) -----",o,"// ----- Keyset seek keys (derived from column nullability) -----",Yi(n)];if(!t.recordsOnly){let i=await gu(r.openapi,t.token,e),a=await Oo(i,t.openApi);s.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return s.join(`
20
20
 
21
21
  `)+`
22
22
  `}var dw,yu=j(()=>{Vi();Xi();Xi();Vi();dw=["/**"," * GENERATED by `turbobase project types` (@turbobase/extensions). DO NOT EDIT."," *"," * Record shapes from /v1/catalog/records + PostgREST operations from"," * /v1/catalog/openapi.json, RLS-scoped to the token used to generate this."," */","","/* eslint-disable */"].join(`
23
- `)});var Zi=j(()=>{gn();tu();ou();cu();mu();yu()});import{homedir as uw}from"node:os";import{join as bu}from"node:path";import{promises as Qi}from"node:fs";function rt(t){return t.trim().replace(/\/+$/,"")}function Lo(){let t=process.env.TURBOBASE_HOME??bu(uw(),".turbobase");return{dir:t,file:bu(t,"credentials")}}function wu(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function yn(){let{file:t}=Lo(),e;try{let s=await Qi.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))wu(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))wu(i)&&(n[s]={token:i.token,updatedAt:i.updatedAt});return{active:pw(n),tenants:n}}function pw(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 ea(t){let{dir:e,file:r}=Lo();await Qi.mkdir(e,{recursive:!0,mode:448}),await Qi.writeFile(r,JSON.stringify(t,null,2)+`
24
- `,{mode:384})}async function vu(t){let e=rt(t.baseUrl),r=await yn(),n=new Date().toISOString();return r.tenants[e]={token:t.token,updatedAt:n},r.active=e,await ea(r),{baseUrl:e,token:t.token,updatedAt:n}}async function mt(t){let e=await yn();if(t){let s=rt(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 jo(t){let e=rt(t),r=await yn(),n=r.tenants[e];return n?(r.active=e,await ea(r),{baseUrl:e,token:n.token,updatedAt:n.updatedAt}):null}async function ta(t){let e=await yn(),r=t?rt(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 ea(e),r}async function Ot(){let t=await yn();return Object.entries(t.tenants).map(([e,r])=>({baseUrl:e,token:r.token,updatedAt:r.updatedAt}))}var bn=j(()=>{});function na(t,e){return t!==503?!1:typeof e=="string"?!0:e?.error==="instance_unavailable"}function mw(t){if(t)try{return JSON.parse(t)}catch{return t}}function hw(t,e){if(!t)return null;let r=t.trim();if(/^\d+$/.test(r))return Number(r)*1e3;let n=Date.parse(r);return Number.isNaN(n)?null:Math.max(0,n-e)}function fw(t){let e=/retry\s+after\s+(\d+)\s*s/i.exec(t);return e?Number(e[1])*1e3:null}async function gw(t,e){let r=hw(t.headers?.get?.("retry-after"),e),n="";try{n=await t.clone().text()}catch{return{maintenance:!1,delayMs:r}}let o=mw(n),s=na(t.status,o),i=typeof o?.error=="string"?o.error:void 0;return{maintenance:s,delayMs:r??fw(n),error:i}}function yw(t){return!!(t==null||typeof t=="string"||typeof ArrayBuffer<"u"&&ArrayBuffer.isView(t)||t instanceof ArrayBuffer||typeof URLSearchParams<"u"&&t instanceof URLSearchParams||typeof Blob<"u"&&t instanceof Blob)}function _u(t){try{let e=typeof t=="string"?t:t instanceof URL?t.href:t?.url??"";return e?new URL(e).host:"the instance"}catch{return"the instance"}}function ra(t){return`${Math.round(t/1e3)}s`}function bw(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: ${t.host} is unavailable${e} \u2014 waiting ${ra(t.delayMs)} before retrying (${ra(t.remainingMs)} of the retry budget left).
23
+ `)});var Zi=j(()=>{gn();tu();ou();cu();hu();yu()});import{homedir as uw}from"node:os";import{join as bu}from"node:path";import{promises as Qi}from"node:fs";function rt(t){return t.trim().replace(/\/+$/,"")}function Lo(){let t=process.env.TURBOBASE_HOME??bu(uw(),".turbobase");return{dir:t,file:bu(t,"credentials")}}function wu(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function yn(){let{file:t}=Lo(),e;try{let s=await Qi.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))wu(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))wu(i)&&(n[s]={token:i.token,updatedAt:i.updatedAt});return{active:pw(n),tenants:n}}function pw(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 ea(t){let{dir:e,file:r}=Lo();await Qi.mkdir(e,{recursive:!0,mode:448}),await Qi.writeFile(r,JSON.stringify(t,null,2)+`
24
+ `,{mode:384})}async function vu(t){let e=rt(t.baseUrl),r=await yn(),n=new Date().toISOString();return r.tenants[e]={token:t.token,updatedAt:n},r.active=e,await ea(r),{baseUrl:e,token:t.token,updatedAt:n}}async function ht(t){let e=await yn();if(t){let s=rt(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 jo(t){let e=rt(t),r=await yn(),n=r.tenants[e];return n?(r.active=e,await ea(r),{baseUrl:e,token:n.token,updatedAt:n.updatedAt}):null}async function ta(t){let e=await yn(),r=t?rt(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 ea(e),r}async function Ot(){let t=await yn();return Object.entries(t.tenants).map(([e,r])=>({baseUrl:e,token:r.token,updatedAt:r.updatedAt}))}var bn=j(()=>{});function na(t,e){return t!==503?!1:typeof e=="string"?!0:e?.error==="instance_unavailable"}function hw(t){if(t)try{return JSON.parse(t)}catch{return t}}function mw(t,e){if(!t)return null;let r=t.trim();if(/^\d+$/.test(r))return Number(r)*1e3;let n=Date.parse(r);return Number.isNaN(n)?null:Math.max(0,n-e)}function fw(t){let e=/retry\s+after\s+(\d+)\s*s/i.exec(t);return e?Number(e[1])*1e3:null}async function gw(t,e){let r=mw(t.headers?.get?.("retry-after"),e),n="";try{n=await t.clone().text()}catch{return{maintenance:!1,delayMs:r}}let o=hw(n),s=na(t.status,o),i=typeof o?.error=="string"?o.error:void 0;return{maintenance:s,delayMs:r??fw(n),error:i}}function yw(t){return!!(t==null||typeof t=="string"||typeof ArrayBuffer<"u"&&ArrayBuffer.isView(t)||t instanceof ArrayBuffer||typeof URLSearchParams<"u"&&t instanceof URLSearchParams||typeof Blob<"u"&&t instanceof Blob)}function _u(t){try{let e=typeof t=="string"?t:t instanceof URL?t.href:t?.url??"";return e?new URL(e).host:"the instance"}catch{return"the instance"}}function ra(t){return`${Math.round(t/1e3)}s`}function bw(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: ${t.host} is unavailable${e} \u2014 waiting ${ra(t.delayMs)} before retrying (${ra(t.remainingMs)} of the retry budget left).
25
25
  `)}function ww(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: gave up after ${ra(t.waitedMs)} waiting for ${t.host} to come back${e}; ${t.attempts} ${t.attempts===1?"retry":"retries"} made.
26
- `)}function Do(t,e={}){let r=e.budgetMs??6e5,n=e.defaultDelayMs??6e4,o=e.sleep??(d=>new Promise(p=>setTimeout(p,d))),s=e.now??(()=>Date.now()),i=e.onWait??bw,a=e.onGiveUp??ww;return async(d,p)=>{let f=s(),_=0;for(;;){let y=await t(d,p);if(y.status!==503||p&&!yw(p.body))return y;let k=r-(s()-f),{maintenance:R,delayMs:$,error:P}=await gw(y,s());if(!R)return y;if(k<=0)return _>0&&a({waitedMs:s()-f,attempts:_,host:_u(d),error:P}),y;let I=$??n;I=Math.min(Math.max(I,1e3),12e4),I=Math.min(I,k),_+=1,i({attempt:_,delayMs:I,remainingMs:k,host:_u(d),error:P}),await o(I)}}}var oa=j(()=>{});function Su(t){if(typeof t=="string")return t.trim();if(!t||typeof t!="object")return"";let e=t,r=typeof e.message=="string"&&e.message?e.message:e.error;return typeof r=="string"?r.trim():""}function vw(t){let e=t.trimStart().slice(0,200).toLowerCase();return e.startsWith("<!doctype")||e.startsWith("<html")||e.startsWith("<")}function ku(t){let e=Su(t);return typeof t=="string"&&vw(e)?_w:e.slice(0,200)}function Tu(t,e){return na(t,e)}function xu(t){return t instanceof Q&&Tu(t.status,t.body)}function kw(){let t=(process.env.TURBOBASE_DEBUG??"").trim().toLowerCase();return t!==""&&t!=="0"&&t!=="false"}function Ru(t){return t.replace(/\/+$/,"")}function sa(t=process.env){let e=(t[Cr]??"").trim(),r=(t[Uo]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function ia(t){let e;try{e=new URL(t)}catch{return`${Cr} 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:`${Cr} 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 Q,_w,Sw,q,Cr,Uo,wn,ht=j(()=>{oa();Q=class extends Error{constructor(r,n,o){super(r);this.status=n;this.body=o;this.name="ApiError"}status;body};_w="the request did not reach the instance \u2014 a proxy or edge answered with an HTML page, so the server gave no detail";Sw="this instance is temporarily unavailable \u2014 it is upgrading or restarting. Retry shortly.";q=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=Ru(e.baseUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("ExtensionsApi: no fetch implementation available");this.fetchImpl=e.retry===!1?r:Do(r,e.retry??{})}async request(e,r,n,o){let s=await this.fetchImpl(`${this.baseUrl}${r}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/json",...n!==void 0?{"Content-Type":"application/json"}:{},...o??{}},...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await s.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!s.ok){if(kw()){let d=Su(a);throw new Q(`${e} ${r} \u2192 ${s.status}${d?`: ${d}`:""}`,s.status,a)}if(Tu(s.status,a))throw new Q(Sw,s.status,a);let l=ku(a);throw new Q(`${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"})}authorConduit(e){return this.request("POST","/v1/extensions/author-conduit",{intent:e.intent,from:e.from,to:e.to,...e.intentId?{intentId:e.intentId}:{},...e.columns?.length?{columns:e.columns}:{}})}async proposals(e={}){let r=new URLSearchParams;e.status?.length&&r.set("status",e.status.join(",")),e.provenance?.length&&r.set("provenance",e.provenance.join(",")),e.recordType&&r.set("recordType",e.recordType),e.source&&r.set("source",e.source),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString();return(await this.request("GET",`/v1/extensions/proposals${n?`?${n}`:""}`)).proposals??[]}proposalPromote(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/promote`,{})}proposalRetract(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/retract`,{})}proposalReject(e,r){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/reject`,r?{reason:r}:{})}extensionDisable(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/disable`,{})}extensionEnable(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/enable`,{})}extensionRemove(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/remove`,{})}async logs(e,r){let n=r&&r>0?`?limit=${Math.floor(r)}`:"";return(await this.request("GET",`/v1/extensions/${encodeURIComponent(e)}/logs${n}`)).logs??[]}async catalogRecords(){return(await this.request("GET","/v1/catalog/records")).records??[]}async conduitEvents(e,r={}){let n=new URLSearchParams;r.since&&n.set("since",r.since),r.limit&&r.limit>0&&n.set("limit",String(Math.floor(r.limit)));let o=n.toString()?`?${n.toString()}`:"";return(await this.request("GET",`/v1/conduits/${encodeURIComponent(e)}/events${o}`)).events??[]}async platformEvents(e={}){let r=new URLSearchParams;e.subsystem&&r.set("subsystem",e.subsystem),e.severity&&r.set("severity",e.severity),e.code&&r.set("code",e.code),e.since&&r.set("since",e.since),e.after&&r.set("after",e.after),e.correlationId&&r.set("correlationId",e.correlationId),e.extension&&r.set("extension",e.extension),e.conduit&&r.set("conduit",e.conduit),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/events${n}`)).events??[]}async bindings(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/bindings${n}`)).bindings??[]}async appsList(){return(await this.request("GET","/v1/apps")).apps??[]}appsCreate(e){return this.request("POST","/v1/apps",{slug:e.slug,name:e.name??e.slug,description:e.description})}appsPull(e){return this.request("GET",`/v1/apps/${encodeURIComponent(e)}/pull`)}appPullContext(e){return this.request("GET",`/v1/apps/proposals/${encodeURIComponent(e)}/pull-context`)}appsPush(e,r,n={}){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/push`,{files:r,...n.note?{note:n.note}:{},...n.meta?{meta:n.meta}:{}},n.proposalId?{"x-proposal-id":n.proposalId}:void 0)}learningsPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.section&&r.set("section",e.section),e.limit!==void 0&&r.set("limit",String(e.limit)),e.group===!1&&r.set("group","false");let n=r.toString();return this.request("GET",`/v1/learnings/pending${n?`?${n}`:""}`)}learningsIngest(e){return this.request("POST","/v1/learnings/ingest",{...e?{app:e}:{}})}rulesPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.limit!==void 0&&r.set("limit",String(e.limit)),e.group===!1&&r.set("group","false"),e.reapply&&r.set("reapply","true");let n=r.toString();return this.request("GET",`/v1/learnings/rules-pending${n?`?${n}`:""}`)}rulesPush(e,r={}){return this.request("POST","/v1/learnings/push-rules",{planToken:e,...r.app?{app:r.app}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{},...r.reapply?{reapply:!0}:{}})}skillsList(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status);let n=r.toString();return this.request("GET",`/v1/skills${n?`?${n}`:""}`)}appSkillsPush(e,r,n){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/skills`,{skills:[...r],dryRun:n})}skillsPublish(e){return this.request("POST","/v1/skills/publish",{slugs:[...e]})}skillsUnpublish(e){return this.request("POST","/v1/skills/unpublish",{slugs:[...e]})}skillsRollback(e){return this.request("POST","/v1/skills/rollback",{versionNo:e})}skillsReleases(){return this.request("GET","/v1/skills/releases")}skillsDelete(e){return this.request("DELETE",`/v1/skills/${encodeURIComponent(e)}`)}docsList(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status);let n=r.toString();return this.request("GET",`/v1/docs${n?`?${n}`:""}`)}docsPublish(e){return this.request("POST","/v1/docs/publish",{slugs:[...e]})}docsUnpublish(e){return this.request("POST","/v1/docs/unpublish",{slugs:[...e]})}docsVersions(){return this.request("GET","/v1/docs/versions")}docsRollback(e){return this.request("POST","/v1/docs/rollback",{versionNo:e})}docsDelete(e){return this.request("DELETE",`/v1/docs/${encodeURIComponent(e)}`)}learningsPushKb(e,r={}){return this.request("POST","/v1/learnings/push-kb",{planToken:e,...r.app?{app:r.app}:{},...r.section?{section:r.section}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{}})}retryBinding(e){return this.request("POST",`/v1/bindings/${encodeURIComponent(e)}/retry`)}configExport(){return this.request("GET","/v1/config/export")}configPlan(e){return this.request("POST","/v1/config/plan",{bundle:e})}configApply(e,r={}){return this.request("POST","/v1/config/apply",{bundle:e,...r.prune?{prune:!0}:{}})}async tablesList(){return(await this.request("GET","/v1/tables")).tables??[]}tablesPlan(e){return this.request("POST","/v1/tables/plan",e)}appsPlan(e){return this.request("POST","/v1/apps/plan",{writes:e.writes??[],...e.roles!==void 0?{roles:e.roles}:{},labels:e.labels??[],...e.app?{app:e.app}:{}})}tablesApply(e){return this.request("POST","/v1/tables/apply",e)}tablesDrop(e,r){return this.request("DELETE",`/v1/tables/${encodeURIComponent(e)}?confirm=${encodeURIComponent(r)}`)}async guardrailsList(){return(await this.request("GET","/v1/guardrails")).guardrails??[]}async guardrailCreate(e){return(await this.request("POST","/v1/guardrails",e)).guardrail}async guardrailUpdate(e,r){return(await this.request("PATCH",`/v1/guardrails/${encodeURIComponent(e)}`,r)).guardrail}guardrailDelete(e){return this.request("DELETE",`/v1/guardrails/${encodeURIComponent(e)}`)}guardrailTest(e){return this.request("POST","/v1/guardrails/test",e)}guardrailPostureGet(){return this.request("GET","/v1/guardrails/posture")}guardrailPostureSet(e){return this.request("PUT","/v1/guardrails/posture",{mode:e})}releaseDeploy(e){return this.request("POST","/v1/releases/deploy",{...e.solutionId?{solutionId:e.solutionId}:{},target:e.target,...e.approvedBy?{approvedBy:e.approvedBy}:{},...e.files?{files:e.files}:{},...e.gitRepo?{gitRepo:e.gitRepo}:{},...e.gitRef?{gitRef:e.gitRef}:{},...e.gitSha?{gitSha:e.gitSha}:{},...e.prUrl?{prUrl:e.prUrl}:{}})}async releaseList(){return(await this.request("GET","/v1/releases")).releases??[]}releaseGet(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}`)}releaseFiles(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/files`)}releasePush(e,r){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/push`,{files:r.files,target:r.target,...r.approvedBy?{approvedBy:r.approvedBy}:{}})}releaseStatus(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/status`)}releaseRollback(e){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/rollback`)}},Cr="TURBOBASE_REGISTRY_URL",Uo="TURBOBASE_REGISTRY_TOKEN";wn=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=Ru(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=ku(a);throw new Q(`${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}:{}})}}});import{existsSync as Tw,statSync as xw}from"node:fs";import{resolve as Mo,sep as $u}from"node:path";function Eu(t){if($w.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits|processes)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function Pw(t,e,r){let n=Mo(e,r),o=Mo(t);if(n!==o&&!n.startsWith(o+$u))return null;let s=[n];/\.(js|mjs|cjs)$/.test(n)&&s.push(n.replace(/\.js$/,".ts"),n.replace(/\.mjs$/,".mts"),n.replace(/\.cjs$/,".cts")),/\.[cm]?[jt]sx?$/.test(n)||s.push(`${n}.ts`,`${n}.tsx`,`${n}.js`,`${n}/index.ts`,`${n}/index.js`);for(let i of s)if(i.startsWith(o+$u)&&Tw(i)&&xw(i).isFile())return i;return null}function Pu(t){return{name:"extension-self-contained-fence",setup(e){e.onResolve({filter:/.*/},r=>{if(r.kind==="entry-point")return null;if(Eu(r.path))return{path:r.path,namespace:"extension-sdk"};let n=r.path.startsWith(".")||r.path.startsWith("/");if(n&&t){let s=Pw(t,r.resolveDir,r.path);if(s)return{path:s}}return{errors:[{text:`extension ${n?`imports a sibling/local file ('${r.path}')${t?" that does not resolve inside the extension\u2019s own directory":""}`:r.path.startsWith("node:")||Cw(r.path)?`imports a Node builtin ('${r.path}')`:`imports an external module ('${r.path}')`} \u2014 sandboxed extensions must be self-contained. The ONLY allowed imports are the SDK factory ('@/sync/hooks' or '@turbobase/extensions') and a relative sibling inside the extension's own directory; inline everything else into the extension file.`}]}}),e.onLoad({filter:/.*/,namespace:"extension-sdk"},()=>({contents:Ew,loader:"js"}))}}}function Cw(t){let e=t.startsWith("node:")?t.slice(5):t;return Aw.has(e.split("/")[0])}function Au(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 Cu(){try{return(await import("esbuild")).build}catch(t){throw Au("esbuild",t)}}async function Iw(){try{return(await import("isolated-vm")).default}catch(t){throw Au("isolated-vm",t)}}async function Bo(t,e={}){let r=await Cu(),n=e.resolveDir?Mo(e.resolveDir):void 0,o;try{o=await r({stdin:{contents:t,loader:"ts",resolveDir:n??process.cwd(),sourcefile:"extension.ts"},bundle:!0,write:!1,format:"iife",globalName:"__tb_extension_module",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[Pu(n)]})}catch(s){let a=s.errors?.map(l=>l.text).filter(Boolean).join("; ");throw new qo(a||`extension bundle failed: ${String(s)}`)}return o.outputFiles?.[0]?.text??""}async function aa(t,e){if(!/(^|\n)\s*(import|export)\s[^;]*?from\s*['"](\.|\/)/.test(t)&&!/\bimport\s*\(\s*['"](\.|\/)/.test(t))return t;let r=await Cu(),n=Mo(e),o=Pu(n),s={name:"extension-sdk-external",setup(a){a.onResolve({filter:/.*/},l=>l.kind==="entry-point"?null:Eu(l.path)?{path:l.path,external:!0}:null)}},i;try{i=await r({stdin:{contents:t,loader:"ts",resolveDir:n,sourcefile:"extension.ts"},bundle:!0,write:!1,format:"esm",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[s,o]})}catch(a){let d=a.errors?.map(p=>p.text).filter(Boolean).join("; ");throw new qo(d||`extension bundle failed: ${String(a)}`)}return i.outputFiles?.[0]?.text??t}async function vn(t,e,r={}){let n=r.timeoutMs??zo,o=r.memoryLimitMb??Rw,s=r.member??"run",i={patches:[],logs:[]},a=await Iw(),l=new a.Isolate({memoryLimit:o});try{let d=await l.createContext(),p=d.global,f=new a.Callback(Y=>{let F=JSON.parse(String(Y));i.rejection||(i.rejection=F)}),_=new a.Callback(Y=>{i.patches.push(JSON.parse(String(Y)))}),y=new a.Callback(Y=>{let F=JSON.parse(String(Y));i.logs.push(F)}),k=new a.Callback(Y=>{i.result=JSON.parse(String(Y))}),R=r.query,$=new a.Reference(async Y=>{if(!R)throw new Error("ctx.query is not available in this context");return JSON.stringify(await R(String(Y)))});await p.set("__tb_reject",f),await p.set("__tb_patch",_),await p.set("__tb_log",y),await p.set("__tb_result",k),await p.set("__tb_query",$),await p.set("__tb_ctx_json",JSON.stringify(Ow(e)));let P=Lw(t,s,r.stepIndex??0,!!r.query),D=await(await l.compileScript(P)).run(d,{timeout:n,promise:!0});return s==="when"?{effects:i,whenResult:!!D}:{effects:i}}finally{l.isDisposed||l.dispose()}}function Ow(t){return{recordType:t.recordType,event:t.event,direction:t.direction,origin:t.origin,source:t.source,payload:t.payload??null,prior:t.prior??null,user:t.user??null,tenantConfig:t.tenantConfig??{},metadata:t.metadata??null,bindings:t.bindings??null,atlasLinks:t.atlasLinks??null,materialized:t.materialized??null,process:t.process??null}}function Nw(t){return`
26
+ `)}function Do(t,e={}){let r=e.budgetMs??6e5,n=e.defaultDelayMs??6e4,o=e.sleep??(d=>new Promise(p=>setTimeout(p,d))),s=e.now??(()=>Date.now()),i=e.onWait??bw,a=e.onGiveUp??ww;return async(d,p)=>{let f=s(),_=0;for(;;){let y=await t(d,p);if(y.status!==503||p&&!yw(p.body))return y;let k=r-(s()-f),{maintenance:R,delayMs:$,error:P}=await gw(y,s());if(!R)return y;if(k<=0)return _>0&&a({waitedMs:s()-f,attempts:_,host:_u(d),error:P}),y;let I=$??n;I=Math.min(Math.max(I,1e3),12e4),I=Math.min(I,k),_+=1,i({attempt:_,delayMs:I,remainingMs:k,host:_u(d),error:P}),await o(I)}}}var oa=j(()=>{});function Su(t){if(typeof t=="string")return t.trim();if(!t||typeof t!="object")return"";let e=t,r=typeof e.message=="string"&&e.message?e.message:e.error;return typeof r=="string"?r.trim():""}function vw(t){let e=t.trimStart().slice(0,200).toLowerCase();return e.startsWith("<!doctype")||e.startsWith("<html")||e.startsWith("<")}function ku(t){let e=Su(t);return typeof t=="string"&&vw(e)?_w:e.slice(0,200)}function Tu(t,e){return na(t,e)}function xu(t){return t instanceof Q&&Tu(t.status,t.body)}function kw(){let t=(process.env.TURBOBASE_DEBUG??"").trim().toLowerCase();return t!==""&&t!=="0"&&t!=="false"}function Ru(t){return t.replace(/\/+$/,"")}function sa(t=process.env){let e=(t[Cr]??"").trim(),r=(t[Uo]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function ia(t){let e;try{e=new URL(t)}catch{return`${Cr} 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:`${Cr} 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 Q,_w,Sw,q,Cr,Uo,wn,mt=j(()=>{oa();Q=class extends Error{constructor(r,n,o){super(r);this.status=n;this.body=o;this.name="ApiError"}status;body};_w="the request did not reach the instance \u2014 a proxy or edge answered with an HTML page, so the server gave no detail";Sw="this instance is temporarily unavailable \u2014 it is upgrading or restarting. Retry shortly.";q=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=Ru(e.baseUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("ExtensionsApi: no fetch implementation available");this.fetchImpl=e.retry===!1?r:Do(r,e.retry??{})}async request(e,r,n,o){let s=await this.fetchImpl(`${this.baseUrl}${r}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/json",...n!==void 0?{"Content-Type":"application/json"}:{},...o??{}},...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await s.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!s.ok){if(kw()){let d=Su(a);throw new Q(`${e} ${r} \u2192 ${s.status}${d?`: ${d}`:""}`,s.status,a)}if(Tu(s.status,a))throw new Q(Sw,s.status,a);let l=ku(a);throw new Q(`${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"})}authorConduit(e){return this.request("POST","/v1/extensions/author-conduit",{intent:e.intent,from:e.from,to:e.to,...e.intentId?{intentId:e.intentId}:{},...e.columns?.length?{columns:e.columns}:{}})}async proposals(e={}){let r=new URLSearchParams;e.status?.length&&r.set("status",e.status.join(",")),e.provenance?.length&&r.set("provenance",e.provenance.join(",")),e.recordType&&r.set("recordType",e.recordType),e.source&&r.set("source",e.source),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString();return(await this.request("GET",`/v1/extensions/proposals${n?`?${n}`:""}`)).proposals??[]}proposalPromote(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/promote`,{})}proposalRetract(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/retract`,{})}proposalReject(e,r){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/reject`,r?{reason:r}:{})}extensionDisable(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/disable`,{})}extensionEnable(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/enable`,{})}extensionRemove(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/remove`,{})}async logs(e,r){let n=r&&r>0?`?limit=${Math.floor(r)}`:"";return(await this.request("GET",`/v1/extensions/${encodeURIComponent(e)}/logs${n}`)).logs??[]}async catalogRecords(){return(await this.request("GET","/v1/catalog/records")).records??[]}async conduitEvents(e,r={}){let n=new URLSearchParams;r.since&&n.set("since",r.since),r.limit&&r.limit>0&&n.set("limit",String(Math.floor(r.limit)));let o=n.toString()?`?${n.toString()}`:"";return(await this.request("GET",`/v1/conduits/${encodeURIComponent(e)}/events${o}`)).events??[]}async platformEvents(e={}){let r=new URLSearchParams;e.subsystem&&r.set("subsystem",e.subsystem),e.severity&&r.set("severity",e.severity),e.code&&r.set("code",e.code),e.since&&r.set("since",e.since),e.after&&r.set("after",e.after),e.correlationId&&r.set("correlationId",e.correlationId),e.extension&&r.set("extension",e.extension),e.conduit&&r.set("conduit",e.conduit),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/events${n}`)).events??[]}async bindings(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/bindings${n}`)).bindings??[]}async appsList(){return(await this.request("GET","/v1/apps")).apps??[]}appsCreate(e){return this.request("POST","/v1/apps",{slug:e.slug,name:e.name??e.slug,description:e.description})}appsPull(e){return this.request("GET",`/v1/apps/${encodeURIComponent(e)}/pull`)}appPullContext(e){return this.request("GET",`/v1/apps/proposals/${encodeURIComponent(e)}/pull-context`)}appsPush(e,r,n={}){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/push`,{files:r,...n.note?{note:n.note}:{},...n.meta?{meta:n.meta}:{}},n.proposalId?{"x-proposal-id":n.proposalId}:void 0)}learningsPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.section&&r.set("section",e.section),e.limit!==void 0&&r.set("limit",String(e.limit)),e.group===!1&&r.set("group","false");let n=r.toString();return this.request("GET",`/v1/learnings/pending${n?`?${n}`:""}`)}learningsIngest(e){return this.request("POST","/v1/learnings/ingest",{...e?{app:e}:{}})}rulesPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.limit!==void 0&&r.set("limit",String(e.limit)),e.group===!1&&r.set("group","false"),e.reapply&&r.set("reapply","true");let n=r.toString();return this.request("GET",`/v1/learnings/rules-pending${n?`?${n}`:""}`)}rulesPush(e,r={}){return this.request("POST","/v1/learnings/push-rules",{planToken:e,...r.app?{app:r.app}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{},...r.reapply?{reapply:!0}:{}})}skillsList(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status);let n=r.toString();return this.request("GET",`/v1/skills${n?`?${n}`:""}`)}appSkillsPush(e,r,n){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/skills`,{skills:[...r],dryRun:n})}skillsPublish(e){return this.request("POST","/v1/skills/publish",{slugs:[...e]})}skillsUnpublish(e){return this.request("POST","/v1/skills/unpublish",{slugs:[...e]})}skillsRollback(e){return this.request("POST","/v1/skills/rollback",{versionNo:e})}skillsReleases(){return this.request("GET","/v1/skills/releases")}skillsDelete(e){return this.request("DELETE",`/v1/skills/${encodeURIComponent(e)}`)}docsList(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status);let n=r.toString();return this.request("GET",`/v1/docs${n?`?${n}`:""}`)}docsPublish(e){return this.request("POST","/v1/docs/publish",{slugs:[...e]})}docsUnpublish(e){return this.request("POST","/v1/docs/unpublish",{slugs:[...e]})}docsVersions(){return this.request("GET","/v1/docs/versions")}docsRollback(e){return this.request("POST","/v1/docs/rollback",{versionNo:e})}docsDelete(e){return this.request("DELETE",`/v1/docs/${encodeURIComponent(e)}`)}learningsPushKb(e,r={}){return this.request("POST","/v1/learnings/push-kb",{planToken:e,...r.app?{app:r.app}:{},...r.section?{section:r.section}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{}})}retryBinding(e){return this.request("POST",`/v1/bindings/${encodeURIComponent(e)}/retry`)}configExport(){return this.request("GET","/v1/config/export")}configPlan(e){return this.request("POST","/v1/config/plan",{bundle:e})}configApply(e,r={}){return this.request("POST","/v1/config/apply",{bundle:e,...r.prune?{prune:!0}:{}})}async tablesList(){return(await this.request("GET","/v1/tables")).tables??[]}tablesPlan(e){return this.request("POST","/v1/tables/plan",e)}appsPlan(e){return this.request("POST","/v1/apps/plan",{writes:e.writes??[],...e.roles!==void 0?{roles:e.roles}:{},labels:e.labels??[],...e.app?{app:e.app}:{}})}tablesApply(e){return this.request("POST","/v1/tables/apply",e)}tablesDrop(e,r){return this.request("DELETE",`/v1/tables/${encodeURIComponent(e)}?confirm=${encodeURIComponent(r)}`)}async guardrailsList(){return(await this.request("GET","/v1/guardrails")).guardrails??[]}async guardrailCreate(e){return(await this.request("POST","/v1/guardrails",e)).guardrail}async guardrailUpdate(e,r){return(await this.request("PATCH",`/v1/guardrails/${encodeURIComponent(e)}`,r)).guardrail}guardrailDelete(e){return this.request("DELETE",`/v1/guardrails/${encodeURIComponent(e)}`)}guardrailTest(e){return this.request("POST","/v1/guardrails/test",e)}guardrailPostureGet(){return this.request("GET","/v1/guardrails/posture")}guardrailPostureSet(e){return this.request("PUT","/v1/guardrails/posture",{mode:e})}releaseDeploy(e){return this.request("POST","/v1/releases/deploy",{...e.solutionId?{solutionId:e.solutionId}:{},target:e.target,...e.approvedBy?{approvedBy:e.approvedBy}:{},...e.files?{files:e.files}:{},...e.gitRepo?{gitRepo:e.gitRepo}:{},...e.gitRef?{gitRef:e.gitRef}:{},...e.gitSha?{gitSha:e.gitSha}:{},...e.prUrl?{prUrl:e.prUrl}:{}})}async releaseList(){return(await this.request("GET","/v1/releases")).releases??[]}releaseGet(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}`)}releaseFiles(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/files`)}releasePush(e,r){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/push`,{files:r.files,target:r.target,...r.approvedBy?{approvedBy:r.approvedBy}:{}})}releaseStatus(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/status`)}releaseRollback(e){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/rollback`)}},Cr="TURBOBASE_REGISTRY_URL",Uo="TURBOBASE_REGISTRY_TOKEN";wn=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=Ru(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=ku(a);throw new Q(`${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}:{}})}}});import{existsSync as Tw,statSync as xw}from"node:fs";import{resolve as Mo,sep as $u}from"node:path";function Eu(t){if($w.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits|processes)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function Pw(t,e,r){let n=Mo(e,r),o=Mo(t);if(n!==o&&!n.startsWith(o+$u))return null;let s=[n];/\.(js|mjs|cjs)$/.test(n)&&s.push(n.replace(/\.js$/,".ts"),n.replace(/\.mjs$/,".mts"),n.replace(/\.cjs$/,".cts")),/\.[cm]?[jt]sx?$/.test(n)||s.push(`${n}.ts`,`${n}.tsx`,`${n}.js`,`${n}/index.ts`,`${n}/index.js`);for(let i of s)if(i.startsWith(o+$u)&&Tw(i)&&xw(i).isFile())return i;return null}function Pu(t){return{name:"extension-self-contained-fence",setup(e){e.onResolve({filter:/.*/},r=>{if(r.kind==="entry-point")return null;if(Eu(r.path))return{path:r.path,namespace:"extension-sdk"};let n=r.path.startsWith(".")||r.path.startsWith("/");if(n&&t){let s=Pw(t,r.resolveDir,r.path);if(s)return{path:s}}return{errors:[{text:`extension ${n?`imports a sibling/local file ('${r.path}')${t?" that does not resolve inside the extension\u2019s own directory":""}`:r.path.startsWith("node:")||Cw(r.path)?`imports a Node builtin ('${r.path}')`:`imports an external module ('${r.path}')`} \u2014 sandboxed extensions must be self-contained. The ONLY allowed imports are the SDK factory ('@/sync/hooks' or '@turbobase/extensions') and a relative sibling inside the extension's own directory; inline everything else into the extension file.`}]}}),e.onLoad({filter:/.*/,namespace:"extension-sdk"},()=>({contents:Ew,loader:"js"}))}}}function Cw(t){let e=t.startsWith("node:")?t.slice(5):t;return Aw.has(e.split("/")[0])}function Au(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 Cu(){try{return(await import("esbuild")).build}catch(t){throw Au("esbuild",t)}}async function Iw(){try{return(await import("isolated-vm")).default}catch(t){throw Au("isolated-vm",t)}}async function Bo(t,e={}){let r=await Cu(),n=e.resolveDir?Mo(e.resolveDir):void 0,o;try{o=await r({stdin:{contents:t,loader:"ts",resolveDir:n??process.cwd(),sourcefile:"extension.ts"},bundle:!0,write:!1,format:"iife",globalName:"__tb_extension_module",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[Pu(n)]})}catch(s){let a=s.errors?.map(l=>l.text).filter(Boolean).join("; ");throw new qo(a||`extension bundle failed: ${String(s)}`)}return o.outputFiles?.[0]?.text??""}async function aa(t,e){if(!/(^|\n)\s*(import|export)\s[^;]*?from\s*['"](\.|\/)/.test(t)&&!/\bimport\s*\(\s*['"](\.|\/)/.test(t))return t;let r=await Cu(),n=Mo(e),o=Pu(n),s={name:"extension-sdk-external",setup(a){a.onResolve({filter:/.*/},l=>l.kind==="entry-point"?null:Eu(l.path)?{path:l.path,external:!0}:null)}},i;try{i=await r({stdin:{contents:t,loader:"ts",resolveDir:n,sourcefile:"extension.ts"},bundle:!0,write:!1,format:"esm",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[s,o]})}catch(a){let d=a.errors?.map(p=>p.text).filter(Boolean).join("; ");throw new qo(d||`extension bundle failed: ${String(a)}`)}return i.outputFiles?.[0]?.text??t}async function vn(t,e,r={}){let n=r.timeoutMs??zo,o=r.memoryLimitMb??Rw,s=r.member??"run",i={patches:[],logs:[]},a=await Iw(),l=new a.Isolate({memoryLimit:o});try{let d=await l.createContext(),p=d.global,f=new a.Callback(Y=>{let F=JSON.parse(String(Y));i.rejection||(i.rejection=F)}),_=new a.Callback(Y=>{i.patches.push(JSON.parse(String(Y)))}),y=new a.Callback(Y=>{let F=JSON.parse(String(Y));i.logs.push(F)}),k=new a.Callback(Y=>{i.result=JSON.parse(String(Y))}),R=r.query,$=new a.Reference(async Y=>{if(!R)throw new Error("ctx.query is not available in this context");return JSON.stringify(await R(String(Y)))});await p.set("__tb_reject",f),await p.set("__tb_patch",_),await p.set("__tb_log",y),await p.set("__tb_result",k),await p.set("__tb_query",$),await p.set("__tb_ctx_json",JSON.stringify(Ow(e)));let P=Lw(t,s,r.stepIndex??0,!!r.query),D=await(await l.compileScript(P)).run(d,{timeout:n,promise:!0});return s==="when"?{effects:i,whenResult:!!D}:{effects:i}}finally{l.isDisposed||l.dispose()}}function Ow(t){return{recordType:t.recordType,event:t.event,direction:t.direction,origin:t.origin,source:t.source,payload:t.payload??null,prior:t.prior??null,user:t.user??null,tenantConfig:t.tenantConfig??{},metadata:t.metadata??null,bindings:t.bindings??null,atlasLinks:t.atlasLinks??null,materialized:t.materialized??null,process:t.process??null}}function Nw(t){return`
27
27
  "use strict";
28
28
  (async () => {
29
29
  const __tb_ctx = JSON.parse(__tb_ctx_json);
@@ -304,7 +304,7 @@ export default defineProcess({
304
304
  ],
305
305
  onFailure: ${JSON.stringify(n)},
306
306
  });
307
- `;return{relativePath:`processes/${o}.ts`,content:l}}function Rt(t,e){let r=Av[t];if(!r)throw new Je(`unknown extension kind '${t}'. Scaffoldable kinds: ${ip.join(", ")}.`);return r(e)}var ip,Je,Av,Jo=j(()=>{ip=["hook","conduit","process"];Je=class extends Error{};Av={hook:$v,conduit:Ev,process:Pv}});var Ca,Ia=j(()=>{Ca=Object.freeze({instance:!0,platform:!0,share:"inherit"})});function JS(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 YS(t){return jm[JS(t)%jm.length]}function XS(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 Dm(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Um(t,e){let[r,n]=YS(t),o=Dm(XS(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${Dm(e)}">
307
+ `;return{relativePath:`processes/${o}.ts`,content:l}}function Rt(t,e){let r=Av[t];if(!r)throw new Je(`unknown extension kind '${t}'. Scaffoldable kinds: ${ip.join(", ")}.`);return r(e)}var ip,Je,Av,Jo=j(()=>{ip=["hook","conduit","process"];Je=class extends Error{};Av={hook:$v,conduit:Ev,process:Pv}});var Ca,Ia=j(()=>{Ca=Object.freeze({instance:!0,platform:!0,share:"inherit"})});function JS(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 YS(t){return jh[JS(t)%jh.length]}function XS(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 Dh(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Uh(t,e){let[r,n]=YS(t),o=Dh(XS(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${Dh(e)}">
308
308
  <defs>
309
309
  <linearGradient id="tile" x1="0" y1="0" x2="1" y2="1">
310
310
  <stop offset="0" stop-color="${r}"/>
@@ -314,9 +314,9 @@ export default defineProcess({
314
314
  <rect width="64" height="64" rx="14" fill="url(#tile)"/>
315
315
  <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>
316
316
  </svg>
317
- `}var jm,Mm=j(()=>{jm=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var th={};Yd(th,{CN_UTIL:()=>Km,COMPONENTS_JSON:()=>Hm,MAIN_TSX:()=>Gm,STYLES_CSS:()=>Wm,TSCONFIG:()=>Fm,TURBOBASE_CLIENT:()=>qm,UI_BADGE:()=>Xm,UI_BUTTON:()=>Jm,UI_CARD:()=>Ym,UI_INPUT:()=>Qm,UI_LABEL:()=>eh,UI_TABLE:()=>Zm,indexHtml:()=>Vm,instanceOriginFromEnv:()=>ik,packageJson:()=>zm,scaffoldAppFiles:()=>lk,starterApp:()=>ck,viteConfig:()=>Bm});function ek(t,e){let r=t.trim();if(r.length<=e)return r;let n=r.slice(0,e);return n.replace(/[\s\p{P}\p{S}]+$/u,"")||n}function tk(t){let e={name:ek(t.title,QS)},r=(t.description??"").trim().slice(0,ZS);return r&&(e.description=r),e.icon="favicon.svg",e.learnings={...Ca},JSON.stringify(e,null,2)+`
318
- `}function zm(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview",pretest:rk},dependencies:{react:"^19.2.0","react-dom":"^19.2.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1","tailwind-merge":"^3.0.0","lucide-react":"^0.469.0","@fontsource/inter":"^5.1.0"},devDependencies:{"@types/react":"^19.2.0","@types/react-dom":"^19.2.0","@vitejs/plugin-react":"^4.3.1",tailwindcss:"^4.0.0","@tailwindcss/vite":"^4.0.0","tw-animate-css":"^1.2.5",typescript:"^5.5.3",vite:"^5.4.0"}},null,2)}
319
- `}function sk(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 ik(t=process.env){let e=(t.TENANT_SLUG??"").trim(),r=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!r))return`https://${e}.${r}`}function Bm(t,e={}){let r=sk(e.instanceOrigin);return`import { defineConfig } from 'vite';
317
+ `}var jh,Mh=j(()=>{jh=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var tm={};Yd(tm,{CN_UTIL:()=>Kh,COMPONENTS_JSON:()=>Hh,MAIN_TSX:()=>Gh,STYLES_CSS:()=>Wh,TSCONFIG:()=>Fh,TURBOBASE_CLIENT:()=>qh,UI_BADGE:()=>Xh,UI_BUTTON:()=>Jh,UI_CARD:()=>Yh,UI_INPUT:()=>Qh,UI_LABEL:()=>em,UI_TABLE:()=>Zh,indexHtml:()=>Vh,instanceOriginFromEnv:()=>ik,packageJson:()=>zh,scaffoldAppFiles:()=>lk,starterApp:()=>ck,viteConfig:()=>Bh});function ek(t,e){let r=t.trim();if(r.length<=e)return r;let n=r.slice(0,e);return n.replace(/[\s\p{P}\p{S}]+$/u,"")||n}function tk(t){let e={name:ek(t.title,QS)},r=(t.description??"").trim().slice(0,ZS);return r&&(e.description=r),e.icon="favicon.svg",e.learnings={...Ca},JSON.stringify(e,null,2)+`
318
+ `}function zh(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview",pretest:rk},dependencies:{react:"^19.2.0","react-dom":"^19.2.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1","tailwind-merge":"^3.0.0","lucide-react":"^0.469.0","@fontsource/inter":"^5.1.0"},devDependencies:{"@types/react":"^19.2.0","@types/react-dom":"^19.2.0","@vitejs/plugin-react":"^4.3.1",tailwindcss:"^4.0.0","@tailwindcss/vite":"^4.0.0","tw-animate-css":"^1.2.5",typescript:"^5.5.3",vite:"^5.4.0"}},null,2)}
319
+ `}function sk(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 ik(t=process.env){let e=(t.TENANT_SLUG??"").trim(),r=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!r))return`https://${e}.${r}`}function Bh(t,e={}){let r=sk(e.instanceOrigin);return`import { defineConfig } from 'vite';
320
320
  import { fileURLToPath, URL } from 'node:url';
321
321
  import react from '@vitejs/plugin-react';
322
322
  // Tailwind v4 is a Vite PLUGIN, not a PostCSS pass \u2014 there is no
@@ -374,7 +374,7 @@ export default defineConfig({
374
374
  },
375
375
  build: { outDir: 'dist' },
376
376
  });
377
- `}function Vm(t){return`<!doctype html>
377
+ `}function Vh(t){return`<!doctype html>
378
378
  <html lang="en">
379
379
  <head>
380
380
  <meta charset="UTF-8" />
@@ -387,7 +387,7 @@ export default defineConfig({
387
387
  <script type="module" src="/src/main.tsx"></script>
388
388
  </body>
389
389
  </html>
390
- `}function lk(t){return{"package.json":zm(t.slug),"vite.config.ts":Bm(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":ak,"tsconfig.json":Fm,"index.html":Vm(t.title),"public/turbobase.json":tk(t),"public/favicon.svg":Um(t.slug,t.title),"src/main.tsx":Gm,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":qm,"src/styles.css":Wm,"components.json":Hm,"src/lib/utils.ts":Km,"src/components/ui/button.tsx":Jm,"src/components/ui/card.tsx":Ym,"src/components/ui/badge.tsx":Xm,"src/components/ui/table.tsx":Zm,"src/components/ui/input.tsx":Qm,"src/components/ui/label.tsx":eh,"README.md":`# ${t.title}
390
+ `}function lk(t){return{"package.json":zh(t.slug),"vite.config.ts":Bh(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":ak,"tsconfig.json":Fh,"index.html":Vh(t.title),"public/turbobase.json":tk(t),"public/favicon.svg":Uh(t.slug,t.title),"src/main.tsx":Gh,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":qh,"src/styles.css":Wh,"components.json":Hh,"src/lib/utils.ts":Kh,"src/components/ui/button.tsx":Jh,"src/components/ui/card.tsx":Yh,"src/components/ui/badge.tsx":Xh,"src/components/ui/table.tsx":Zh,"src/components/ui/input.tsx":Qh,"src/components/ui/label.tsx":em,"README.md":`# ${t.title}
391
391
 
392
392
  \`\`\`sh
393
393
  npm install
@@ -633,7 +633,7 @@ export default function App() {
633
633
  </main>
634
634
  );
635
635
  }
636
- `}var ZS,QS,qm,On,rk,nk,ok,ak,Fm,Hm,Km,Gm,Wm,Jm,Ym,Xm,Zm,Qm,eh,rh=j(()=>{Mm();Ia();ZS=200,QS=60;qm=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
636
+ `}var ZS,QS,qh,On,rk,nk,ok,ak,Fh,Hh,Kh,Gh,Wh,Jh,Yh,Xh,Zh,Qh,em,rm=j(()=>{Mh();Ia();ZS=200,QS=60;qh=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
637
637
  // Reads go through PostgREST (RLS-scoped); writes go through POST /v1/data/<recordType>.
638
638
  // A cold first paint that fans out many reads should use batch() \u2014 ONE request
639
639
  // that multiplexes them, sidestepping the per-request rate limiter.
@@ -1675,9 +1675,9 @@ build/
1675
1675
  !.env.example
1676
1676
 
1677
1677
  .DS_Store
1678
- `,Fm=`${JSON.stringify({compilerOptions:{target:"ES2022",lib:["ES2022","DOM","DOM.Iterable"],module:"ESNext",moduleResolution:"bundler",jsx:"react-jsx",strict:!0,skipLibCheck:!0,noEmit:!0,baseUrl:".",paths:{"@/*":["./src/*"]}},include:["src"]},null,2)}
1679
- `,Hm=`${JSON.stringify({$schema:"https://ui.shadcn.com/schema.json",style:"new-york",rsc:!1,tsx:!0,tailwind:{config:"",css:"src/styles.css",baseColor:"neutral",cssVariables:!0,prefix:""},aliases:{components:"@/components",utils:"@/lib/utils",ui:"@/components/ui",lib:"@/lib",hooks:"@/hooks"},iconLibrary:"lucide"},null,2)}
1680
- `,Km=`import { clsx, type ClassValue } from 'clsx';
1678
+ `,Fh=`${JSON.stringify({compilerOptions:{target:"ES2022",lib:["ES2022","DOM","DOM.Iterable"],module:"ESNext",moduleResolution:"bundler",jsx:"react-jsx",strict:!0,skipLibCheck:!0,noEmit:!0,baseUrl:".",paths:{"@/*":["./src/*"]}},include:["src"]},null,2)}
1679
+ `,Hh=`${JSON.stringify({$schema:"https://ui.shadcn.com/schema.json",style:"new-york",rsc:!1,tsx:!0,tailwind:{config:"",css:"src/styles.css",baseColor:"neutral",cssVariables:!0,prefix:""},aliases:{components:"@/components",utils:"@/lib/utils",ui:"@/components/ui",lib:"@/lib",hooks:"@/hooks"},iconLibrary:"lucide"},null,2)}
1680
+ `,Kh=`import { clsx, type ClassValue } from 'clsx';
1681
1681
  import { twMerge } from 'tailwind-merge';
1682
1682
 
1683
1683
  /**
@@ -1691,7 +1691,7 @@ import { twMerge } from 'tailwind-merge';
1691
1691
  export function cn(...inputs: ClassValue[]) {
1692
1692
  return twMerge(clsx(inputs));
1693
1693
  }
1694
- `;Gm=`import React from 'react';
1694
+ `;Gh=`import React from 'react';
1695
1695
  import { createRoot } from 'react-dom/client';
1696
1696
  import App from './App';
1697
1697
  import './styles.css';
@@ -1701,7 +1701,7 @@ createRoot(document.getElementById('root')!).render(
1701
1701
  <App />
1702
1702
  </React.StrictMode>,
1703
1703
  );
1704
- `,Wm=`@import 'tailwindcss';
1704
+ `,Wh=`@import 'tailwindcss';
1705
1705
  @import 'tw-animate-css';
1706
1706
 
1707
1707
  /* Inter, self-hosted \u2014 the design system's font.
@@ -1789,7 +1789,7 @@ createRoot(document.getElementById('root')!).render(
1789
1789
  transition-duration: 0.01ms !important;
1790
1790
  }
1791
1791
  }
1792
- `,Jm=`import * as React from 'react';
1792
+ `,Jh=`import * as React from 'react';
1793
1793
  import { cva, type VariantProps } from 'class-variance-authority';
1794
1794
 
1795
1795
  import { cn } from '@/lib/utils';
@@ -1829,7 +1829,7 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
1829
1829
  Button.displayName = 'Button';
1830
1830
 
1831
1831
  export { Button, buttonVariants };
1832
- `,Ym=`import * as React from 'react';
1832
+ `,Yh=`import * as React from 'react';
1833
1833
 
1834
1834
  import { cn } from '@/lib/utils';
1835
1835
 
@@ -1867,7 +1867,7 @@ const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDi
1867
1867
  CardContent.displayName = 'CardContent';
1868
1868
 
1869
1869
  export { Card, CardHeader, CardTitle, CardDescription, CardContent };
1870
- `,Xm=`import * as React from 'react';
1870
+ `,Xh=`import * as React from 'react';
1871
1871
  import { cva, type VariantProps } from 'class-variance-authority';
1872
1872
 
1873
1873
  import { cn } from '@/lib/utils';
@@ -1902,7 +1902,7 @@ function Badge({ className, variant, ...props }: BadgeProps) {
1902
1902
  }
1903
1903
 
1904
1904
  export { Badge, badgeVariants };
1905
- `,Zm=`import * as React from 'react';
1905
+ `,Zh=`import * as React from 'react';
1906
1906
 
1907
1907
  import { cn } from '@/lib/utils';
1908
1908
 
@@ -1961,7 +1961,7 @@ const TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<
1961
1961
  TableCell.displayName = 'TableCell';
1962
1962
 
1963
1963
  export { Table, TableHeader, TableBody, TableRow, TableHead, TableCell };
1964
- `,Qm=`import * as React from 'react';
1964
+ `,Qh=`import * as React from 'react';
1965
1965
 
1966
1966
  import { cn } from '@/lib/utils';
1967
1967
 
@@ -1981,7 +1981,7 @@ const Input = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLI
1981
1981
  Input.displayName = 'Input';
1982
1982
 
1983
1983
  export { Input };
1984
- `,eh=`import * as React from 'react';
1984
+ `,em=`import * as React from 'react';
1985
1985
 
1986
1986
  import { cn } from '@/lib/utils';
1987
1987
 
@@ -1998,51 +1998,51 @@ const Label = React.forwardRef<HTMLLabelElement, React.LabelHTMLAttributes<HTMLL
1998
1998
  Label.displayName = 'Label';
1999
1999
 
2000
2000
  export { Label };
2001
- `});import*as nh from"zod/v3";import*as gr from"zod/v4-mini";function $t(t){return!!t._zod}function yr(t){let e=Object.values(t);if(e.length===0)return gr.object({});let r=e.every($t),n=e.every(o=>!$t(o));if(r)return gr.object(t);if(n)return nh.object(t);throw new Error("Mixed Zod versions detected in object shape.")}function Yt(t,e){return $t(t)?gr.safeParse(t,e):t.safeParse(e)}async function cs(t,e){return $t(t)?await gr.safeParseAsync(t,e):await t.safeParseAsync(e)}function Xt(t){if(!t)return;let e;if($t(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Br(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 yr(t)}}if($t(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 dk(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function ds(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 ${dk(e.path)}`:e.message).join(`
2002
- `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function oh(t){return t.description}function sh(t){if($t(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Fr(t){if($t(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 Nn=j(()=>{});import*as c from"zod/v4";function Sh(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function kh(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Ka,ih,Zt,ps,Ae,ah,lh,SN,uk,pk,Va,tt,Ln,ch,je,it,at,De,ms,dh,Ga,uh,ph,Wa,jn,K,Ja,mh,hh,kN,hs,mk,fs,hk,Dn,Hr,fh,fk,gk,yk,bk,wk,vk,Ya,_k,Sk,Xa,gs,kk,Tk,ys,xk,Un,Mn,Rk,qn,Kr,$k,zn,bs,ws,vs,TN,_s,Ss,ks,gh,yh,bh,Za,wh,Bn,Vr,vh,Ek,Ts,Pk,xs,Ak,Qa,Ck,Rs,Ik,Ok,Nk,Lk,jk,Dk,Uk,Mk,qk,zk,$s,Bk,Fk,Es,el,tl,rl,Hk,Kk,Vk,nl,Gk,Wk,Jk,Yk,Xk,_h,Ps,Zk,As,xN,Qk,Gr,eT,RN,Fn,tT,ol,rT,nT,oT,sT,iT,aT,lT,us,cT,dT,uT,Hn,sl,pT,mT,hT,fT,gT,yT,bT,wT,vT,_T,ST,kT,TT,xT,RT,$T,ET,PT,Wr,AT,CT,IT,Cs,OT,NT,LT,il,jT,$N,EN,PN,AN,CN,IN,z,Ha,Jr=j(()=>{Ka="2025-11-25",ih=[Ka,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Zt="io.modelcontextprotocol/related-task",ps="2.0",Ae=c.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),ah=c.union([c.string(),c.number().int()]),lh=c.string(),SN=c.looseObject({ttl:c.number().optional(),pollInterval:c.number().optional()}),uk=c.object({ttl:c.number().optional()}),pk=c.object({taskId:c.string()}),Va=c.looseObject({progressToken:ah.optional(),[Zt]:pk.optional()}),tt=c.object({_meta:Va.optional()}),Ln=tt.extend({task:uk.optional()}),ch=t=>Ln.safeParse(t).success,je=c.object({method:c.string(),params:tt.loose().optional()}),it=c.object({_meta:Va.optional()}),at=c.object({method:c.string(),params:it.loose().optional()}),De=c.looseObject({_meta:Va.optional()}),ms=c.union([c.string(),c.number().int()]),dh=c.object({jsonrpc:c.literal(ps),id:ms,...je.shape}).strict(),Ga=t=>dh.safeParse(t).success,uh=c.object({jsonrpc:c.literal(ps),...at.shape}).strict(),ph=t=>uh.safeParse(t).success,Wa=c.object({jsonrpc:c.literal(ps),id:ms,result:De}).strict(),jn=t=>Wa.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"})(K||(K={}));Ja=c.object({jsonrpc:c.literal(ps),id:ms.optional(),error:c.object({code:c.number().int(),message:c.string(),data:c.unknown().optional()})}).strict(),mh=t=>Ja.safeParse(t).success,hh=c.union([dh,uh,Wa,Ja]),kN=c.union([Wa,Ja]),hs=De.strict(),mk=it.extend({requestId:ms.optional(),reason:c.string().optional()}),fs=at.extend({method:c.literal("notifications/cancelled"),params:mk}),hk=c.object({src:c.string(),mimeType:c.string().optional(),sizes:c.array(c.string()).optional(),theme:c.enum(["light","dark"]).optional()}),Dn=c.object({icons:c.array(hk).optional()}),Hr=c.object({name:c.string(),title:c.string().optional()}),fh=Hr.extend({...Hr.shape,...Dn.shape,version:c.string(),websiteUrl:c.string().optional(),description:c.string().optional()}),fk=c.intersection(c.object({applyDefaults:c.boolean().optional()}),c.record(c.string(),c.unknown())),gk=c.preprocess(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,c.intersection(c.object({form:fk.optional(),url:Ae.optional()}),c.record(c.string(),c.unknown()).optional())),yk=c.looseObject({list:Ae.optional(),cancel:Ae.optional(),requests:c.looseObject({sampling:c.looseObject({createMessage:Ae.optional()}).optional(),elicitation:c.looseObject({create:Ae.optional()}).optional()}).optional()}),bk=c.looseObject({list:Ae.optional(),cancel:Ae.optional(),requests:c.looseObject({tools:c.looseObject({call:Ae.optional()}).optional()}).optional()}),wk=c.object({experimental:c.record(c.string(),Ae).optional(),sampling:c.object({context:Ae.optional(),tools:Ae.optional()}).optional(),elicitation:gk.optional(),roots:c.object({listChanged:c.boolean().optional()}).optional(),tasks:yk.optional(),extensions:c.record(c.string(),Ae).optional()}),vk=tt.extend({protocolVersion:c.string(),capabilities:wk,clientInfo:fh}),Ya=je.extend({method:c.literal("initialize"),params:vk}),_k=c.object({experimental:c.record(c.string(),Ae).optional(),logging:Ae.optional(),completions:Ae.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:bk.optional(),extensions:c.record(c.string(),Ae).optional()}),Sk=De.extend({protocolVersion:c.string(),capabilities:_k,serverInfo:fh,instructions:c.string().optional()}),Xa=at.extend({method:c.literal("notifications/initialized"),params:it.optional()}),gs=je.extend({method:c.literal("ping"),params:tt.optional()}),kk=c.object({progress:c.number(),total:c.optional(c.number()),message:c.optional(c.string())}),Tk=c.object({...it.shape,...kk.shape,progressToken:ah}),ys=at.extend({method:c.literal("notifications/progress"),params:Tk}),xk=tt.extend({cursor:lh.optional()}),Un=je.extend({params:xk.optional()}),Mn=De.extend({nextCursor:lh.optional()}),Rk=c.enum(["working","input_required","completed","failed","cancelled"]),qn=c.object({taskId:c.string(),status:Rk,ttl:c.union([c.number(),c.null()]),createdAt:c.string(),lastUpdatedAt:c.string(),pollInterval:c.optional(c.number()),statusMessage:c.optional(c.string())}),Kr=De.extend({task:qn}),$k=it.merge(qn),zn=at.extend({method:c.literal("notifications/tasks/status"),params:$k}),bs=je.extend({method:c.literal("tasks/get"),params:tt.extend({taskId:c.string()})}),ws=De.merge(qn),vs=je.extend({method:c.literal("tasks/result"),params:tt.extend({taskId:c.string()})}),TN=De.loose(),_s=Un.extend({method:c.literal("tasks/list")}),Ss=Mn.extend({tasks:c.array(qn)}),ks=je.extend({method:c.literal("tasks/cancel"),params:tt.extend({taskId:c.string()})}),gh=De.merge(qn),yh=c.object({uri:c.string(),mimeType:c.optional(c.string()),_meta:c.record(c.string(),c.unknown()).optional()}),bh=yh.extend({text:c.string()}),Za=c.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),wh=yh.extend({blob:Za}),Bn=c.enum(["user","assistant"]),Vr=c.object({audience:c.array(Bn).optional(),priority:c.number().min(0).max(1).optional(),lastModified:c.iso.datetime({offset:!0}).optional()}),vh=c.object({...Hr.shape,...Dn.shape,uri:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),size:c.optional(c.number()),annotations:Vr.optional(),_meta:c.optional(c.looseObject({}))}),Ek=c.object({...Hr.shape,...Dn.shape,uriTemplate:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),annotations:Vr.optional(),_meta:c.optional(c.looseObject({}))}),Ts=Un.extend({method:c.literal("resources/list")}),Pk=Mn.extend({resources:c.array(vh)}),xs=Un.extend({method:c.literal("resources/templates/list")}),Ak=Mn.extend({resourceTemplates:c.array(Ek)}),Qa=tt.extend({uri:c.string()}),Ck=Qa,Rs=je.extend({method:c.literal("resources/read"),params:Ck}),Ik=De.extend({contents:c.array(c.union([bh,wh]))}),Ok=at.extend({method:c.literal("notifications/resources/list_changed"),params:it.optional()}),Nk=Qa,Lk=je.extend({method:c.literal("resources/subscribe"),params:Nk}),jk=Qa,Dk=je.extend({method:c.literal("resources/unsubscribe"),params:jk}),Uk=it.extend({uri:c.string()}),Mk=at.extend({method:c.literal("notifications/resources/updated"),params:Uk}),qk=c.object({name:c.string(),description:c.optional(c.string()),required:c.optional(c.boolean())}),zk=c.object({...Hr.shape,...Dn.shape,description:c.optional(c.string()),arguments:c.optional(c.array(qk)),_meta:c.optional(c.looseObject({}))}),$s=Un.extend({method:c.literal("prompts/list")}),Bk=Mn.extend({prompts:c.array(zk)}),Fk=tt.extend({name:c.string(),arguments:c.record(c.string(),c.string()).optional()}),Es=je.extend({method:c.literal("prompts/get"),params:Fk}),el=c.object({type:c.literal("text"),text:c.string(),annotations:Vr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),tl=c.object({type:c.literal("image"),data:Za,mimeType:c.string(),annotations:Vr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),rl=c.object({type:c.literal("audio"),data:Za,mimeType:c.string(),annotations:Vr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Hk=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()}),Kk=c.object({type:c.literal("resource"),resource:c.union([bh,wh]),annotations:Vr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Vk=vh.extend({type:c.literal("resource_link")}),nl=c.union([el,tl,rl,Vk,Kk]),Gk=c.object({role:Bn,content:nl}),Wk=De.extend({description:c.string().optional(),messages:c.array(Gk)}),Jk=at.extend({method:c.literal("notifications/prompts/list_changed"),params:it.optional()}),Yk=c.object({title:c.string().optional(),readOnlyHint:c.boolean().optional(),destructiveHint:c.boolean().optional(),idempotentHint:c.boolean().optional(),openWorldHint:c.boolean().optional()}),Xk=c.object({taskSupport:c.enum(["required","optional","forbidden"]).optional()}),_h=c.object({...Hr.shape,...Dn.shape,description:c.string().optional(),inputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),Ae).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()),outputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),Ae).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()).optional(),annotations:Yk.optional(),execution:Xk.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Ps=Un.extend({method:c.literal("tools/list")}),Zk=Mn.extend({tools:c.array(_h)}),As=De.extend({content:c.array(nl).default([]),structuredContent:c.record(c.string(),c.unknown()).optional(),isError:c.boolean().optional()}),xN=As.or(De.extend({toolResult:c.unknown()})),Qk=Ln.extend({name:c.string(),arguments:c.record(c.string(),c.unknown()).optional()}),Gr=je.extend({method:c.literal("tools/call"),params:Qk}),eT=at.extend({method:c.literal("notifications/tools/list_changed"),params:it.optional()}),RN=c.object({autoRefresh:c.boolean().default(!0),debounceMs:c.number().int().nonnegative().default(300)}),Fn=c.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),tT=tt.extend({level:Fn}),ol=je.extend({method:c.literal("logging/setLevel"),params:tT}),rT=it.extend({level:Fn,logger:c.string().optional(),data:c.unknown()}),nT=at.extend({method:c.literal("notifications/message"),params:rT}),oT=c.object({name:c.string().optional()}),sT=c.object({hints:c.array(oT).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()}),iT=c.object({mode:c.enum(["auto","required","none"]).optional()}),aT=c.object({type:c.literal("tool_result"),toolUseId:c.string().describe("The unique identifier for the corresponding tool call."),content:c.array(nl).default([]),structuredContent:c.object({}).loose().optional(),isError:c.boolean().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),lT=c.discriminatedUnion("type",[el,tl,rl]),us=c.discriminatedUnion("type",[el,tl,rl,Hk,aT]),cT=c.object({role:Bn,content:c.union([us,c.array(us)]),_meta:c.record(c.string(),c.unknown()).optional()}),dT=Ln.extend({messages:c.array(cT),modelPreferences:sT.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:Ae.optional(),tools:c.array(_h).optional(),toolChoice:iT.optional()}),uT=je.extend({method:c.literal("sampling/createMessage"),params:dT}),Hn=De.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens"]).or(c.string())),role:Bn,content:lT}),sl=De.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(c.string())),role:Bn,content:c.union([us,c.array(us)])}),pT=c.object({type:c.literal("boolean"),title:c.string().optional(),description:c.string().optional(),default:c.boolean().optional()}),mT=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()}),hT=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()}),fT=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),enum:c.array(c.string()),default:c.string().optional()}),gT=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()}),yT=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()}),bT=c.union([fT,gT]),wT=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()}),vT=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()}),_T=c.union([wT,vT]),ST=c.union([yT,bT,_T]),kT=c.union([ST,pT,mT,hT]),TT=Ln.extend({mode:c.literal("form").optional(),message:c.string(),requestedSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),kT),required:c.array(c.string()).optional()})}),xT=Ln.extend({mode:c.literal("url"),message:c.string(),elicitationId:c.string(),url:c.string().url()}),RT=c.union([TT,xT]),$T=je.extend({method:c.literal("elicitation/create"),params:RT}),ET=it.extend({elicitationId:c.string()}),PT=at.extend({method:c.literal("notifications/elicitation/complete"),params:ET}),Wr=De.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())}),AT=c.object({type:c.literal("ref/resource"),uri:c.string()}),CT=c.object({type:c.literal("ref/prompt"),name:c.string()}),IT=tt.extend({ref:c.union([CT,AT]),argument:c.object({name:c.string(),value:c.string()}),context:c.object({arguments:c.record(c.string(),c.string()).optional()}).optional()}),Cs=je.extend({method:c.literal("completion/complete"),params:IT});OT=De.extend({completion:c.looseObject({values:c.array(c.string()).max(100),total:c.optional(c.number().int()),hasMore:c.optional(c.boolean())})}),NT=c.object({uri:c.string().startsWith("file://"),name:c.string().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),LT=je.extend({method:c.literal("roots/list"),params:tt.optional()}),il=De.extend({roots:c.array(NT)}),jT=at.extend({method:c.literal("notifications/roots/list_changed"),params:it.optional()}),$N=c.union([gs,Ya,Cs,ol,Es,$s,Ts,xs,Rs,Lk,Dk,Gr,Ps,bs,vs,_s,ks]),EN=c.union([fs,ys,Xa,jT,zn]),PN=c.union([hs,Hn,sl,Wr,il,ws,Ss,Kr]),AN=c.union([gs,uT,$T,LT,bs,vs,_s,ks]),CN=c.union([fs,ys,nT,Mk,Ok,eT,Jk,zn,PT]),IN=c.union([hs,Sk,OT,Wk,Bk,Pk,Ak,Ik,As,Zk,ws,Ss,Kr]),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===K.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Ha(o.elicitations,r)}return new t(e,r,n)}},Ha=class extends z{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(K.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Qt(t){return t==="completed"||t==="failed"||t==="cancelled"}var Th=j(()=>{});var Rh,xh,$h,Is=j(()=>{Rh=Symbol("Let zodToJsonSchema decide on which parser to use"),xh={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},$h=t=>typeof t=="string"?{...xh,name:t}:{...xh,...t}});var Eh,al=j(()=>{Is();Eh=t=>{let e=$h(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function ll(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ce(t,e,r,n,o){t[e]=r,ll(t,e,n,o)}var er=j(()=>{});var Os,Ns=j(()=>{Os=(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 ke(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Os(e,t.currentPath):e.join("/")}}var lt=j(()=>{Ns()});import{ZodFirstPartyTypeKind as DT}from"zod/v3";function Ph(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==DT.ZodAny&&(r.items=X(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ce(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ce(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ce(r,"minItems",t.exactLength.value,t.exactLength.message,e),ce(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var cl=j(()=>{er();Pe()});function Ah(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?ce(r,"minimum",n.value,n.message,e):ce(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ce(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ce(r,"maximum",n.value,n.message,e):ce(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ce(r,"maximum",n.value,n.message,e));break;case"multipleOf":ce(r,"multipleOf",n.value,n.message,e);break}return r}var dl=j(()=>{er()});function Ch(){return{type:"boolean"}}var ul=j(()=>{});function Ls(t,e){return X(t.type._def,e)}var js=j(()=>{Pe()});var Ih,pl=j(()=>{Pe();Ih=(t,e)=>X(t.innerType._def,e)});function ml(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>ml(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 UT(t,e)}}var UT,hl=j(()=>{er();UT=(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":ce(r,"minimum",n.value,n.message,e);break;case"max":ce(r,"maximum",n.value,n.message,e);break}return r}});function Oh(t,e){return{...X(t.innerType._def,e),default:t.defaultValue()}}var fl=j(()=>{Pe()});function Nh(t,e){return e.effectStrategy==="input"?X(t.schema._def,e):ke(e)}var gl=j(()=>{Pe();lt()});function Lh(t){return{type:"string",enum:Array.from(t.values)}}var yl=j(()=>{});function jh(t,e){let r=[X(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),X(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(MT(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 MT,bl=j(()=>{Pe();MT=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function Dh(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 wl=j(()=>{});function Ds(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ce(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ce(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":bt(r,"email",n.message,e);break;case"format:idn-email":bt(r,"idn-email",n.message,e);break;case"pattern:zod":He(r,yt.email,n.message,e);break}break;case"url":bt(r,"uri",n.message,e);break;case"uuid":bt(r,"uuid",n.message,e);break;case"regex":He(r,n.regex,n.message,e);break;case"cuid":He(r,yt.cuid,n.message,e);break;case"cuid2":He(r,yt.cuid2,n.message,e);break;case"startsWith":He(r,RegExp(`^${_l(n.value,e)}`),n.message,e);break;case"endsWith":He(r,RegExp(`${_l(n.value,e)}$`),n.message,e);break;case"datetime":bt(r,"date-time",n.message,e);break;case"date":bt(r,"date",n.message,e);break;case"time":bt(r,"time",n.message,e);break;case"duration":bt(r,"duration",n.message,e);break;case"length":ce(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ce(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{He(r,RegExp(_l(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&bt(r,"ipv4",n.message,e),n.version!=="v4"&&bt(r,"ipv6",n.message,e);break}case"base64url":He(r,yt.base64url,n.message,e);break;case"jwt":He(r,yt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&He(r,yt.ipv4Cidr,n.message,e),n.version!=="v4"&&He(r,yt.ipv6Cidr,n.message,e);break}case"emoji":He(r,yt.emoji(),n.message,e);break;case"ulid":{He(r,yt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{bt(r,"binary",n.message,e);break}case"contentEncoding:base64":{ce(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{He(r,yt.base64,n.message,e);break}}break}case"nanoid":He(r,yt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function _l(t,e){return e.patternStrategy==="escape"?zT(t):t}function zT(t){let e="";for(let r=0;r<t.length;r++)qT.has(t[r])||(e+="\\"),e+=t[r];return e}function bt(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}}})):ce(t,"format",e,r,n)}function He(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:Uh(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ce(t,"pattern",Uh(e,n),r,n)}function Uh(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
2001
+ `});import*as nm from"zod/v3";import*as gr from"zod/v4-mini";function $t(t){return!!t._zod}function yr(t){let e=Object.values(t);if(e.length===0)return gr.object({});let r=e.every($t),n=e.every(o=>!$t(o));if(r)return gr.object(t);if(n)return nm.object(t);throw new Error("Mixed Zod versions detected in object shape.")}function Yt(t,e){return $t(t)?gr.safeParse(t,e):t.safeParse(e)}async function cs(t,e){return $t(t)?await gr.safeParseAsync(t,e):await t.safeParseAsync(e)}function Xt(t){if(!t)return;let e;if($t(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Br(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 yr(t)}}if($t(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 dk(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function ds(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 ${dk(e.path)}`:e.message).join(`
2002
+ `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function om(t){return t.description}function sm(t){if($t(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Fr(t){if($t(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 Nn=j(()=>{});import*as c from"zod/v4";function Sm(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function km(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Ka,im,Zt,ps,Ae,am,lm,SN,uk,pk,Va,tt,Ln,cm,je,it,at,De,hs,dm,Ga,um,pm,Wa,jn,K,Ja,hm,mm,kN,ms,hk,fs,mk,Dn,Hr,fm,fk,gk,yk,bk,wk,vk,Ya,_k,Sk,Xa,gs,kk,Tk,ys,xk,Un,Mn,Rk,qn,Kr,$k,zn,bs,ws,vs,TN,_s,Ss,ks,gm,ym,bm,Za,wm,Bn,Vr,vm,Ek,Ts,Pk,xs,Ak,Qa,Ck,Rs,Ik,Ok,Nk,Lk,jk,Dk,Uk,Mk,qk,zk,$s,Bk,Fk,Es,el,tl,rl,Hk,Kk,Vk,nl,Gk,Wk,Jk,Yk,Xk,_m,Ps,Zk,As,xN,Qk,Gr,eT,RN,Fn,tT,ol,rT,nT,oT,sT,iT,aT,lT,us,cT,dT,uT,Hn,sl,pT,hT,mT,fT,gT,yT,bT,wT,vT,_T,ST,kT,TT,xT,RT,$T,ET,PT,Wr,AT,CT,IT,Cs,OT,NT,LT,il,jT,$N,EN,PN,AN,CN,IN,z,Ha,Jr=j(()=>{Ka="2025-11-25",im=[Ka,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Zt="io.modelcontextprotocol/related-task",ps="2.0",Ae=c.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),am=c.union([c.string(),c.number().int()]),lm=c.string(),SN=c.looseObject({ttl:c.number().optional(),pollInterval:c.number().optional()}),uk=c.object({ttl:c.number().optional()}),pk=c.object({taskId:c.string()}),Va=c.looseObject({progressToken:am.optional(),[Zt]:pk.optional()}),tt=c.object({_meta:Va.optional()}),Ln=tt.extend({task:uk.optional()}),cm=t=>Ln.safeParse(t).success,je=c.object({method:c.string(),params:tt.loose().optional()}),it=c.object({_meta:Va.optional()}),at=c.object({method:c.string(),params:it.loose().optional()}),De=c.looseObject({_meta:Va.optional()}),hs=c.union([c.string(),c.number().int()]),dm=c.object({jsonrpc:c.literal(ps),id:hs,...je.shape}).strict(),Ga=t=>dm.safeParse(t).success,um=c.object({jsonrpc:c.literal(ps),...at.shape}).strict(),pm=t=>um.safeParse(t).success,Wa=c.object({jsonrpc:c.literal(ps),id:hs,result:De}).strict(),jn=t=>Wa.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"})(K||(K={}));Ja=c.object({jsonrpc:c.literal(ps),id:hs.optional(),error:c.object({code:c.number().int(),message:c.string(),data:c.unknown().optional()})}).strict(),hm=t=>Ja.safeParse(t).success,mm=c.union([dm,um,Wa,Ja]),kN=c.union([Wa,Ja]),ms=De.strict(),hk=it.extend({requestId:hs.optional(),reason:c.string().optional()}),fs=at.extend({method:c.literal("notifications/cancelled"),params:hk}),mk=c.object({src:c.string(),mimeType:c.string().optional(),sizes:c.array(c.string()).optional(),theme:c.enum(["light","dark"]).optional()}),Dn=c.object({icons:c.array(mk).optional()}),Hr=c.object({name:c.string(),title:c.string().optional()}),fm=Hr.extend({...Hr.shape,...Dn.shape,version:c.string(),websiteUrl:c.string().optional(),description:c.string().optional()}),fk=c.intersection(c.object({applyDefaults:c.boolean().optional()}),c.record(c.string(),c.unknown())),gk=c.preprocess(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,c.intersection(c.object({form:fk.optional(),url:Ae.optional()}),c.record(c.string(),c.unknown()).optional())),yk=c.looseObject({list:Ae.optional(),cancel:Ae.optional(),requests:c.looseObject({sampling:c.looseObject({createMessage:Ae.optional()}).optional(),elicitation:c.looseObject({create:Ae.optional()}).optional()}).optional()}),bk=c.looseObject({list:Ae.optional(),cancel:Ae.optional(),requests:c.looseObject({tools:c.looseObject({call:Ae.optional()}).optional()}).optional()}),wk=c.object({experimental:c.record(c.string(),Ae).optional(),sampling:c.object({context:Ae.optional(),tools:Ae.optional()}).optional(),elicitation:gk.optional(),roots:c.object({listChanged:c.boolean().optional()}).optional(),tasks:yk.optional(),extensions:c.record(c.string(),Ae).optional()}),vk=tt.extend({protocolVersion:c.string(),capabilities:wk,clientInfo:fm}),Ya=je.extend({method:c.literal("initialize"),params:vk}),_k=c.object({experimental:c.record(c.string(),Ae).optional(),logging:Ae.optional(),completions:Ae.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:bk.optional(),extensions:c.record(c.string(),Ae).optional()}),Sk=De.extend({protocolVersion:c.string(),capabilities:_k,serverInfo:fm,instructions:c.string().optional()}),Xa=at.extend({method:c.literal("notifications/initialized"),params:it.optional()}),gs=je.extend({method:c.literal("ping"),params:tt.optional()}),kk=c.object({progress:c.number(),total:c.optional(c.number()),message:c.optional(c.string())}),Tk=c.object({...it.shape,...kk.shape,progressToken:am}),ys=at.extend({method:c.literal("notifications/progress"),params:Tk}),xk=tt.extend({cursor:lm.optional()}),Un=je.extend({params:xk.optional()}),Mn=De.extend({nextCursor:lm.optional()}),Rk=c.enum(["working","input_required","completed","failed","cancelled"]),qn=c.object({taskId:c.string(),status:Rk,ttl:c.union([c.number(),c.null()]),createdAt:c.string(),lastUpdatedAt:c.string(),pollInterval:c.optional(c.number()),statusMessage:c.optional(c.string())}),Kr=De.extend({task:qn}),$k=it.merge(qn),zn=at.extend({method:c.literal("notifications/tasks/status"),params:$k}),bs=je.extend({method:c.literal("tasks/get"),params:tt.extend({taskId:c.string()})}),ws=De.merge(qn),vs=je.extend({method:c.literal("tasks/result"),params:tt.extend({taskId:c.string()})}),TN=De.loose(),_s=Un.extend({method:c.literal("tasks/list")}),Ss=Mn.extend({tasks:c.array(qn)}),ks=je.extend({method:c.literal("tasks/cancel"),params:tt.extend({taskId:c.string()})}),gm=De.merge(qn),ym=c.object({uri:c.string(),mimeType:c.optional(c.string()),_meta:c.record(c.string(),c.unknown()).optional()}),bm=ym.extend({text:c.string()}),Za=c.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),wm=ym.extend({blob:Za}),Bn=c.enum(["user","assistant"]),Vr=c.object({audience:c.array(Bn).optional(),priority:c.number().min(0).max(1).optional(),lastModified:c.iso.datetime({offset:!0}).optional()}),vm=c.object({...Hr.shape,...Dn.shape,uri:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),size:c.optional(c.number()),annotations:Vr.optional(),_meta:c.optional(c.looseObject({}))}),Ek=c.object({...Hr.shape,...Dn.shape,uriTemplate:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),annotations:Vr.optional(),_meta:c.optional(c.looseObject({}))}),Ts=Un.extend({method:c.literal("resources/list")}),Pk=Mn.extend({resources:c.array(vm)}),xs=Un.extend({method:c.literal("resources/templates/list")}),Ak=Mn.extend({resourceTemplates:c.array(Ek)}),Qa=tt.extend({uri:c.string()}),Ck=Qa,Rs=je.extend({method:c.literal("resources/read"),params:Ck}),Ik=De.extend({contents:c.array(c.union([bm,wm]))}),Ok=at.extend({method:c.literal("notifications/resources/list_changed"),params:it.optional()}),Nk=Qa,Lk=je.extend({method:c.literal("resources/subscribe"),params:Nk}),jk=Qa,Dk=je.extend({method:c.literal("resources/unsubscribe"),params:jk}),Uk=it.extend({uri:c.string()}),Mk=at.extend({method:c.literal("notifications/resources/updated"),params:Uk}),qk=c.object({name:c.string(),description:c.optional(c.string()),required:c.optional(c.boolean())}),zk=c.object({...Hr.shape,...Dn.shape,description:c.optional(c.string()),arguments:c.optional(c.array(qk)),_meta:c.optional(c.looseObject({}))}),$s=Un.extend({method:c.literal("prompts/list")}),Bk=Mn.extend({prompts:c.array(zk)}),Fk=tt.extend({name:c.string(),arguments:c.record(c.string(),c.string()).optional()}),Es=je.extend({method:c.literal("prompts/get"),params:Fk}),el=c.object({type:c.literal("text"),text:c.string(),annotations:Vr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),tl=c.object({type:c.literal("image"),data:Za,mimeType:c.string(),annotations:Vr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),rl=c.object({type:c.literal("audio"),data:Za,mimeType:c.string(),annotations:Vr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Hk=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()}),Kk=c.object({type:c.literal("resource"),resource:c.union([bm,wm]),annotations:Vr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Vk=vm.extend({type:c.literal("resource_link")}),nl=c.union([el,tl,rl,Vk,Kk]),Gk=c.object({role:Bn,content:nl}),Wk=De.extend({description:c.string().optional(),messages:c.array(Gk)}),Jk=at.extend({method:c.literal("notifications/prompts/list_changed"),params:it.optional()}),Yk=c.object({title:c.string().optional(),readOnlyHint:c.boolean().optional(),destructiveHint:c.boolean().optional(),idempotentHint:c.boolean().optional(),openWorldHint:c.boolean().optional()}),Xk=c.object({taskSupport:c.enum(["required","optional","forbidden"]).optional()}),_m=c.object({...Hr.shape,...Dn.shape,description:c.string().optional(),inputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),Ae).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()),outputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),Ae).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()).optional(),annotations:Yk.optional(),execution:Xk.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Ps=Un.extend({method:c.literal("tools/list")}),Zk=Mn.extend({tools:c.array(_m)}),As=De.extend({content:c.array(nl).default([]),structuredContent:c.record(c.string(),c.unknown()).optional(),isError:c.boolean().optional()}),xN=As.or(De.extend({toolResult:c.unknown()})),Qk=Ln.extend({name:c.string(),arguments:c.record(c.string(),c.unknown()).optional()}),Gr=je.extend({method:c.literal("tools/call"),params:Qk}),eT=at.extend({method:c.literal("notifications/tools/list_changed"),params:it.optional()}),RN=c.object({autoRefresh:c.boolean().default(!0),debounceMs:c.number().int().nonnegative().default(300)}),Fn=c.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),tT=tt.extend({level:Fn}),ol=je.extend({method:c.literal("logging/setLevel"),params:tT}),rT=it.extend({level:Fn,logger:c.string().optional(),data:c.unknown()}),nT=at.extend({method:c.literal("notifications/message"),params:rT}),oT=c.object({name:c.string().optional()}),sT=c.object({hints:c.array(oT).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()}),iT=c.object({mode:c.enum(["auto","required","none"]).optional()}),aT=c.object({type:c.literal("tool_result"),toolUseId:c.string().describe("The unique identifier for the corresponding tool call."),content:c.array(nl).default([]),structuredContent:c.object({}).loose().optional(),isError:c.boolean().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),lT=c.discriminatedUnion("type",[el,tl,rl]),us=c.discriminatedUnion("type",[el,tl,rl,Hk,aT]),cT=c.object({role:Bn,content:c.union([us,c.array(us)]),_meta:c.record(c.string(),c.unknown()).optional()}),dT=Ln.extend({messages:c.array(cT),modelPreferences:sT.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:Ae.optional(),tools:c.array(_m).optional(),toolChoice:iT.optional()}),uT=je.extend({method:c.literal("sampling/createMessage"),params:dT}),Hn=De.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens"]).or(c.string())),role:Bn,content:lT}),sl=De.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(c.string())),role:Bn,content:c.union([us,c.array(us)])}),pT=c.object({type:c.literal("boolean"),title:c.string().optional(),description:c.string().optional(),default:c.boolean().optional()}),hT=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()}),mT=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()}),fT=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),enum:c.array(c.string()),default:c.string().optional()}),gT=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()}),yT=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()}),bT=c.union([fT,gT]),wT=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()}),vT=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()}),_T=c.union([wT,vT]),ST=c.union([yT,bT,_T]),kT=c.union([ST,pT,hT,mT]),TT=Ln.extend({mode:c.literal("form").optional(),message:c.string(),requestedSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),kT),required:c.array(c.string()).optional()})}),xT=Ln.extend({mode:c.literal("url"),message:c.string(),elicitationId:c.string(),url:c.string().url()}),RT=c.union([TT,xT]),$T=je.extend({method:c.literal("elicitation/create"),params:RT}),ET=it.extend({elicitationId:c.string()}),PT=at.extend({method:c.literal("notifications/elicitation/complete"),params:ET}),Wr=De.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())}),AT=c.object({type:c.literal("ref/resource"),uri:c.string()}),CT=c.object({type:c.literal("ref/prompt"),name:c.string()}),IT=tt.extend({ref:c.union([CT,AT]),argument:c.object({name:c.string(),value:c.string()}),context:c.object({arguments:c.record(c.string(),c.string()).optional()}).optional()}),Cs=je.extend({method:c.literal("completion/complete"),params:IT});OT=De.extend({completion:c.looseObject({values:c.array(c.string()).max(100),total:c.optional(c.number().int()),hasMore:c.optional(c.boolean())})}),NT=c.object({uri:c.string().startsWith("file://"),name:c.string().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),LT=je.extend({method:c.literal("roots/list"),params:tt.optional()}),il=De.extend({roots:c.array(NT)}),jT=at.extend({method:c.literal("notifications/roots/list_changed"),params:it.optional()}),$N=c.union([gs,Ya,Cs,ol,Es,$s,Ts,xs,Rs,Lk,Dk,Gr,Ps,bs,vs,_s,ks]),EN=c.union([fs,ys,Xa,jT,zn]),PN=c.union([ms,Hn,sl,Wr,il,ws,Ss,Kr]),AN=c.union([gs,uT,$T,LT,bs,vs,_s,ks]),CN=c.union([fs,ys,nT,Mk,Ok,eT,Jk,zn,PT]),IN=c.union([ms,Sk,OT,Wk,Bk,Pk,Ak,Ik,As,Zk,ws,Ss,Kr]),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===K.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Ha(o.elicitations,r)}return new t(e,r,n)}},Ha=class extends z{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(K.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Qt(t){return t==="completed"||t==="failed"||t==="cancelled"}var Tm=j(()=>{});var Rm,xm,$m,Is=j(()=>{Rm=Symbol("Let zodToJsonSchema decide on which parser to use"),xm={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"},$m=t=>typeof t=="string"?{...xm,name:t}:{...xm,...t}});var Em,al=j(()=>{Is();Em=t=>{let e=$m(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 ll(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ce(t,e,r,n,o){t[e]=r,ll(t,e,n,o)}var er=j(()=>{});var Os,Ns=j(()=>{Os=(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 ke(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Os(e,t.currentPath):e.join("/")}}var lt=j(()=>{Ns()});import{ZodFirstPartyTypeKind as DT}from"zod/v3";function Pm(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==DT.ZodAny&&(r.items=X(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ce(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ce(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ce(r,"minItems",t.exactLength.value,t.exactLength.message,e),ce(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var cl=j(()=>{er();Pe()});function Am(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?ce(r,"minimum",n.value,n.message,e):ce(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ce(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ce(r,"maximum",n.value,n.message,e):ce(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ce(r,"maximum",n.value,n.message,e));break;case"multipleOf":ce(r,"multipleOf",n.value,n.message,e);break}return r}var dl=j(()=>{er()});function Cm(){return{type:"boolean"}}var ul=j(()=>{});function Ls(t,e){return X(t.type._def,e)}var js=j(()=>{Pe()});var Im,pl=j(()=>{Pe();Im=(t,e)=>X(t.innerType._def,e)});function hl(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>hl(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 UT(t,e)}}var UT,ml=j(()=>{er();UT=(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":ce(r,"minimum",n.value,n.message,e);break;case"max":ce(r,"maximum",n.value,n.message,e);break}return r}});function Om(t,e){return{...X(t.innerType._def,e),default:t.defaultValue()}}var fl=j(()=>{Pe()});function Nm(t,e){return e.effectStrategy==="input"?X(t.schema._def,e):ke(e)}var gl=j(()=>{Pe();lt()});function Lm(t){return{type:"string",enum:Array.from(t.values)}}var yl=j(()=>{});function jm(t,e){let r=[X(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),X(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(MT(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 MT,bl=j(()=>{Pe();MT=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function Dm(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 wl=j(()=>{});function Ds(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ce(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ce(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":bt(r,"email",n.message,e);break;case"format:idn-email":bt(r,"idn-email",n.message,e);break;case"pattern:zod":He(r,yt.email,n.message,e);break}break;case"url":bt(r,"uri",n.message,e);break;case"uuid":bt(r,"uuid",n.message,e);break;case"regex":He(r,n.regex,n.message,e);break;case"cuid":He(r,yt.cuid,n.message,e);break;case"cuid2":He(r,yt.cuid2,n.message,e);break;case"startsWith":He(r,RegExp(`^${_l(n.value,e)}`),n.message,e);break;case"endsWith":He(r,RegExp(`${_l(n.value,e)}$`),n.message,e);break;case"datetime":bt(r,"date-time",n.message,e);break;case"date":bt(r,"date",n.message,e);break;case"time":bt(r,"time",n.message,e);break;case"duration":bt(r,"duration",n.message,e);break;case"length":ce(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ce(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{He(r,RegExp(_l(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&bt(r,"ipv4",n.message,e),n.version!=="v4"&&bt(r,"ipv6",n.message,e);break}case"base64url":He(r,yt.base64url,n.message,e);break;case"jwt":He(r,yt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&He(r,yt.ipv4Cidr,n.message,e),n.version!=="v4"&&He(r,yt.ipv6Cidr,n.message,e);break}case"emoji":He(r,yt.emoji(),n.message,e);break;case"ulid":{He(r,yt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{bt(r,"binary",n.message,e);break}case"contentEncoding:base64":{ce(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{He(r,yt.base64,n.message,e);break}}break}case"nanoid":He(r,yt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function _l(t,e){return e.patternStrategy==="escape"?zT(t):t}function zT(t){let e="";for(let r=0;r<t.length;r++)qT.has(t[r])||(e+="\\"),e+=t[r];return e}function bt(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}}})):ce(t,"format",e,r,n)}function He(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:Um(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ce(t,"pattern",Um(e,n),r,n)}function Um(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
2003
2003
  ]))`;continue}else if(n[l]==="$"){o+=`($|(?=[\r
2004
2004
  ]))`;continue}}if(r.s&&n[l]==="."){o+=i?`${n[l]}\r
2005
2005
  `:`[${n[l]}\r
2006
- ]`;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 vl,yt,qT,Us=j(()=>{er();yt={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:()=>(vl===void 0&&(vl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),vl),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-_]*$/};qT=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});import{ZodFirstPartyTypeKind as Kn}from"zod/v3";function Ms(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===Kn.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:X(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??ke(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:X(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===Kn.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Ds(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===Kn.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===Kn.ZodBranded&&t.keyType._def.type._def.typeName===Kn.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Ls(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var qs=j(()=>{Pe();Us();js();lt()});function Mh(t,e){if(e.mapStrategy==="record")return Ms(t,e);let r=X(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||ke(e),n=X(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||ke(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var Sl=j(()=>{Pe();qs();lt()});function qh(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 kl=j(()=>{});function zh(t){return t.target==="openAi"?void 0:{not:ke({...t,currentPath:[...t.currentPath,"not"]})}}var Tl=j(()=>{lt()});function Bh(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var xl=j(()=>{});function Hh(t,e){if(e.target==="openApi3")return Fh(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Vn&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Vn[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 Fh(t,e)}var Vn,Fh,zs=j(()=>{Pe();Vn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Fh=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>X(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 Kh(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:Vn[t.innerType._def.typeName],nullable:!0}:{type:[Vn[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=X(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=X(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var Rl=j(()=>{Pe();zs()});function Vh(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",ll(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ce(r,"minimum",n.value,n.message,e):ce(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ce(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ce(r,"maximum",n.value,n.message,e):ce(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ce(r,"maximum",n.value,n.message,e));break;case"multipleOf":ce(r,"multipleOf",n.value,n.message,e);break}return r}var $l=j(()=>{er()});function Gh(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 d=FT(l);d&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),d=!1);let p=X(l._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});p!==void 0&&(n.properties[a]=p,d||o.push(a))}o.length&&(n.required=o);let i=BT(t,e);return i!==void 0&&(n.additionalProperties=i),n}function BT(t,e){if(t.catchall._def.typeName!=="ZodNever")return X(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 FT(t){try{return t.isOptional()}catch{return!0}}var El=j(()=>{Pe()});var Wh,Pl=j(()=>{Pe();lt();Wh=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return X(t.innerType._def,e);let r=X(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:ke(e)},r]}:ke(e)}});var Jh,Al=j(()=>{Pe();Jh=(t,e)=>{if(e.pipeStrategy==="input")return X(t.in._def,e);if(e.pipeStrategy==="output")return X(t.out._def,e);let r=X(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=X(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function Yh(t,e){return X(t.type._def,e)}var Cl=j(()=>{Pe()});function Xh(t,e){let n={type:"array",uniqueItems:!0,items:X(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ce(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ce(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var Il=j(()=>{er();Pe()});function Zh(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>X(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:X(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>X(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var Ol=j(()=>{Pe()});function Qh(t){return{not:ke(t)}}var Nl=j(()=>{lt()});function ef(t){return ke(t)}var Ll=j(()=>{lt()});var tf,jl=j(()=>{Pe();tf=(t,e)=>X(t.innerType._def,e)});import{ZodFirstPartyTypeKind as le}from"zod/v3";var rf,Dl=j(()=>{lt();cl();dl();ul();js();pl();hl();fl();gl();yl();bl();wl();Sl();kl();Tl();xl();Rl();$l();El();Pl();Al();Cl();qs();Il();Us();Ol();Nl();zs();Ll();jl();rf=(t,e,r)=>{switch(e){case le.ZodString:return Ds(t,r);case le.ZodNumber:return Vh(t,r);case le.ZodObject:return Gh(t,r);case le.ZodBigInt:return Ah(t,r);case le.ZodBoolean:return Ch();case le.ZodDate:return ml(t,r);case le.ZodUndefined:return Qh(r);case le.ZodNull:return Bh(r);case le.ZodArray:return Ph(t,r);case le.ZodUnion:case le.ZodDiscriminatedUnion:return Hh(t,r);case le.ZodIntersection:return jh(t,r);case le.ZodTuple:return Zh(t,r);case le.ZodRecord:return Ms(t,r);case le.ZodLiteral:return Dh(t,r);case le.ZodEnum:return Lh(t);case le.ZodNativeEnum:return qh(t);case le.ZodNullable:return Kh(t,r);case le.ZodOptional:return Wh(t,r);case le.ZodMap:return Mh(t,r);case le.ZodSet:return Xh(t,r);case le.ZodLazy:return()=>t.getter()._def;case le.ZodPromise:return Yh(t,r);case le.ZodNaN:case le.ZodNever:return zh(r);case le.ZodEffects:return Nh(t,r);case le.ZodAny:return ke(r);case le.ZodUnknown:return ef(r);case le.ZodDefault:return Oh(t,r);case le.ZodBranded:return Ls(t,r);case le.ZodReadonly:return tf(t,r);case le.ZodCatch:return Ih(t,r);case le.ZodPipeline:return Jh(t,r);case le.ZodFunction:case le.ZodVoid:case le.ZodSymbol:return;default:return(n=>{})(e)}}});function X(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==Rh)return a}if(n&&!r){let a=HT(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=rf(t,t.typeName,e),i=typeof s=="function"?X(s(),e):s;if(i&&KT(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var HT,KT,Pe=j(()=>{Is();Dl();Ns();lt();HT=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Os(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`),ke(e)):e.$refStrategy==="seen"?ke(e):void 0}},KT=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var nf=j(()=>{});var Ul,Ml=j(()=>{Pe();al();lt();Ul=(t,e)=>{let r=Eh(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[d,p])=>({...l,[d]:X(p._def,{...r,currentPath:[...r.basePath,r.definitionPath,d]},!0)??ke(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=X(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??ke(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 of=j(()=>{Is();al();er();Ns();Pe();nf();lt();cl();dl();ul();js();pl();hl();fl();gl();yl();bl();wl();Sl();kl();Tl();xl();Rl();$l();El();Pl();Al();Cl();jl();qs();Il();Us();Ol();Nl();zs();Ll();Dl();Ml();Ml()});import*as sf from"zod/v4-mini";function VT(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function ql(t,e){return $t(t)?sf.toJSONSchema(t,{target:VT(e?.target),io:e?.pipeStrategy??"input"}):Ul(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function zl(t){let r=Xt(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Fr(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Bl(t,e){let r=Yt(t,e);if(!r.success)throw r.error;return r.data}var Fl=j(()=>{Nn();of()});function af(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function lf(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];af(i)&&af(s)?r[o]={...i,...s}:r[o]=s}return r}var GT,Bs,cf=j(()=>{Nn();Jr();Th();Fl();GT=6e4,Bs=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(fs,r=>{this._oncancel(r)}),this.setNotificationHandler(ys,r=>{this._onprogress(r)}),this.setRequestHandler(gs,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(bs,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new z(K.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(vs,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,d=l.id,p=this._requestResolvers.get(d);if(p)if(this._requestResolvers.delete(d),a.type==="response")p(l);else{let f=l,_=new z(f.error.code,f.error.message,f.error.data);p(_)}else{let f=a.type==="response"?"Response":"Error";this._onerror(new Error(`${f} handler missing for request ${d}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new z(K.InvalidParams,`Task not found: ${s}`);if(!Qt(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Qt(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Zt]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(_s,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(K.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(ks,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new z(K.InvalidParams,`Task not found: ${r.params.taskId}`);if(Qt(o.status))throw new z(K.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(K.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof z?o:new z(K.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(K.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),jn(s)||mh(s)?this._onresponse(s):Ga(s)?this._onrequest(s,i):ph(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(K.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?.[Zt]?.taskId;if(n===void 0){let p={jsonrpc:"2.0",id:e.id,error:{code:K.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:p,timestamp:Date.now()},o?.sessionId).catch(f=>this._onerror(new Error(`Failed to enqueue error response: ${f}`))):o?.send(p).catch(f=>this._onerror(new Error(`Failed to send an error response: ${f}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=ch(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,d={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async p=>{if(i.signal.aborted)return;let f={relatedRequestId:e.id};s&&(f.relatedTask={taskId:s}),await this.notification(p,f)},sendRequest:async(p,f,_)=>{if(i.signal.aborted)throw new z(K.ConnectionClosed,"Request was cancelled");let y={..._,relatedRequestId:e.id};s&&!y.relatedTask&&(y.relatedTask={taskId:s});let k=y.relatedTask?.taskId??s;return k&&l&&await l.updateTaskStatus(k,"input_required"),await this.request(p,f,y)},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,d)).then(async p=>{if(i.signal.aborted)return;let f={result:p,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:f,timestamp:Date.now()},o?.sessionId):await o?.send(f)},async p=>{if(i.signal.aborted)return;let f={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(p.code)?p.code:K.InternalError,message:p.message??"Internal error",...p.data!==void 0&&{data:p.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:f,timestamp:Date.now()},o?.sessionId):await o?.send(f)}).catch(p=>this._onerror(new Error(`Failed to send response: ${p}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,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),jn(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(jn(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),jn(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(K.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Kr,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new z(K.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Qt(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(K.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new z(K.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(d=>setTimeout(d,l)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof z?i:new z(K.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:l}=n??{};return new Promise((d,p)=>{let f=I=>{p(I)};if(!this._transport){f(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(I){f(I);return}n?.signal?.throwIfAborted();let _=this._requestMessageId++,y={...e,jsonrpc:"2.0",id:_};n?.onprogress&&(this._progressHandlers.set(_,n.onprogress),y.params={...e.params,_meta:{...e.params?._meta||{},progressToken:_}}),a&&(y.params={...y.params,task:a}),l&&(y.params={...y.params,_meta:{...y.params?._meta||{},[Zt]:l}});let k=I=>{this._responseHandlers.delete(_),this._progressHandlers.delete(_),this._cleanupTimeout(_),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:_,reason:String(I)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(Y=>this._onerror(new Error(`Failed to send cancellation: ${Y}`)));let D=I instanceof z?I:new z(K.RequestTimeout,String(I));p(D)};this._responseHandlers.set(_,I=>{if(!n?.signal?.aborted){if(I instanceof Error)return p(I);try{let D=Yt(r,I.result);D.success?d(D.data):p(D.error)}catch(D){p(D)}}}),n?.signal?.addEventListener("abort",()=>{k(n?.signal?.reason)});let R=n?.timeout??GT,$=()=>k(z.fromError(K.RequestTimeout,"Request timed out",{timeout:R}));this._setupTimeout(_,R,n?.maxTotalTimeout,$,n?.resetTimeoutOnProgress??!1);let P=l?.taskId;if(P){let I=D=>{let Y=this._responseHandlers.get(_);Y?Y(D):this._onerror(new Error(`Response handler missing for side-channeled request ${_}`))};this._requestResolvers.set(_,I),this._enqueueTaskMessage(P,{type:"request",message:y,timestamp:Date.now()}).catch(D=>{this._cleanupTimeout(_),p(D)})}else this._transport.send(y,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(I=>{this._cleanupTimeout(_),p(I)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},ws,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},Ss,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},gh,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||{},[Zt]: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||{},[Zt]: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||{},[Zt]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=zl(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Bl(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=zl(e);this._notificationHandlers.set(n,o=>{let s=Bl(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"&&Ga(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new z(K.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(K.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new z(K.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(K.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=zn.parse({method:"notifications/tasks/status",params:a});await this.notification(l),Qt(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(K.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Qt(a.status))throw new z(K.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 d=zn.parse({method:"notifications/tasks/status",params:l});await this.notification(d),Qt(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var Jn=U(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.regexpCode=me.getEsmExportName=me.getProperty=me.safeStringify=me.stringify=me.strConcat=me.addCodeArg=me.str=me._=me.nil=me._Code=me.Name=me.IDENTIFIER=me._CodeOrName=void 0;var Gn=class{};me._CodeOrName=Gn;me.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var br=class extends Gn{constructor(e){if(super(),!me.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}}};me.Name=br;var ct=class extends Gn{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 br&&(r[n.str]=(r[n.str]||0)+1),r),{})}};me._Code=ct;me.nil=new ct("");function df(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Kl(r,e[n]),r.push(t[++n]);return new ct(r)}me._=df;var Hl=new ct("+");function uf(t,...e){let r=[Wn(t[0])],n=0;for(;n<e.length;)r.push(Hl),Kl(r,e[n]),r.push(Hl,Wn(t[++n]));return WT(r),new ct(r)}me.str=uf;function Kl(t,e){e instanceof ct?t.push(...e._items):e instanceof br?t.push(e):t.push(XT(e))}me.addCodeArg=Kl;function WT(t){let e=1;for(;e<t.length-1;){if(t[e]===Hl){let r=JT(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function JT(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof br||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 br))return`"${t}${e.slice(1)}`}function YT(t,e){return e.emptyStr()?t:t.emptyStr()?e:uf`${t}${e}`}me.strConcat=YT;function XT(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Wn(Array.isArray(t)?t.join(","):t)}function ZT(t){return new ct(Wn(t))}me.stringify=ZT;function Wn(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}me.safeStringify=Wn;function QT(t){return typeof t=="string"&&me.IDENTIFIER.test(t)?new ct(`.${t}`):df`[${t}]`}me.getProperty=QT;function ex(t){if(typeof t=="string"&&me.IDENTIFIER.test(t))return new ct(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}me.getEsmExportName=ex;function tx(t){return new ct(t.toString())}me.regexpCode=tx});var Wl=U(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.ValueScope=Xe.ValueScopeName=Xe.Scope=Xe.varKinds=Xe.UsedValueState=void 0;var Ye=Jn(),Vl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Fs;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Fs||(Xe.UsedValueState=Fs={}));Xe.varKinds={const:new Ye.Name("const"),let:new Ye.Name("let"),var:new Ye.Name("var")};var Hs=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ye.Name?e:this.name(e)}name(e){return new Ye.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}}};Xe.Scope=Hs;var Ks=class extends Ye.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Ye._)`.${new Ye.Name(r)}[${n}]`}};Xe.ValueScopeName=Ks;var rx=(0,Ye._)`\n`,Gl=class extends Hs{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?rx:Ye.nil}}get(){return this._scope}name(e){return new Ks(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 p=a.get(i);if(p)return p}else a=this._values[s]=new Map;a.set(i,o);let l=this._scope[s]||(this._scope[s]=[]),d=l.length;return l[d]=r.ref,o.setValue(r,{property:s,itemIndex:d}),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,Ye._)`${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=Ye.nil;for(let i in e){let a=e[i];if(!a)continue;let l=n[i]=n[i]||new Map;a.forEach(d=>{if(l.has(d))return;l.set(d,Fs.Started);let p=r(d);if(p){let f=this.opts.es5?Xe.varKinds.var:Xe.varKinds.const;s=(0,Ye._)`${s}${f} ${d} = ${p};${this.opts._n}`}else if(p=o?.(d))s=(0,Ye._)`${s}${p}${this.opts._n}`;else throw new Vl(d);l.set(d,Fs.Completed)})}return s}};Xe.ValueScope=Gl});var re=U(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.or=ne.and=ne.not=ne.CodeGen=ne.operators=ne.varKinds=ne.ValueScopeName=ne.ValueScope=ne.Scope=ne.Name=ne.regexpCode=ne.stringify=ne.getProperty=ne.nil=ne.strConcat=ne.str=ne._=void 0;var de=Jn(),wt=Wl(),tr=Jn();Object.defineProperty(ne,"_",{enumerable:!0,get:function(){return tr._}});Object.defineProperty(ne,"str",{enumerable:!0,get:function(){return tr.str}});Object.defineProperty(ne,"strConcat",{enumerable:!0,get:function(){return tr.strConcat}});Object.defineProperty(ne,"nil",{enumerable:!0,get:function(){return tr.nil}});Object.defineProperty(ne,"getProperty",{enumerable:!0,get:function(){return tr.getProperty}});Object.defineProperty(ne,"stringify",{enumerable:!0,get:function(){return tr.stringify}});Object.defineProperty(ne,"regexpCode",{enumerable:!0,get:function(){return tr.regexpCode}});Object.defineProperty(ne,"Name",{enumerable:!0,get:function(){return tr.Name}});var Js=Wl();Object.defineProperty(ne,"Scope",{enumerable:!0,get:function(){return Js.Scope}});Object.defineProperty(ne,"ValueScope",{enumerable:!0,get:function(){return Js.ValueScope}});Object.defineProperty(ne,"ValueScopeName",{enumerable:!0,get:function(){return Js.ValueScopeName}});Object.defineProperty(ne,"varKinds",{enumerable:!0,get:function(){return Js.varKinds}});ne.operators={GT:new de._Code(">"),GTE:new de._Code(">="),LT:new de._Code("<"),LTE:new de._Code("<="),EQ:new de._Code("==="),NEQ:new de._Code("!=="),NOT:new de._Code("!"),OR:new de._Code("||"),AND:new de._Code("&&"),ADD:new de._Code("+")};var Dt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Jl=class extends Dt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?wt.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=Xr(this.rhs,e,r)),this}get names(){return this.rhs instanceof de._CodeOrName?this.rhs.names:{}}},Vs=class extends Dt{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 de.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Xr(this.rhs,e,r),this}get names(){let e=this.lhs instanceof de.Name?{}:{...this.lhs.names};return Ws(e,this.rhs)}},Yl=class extends Vs{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Xl=class extends Dt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Zl=class extends Dt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Ql=class extends Dt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},ec=class extends Dt{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=Xr(this.code,e,r),this}get names(){return this.code instanceof de._CodeOrName?this.code.names:{}}},Yn=class extends Dt{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)||(nx(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>_r(e,r.names),{})}},Ut=class extends Yn{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},tc=class extends Yn{},Yr=class extends Ut{};Yr.kind="else";var wr=class t extends Ut{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 Yr(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(pf(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=Xr(this.condition,e,r),this}get names(){let e=super.names;return Ws(e,this.condition),this.else&&_r(e,this.else.names),e}};wr.kind="if";var vr=class extends Ut{};vr.kind="for";var rc=class extends vr{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=Xr(this.iteration,e,r),this}get names(){return _r(super.names,this.iteration.names)}},nc=class extends vr{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?wt.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=Ws(super.names,this.from);return Ws(e,this.to)}},Gs=class extends vr{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=Xr(this.iterable,e,r),this}get names(){return _r(super.names,this.iterable.names)}},Xn=class extends Ut{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)}};Xn.kind="func";var Zn=class extends Yn{render(e){return"return "+super.render(e)}};Zn.kind="return";var oc=class extends Ut{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&&_r(e,this.catch.names),this.finally&&_r(e,this.finally.names),e}},Qn=class extends Ut{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Qn.kind="catch";var eo=class extends Ut{render(e){return"finally"+super.render(e)}};eo.kind="finally";var sc=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
2007
- `:""},this._extScope=e,this._scope=new wt.Scope({parent:e}),this._nodes=[new tc]}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 Jl(e,s,n)),s}const(e,r,n){return this._def(wt.varKinds.const,e,r,n)}let(e,r,n){return this._def(wt.varKinds.let,e,r,n)}var(e,r,n){return this._def(wt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Vs(e,r,n))}add(e,r){return this._leafNode(new Yl(e,ne.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==de.nil&&this._leafNode(new ec(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,de.addCodeArg)(r,o));return r.push("}"),new de._Code(r)}if(e,r,n){if(this._blockNode(new wr(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 wr(e))}else(){return this._elseNode(new Yr)}endIf(){return this._endBlockNode(wr,Yr)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new rc(e),r)}forRange(e,r,n,o,s=this.opts.es5?wt.varKinds.var:wt.varKinds.let){let i=this._scope.toName(e);return this._for(new nc(s,i,r,n),()=>o(i))}forOf(e,r,n,o=wt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof de.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,de._)`${i}.length`,a=>{this.var(s,(0,de._)`${i}[${a}]`),n(s)})}return this._for(new Gs("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?wt.varKinds.var:wt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,de._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Gs("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(vr)}label(e){return this._leafNode(new Xl(e))}break(e){return this._leafNode(new Zl(e))}return(e){let r=new Zn;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Zn)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new oc;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Qn(s),r(s)}return n&&(this._currNode=o.finally=new eo,this.code(n)),this._endBlockNode(Qn,eo)}throw(e){return this._leafNode(new Ql(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=de.nil,n,o){return this._blockNode(new Xn(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Xn)}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 wr))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}};ne.CodeGen=sc;function _r(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Ws(t,e){return e instanceof de._CodeOrName?_r(t,e.names):t}function Xr(t,e,r){if(t instanceof de.Name)return n(t);if(!o(t))return t;return new de._Code(t._items.reduce((s,i)=>(i instanceof de.Name&&(i=n(i)),i instanceof de._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 de._Code&&s._items.some(i=>i instanceof de.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function nx(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function pf(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,de._)`!${ic(t)}`}ne.not=pf;var ox=mf(ne.operators.AND);function sx(...t){return t.reduce(ox)}ne.and=sx;var ix=mf(ne.operators.OR);function ax(...t){return t.reduce(ix)}ne.or=ax;function mf(t){return(e,r)=>e===de.nil?r:r===de.nil?e:(0,de._)`${ic(e)} ${t} ${ic(r)}`}function ic(t){return t instanceof de.Name?t:(0,de._)`(${t})`}});var ue=U(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.checkStrictMode=oe.getErrorPath=oe.Type=oe.useFunc=oe.setEvaluated=oe.evaluatedPropsToName=oe.mergeEvaluated=oe.eachItem=oe.unescapeJsonPointer=oe.escapeJsonPointer=oe.escapeFragment=oe.unescapeFragment=oe.schemaRefOrVal=oe.schemaHasRulesButRef=oe.schemaHasRules=oe.checkUnknownRules=oe.alwaysValidSchema=oe.toHash=void 0;var we=re(),lx=Jn();function cx(t){let e={};for(let r of t)e[r]=!0;return e}oe.toHash=cx;function dx(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(gf(t,e),!yf(e,t.self.RULES.all))}oe.alwaysValidSchema=dx;function gf(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]||vf(t,`unknown keyword: "${s}"`)}oe.checkUnknownRules=gf;function yf(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}oe.schemaHasRules=yf;function ux(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}oe.schemaHasRulesButRef=ux;function px({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,we._)`${r}`}return(0,we._)`${t}${e}${(0,we.getProperty)(n)}`}oe.schemaRefOrVal=px;function mx(t){return bf(decodeURIComponent(t))}oe.unescapeFragment=mx;function hx(t){return encodeURIComponent(lc(t))}oe.escapeFragment=hx;function lc(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}oe.escapeJsonPointer=lc;function bf(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}oe.unescapeJsonPointer=bf;function fx(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}oe.eachItem=fx;function hf({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let l=i===void 0?s:i instanceof we.Name?(s instanceof we.Name?t(o,s,i):e(o,s,i),i):s instanceof we.Name?(e(o,i,s),s):r(s,i);return a===we.Name&&!(l instanceof we.Name)?n(o,l):l}}oe.mergeEvaluated={props:hf({mergeNames:(t,e,r)=>t.if((0,we._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,we._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,we._)`${r} || {}`).code((0,we._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,we._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,we._)`${r} || {}`),cc(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:wf}),items:hf({mergeNames:(t,e,r)=>t.if((0,we._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,we._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,we._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,we._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function wf(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,we._)`{}`);return e!==void 0&&cc(t,r,e),r}oe.evaluatedPropsToName=wf;function cc(t,e,r){Object.keys(r).forEach(n=>t.assign((0,we._)`${e}${(0,we.getProperty)(n)}`,!0))}oe.setEvaluated=cc;var ff={};function gx(t,e){return t.scopeValue("func",{ref:e,code:ff[e.code]||(ff[e.code]=new lx._Code(e.code))})}oe.useFunc=gx;var ac;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(ac||(oe.Type=ac={}));function yx(t,e,r){if(t instanceof we.Name){let n=e===ac.Num;return r?n?(0,we._)`"[" + ${t} + "]"`:(0,we._)`"['" + ${t} + "']"`:n?(0,we._)`"/" + ${t}`:(0,we._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,we.getProperty)(t).toString():"/"+lc(t)}oe.getErrorPath=yx;function vf(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}oe.checkStrictMode=vf});var Mt=U(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});var qe=re(),bx={data:new qe.Name("data"),valCxt:new qe.Name("valCxt"),instancePath:new qe.Name("instancePath"),parentData:new qe.Name("parentData"),parentDataProperty:new qe.Name("parentDataProperty"),rootData:new qe.Name("rootData"),dynamicAnchors:new qe.Name("dynamicAnchors"),vErrors:new qe.Name("vErrors"),errors:new qe.Name("errors"),this:new qe.Name("this"),self:new qe.Name("self"),scope:new qe.Name("scope"),json:new qe.Name("json"),jsonPos:new qe.Name("jsonPos"),jsonLen:new qe.Name("jsonLen"),jsonPart:new qe.Name("jsonPart")};dc.default=bx});var to=U(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.extendErrors=ze.resetErrorsCount=ze.reportExtraError=ze.reportError=ze.keyword$DataError=ze.keywordError=void 0;var pe=re(),Ys=ue(),Ke=Mt();ze.keywordError={message:({keyword:t})=>(0,pe.str)`must pass "${t}" keyword validation`};ze.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,pe.str)`"${t}" keyword must be ${e} ($data)`:(0,pe.str)`"${t}" keyword is invalid ($data)`};function wx(t,e=ze.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,l=kf(t,e,r);n??(i||a)?_f(s,l):Sf(o,(0,pe._)`[${l}]`)}ze.reportError=wx;function vx(t,e=ze.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=kf(t,e,r);_f(o,a),s||i||Sf(n,Ke.default.vErrors)}ze.reportExtraError=vx;function _x(t,e){t.assign(Ke.default.errors,e),t.if((0,pe._)`${Ke.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,pe._)`${Ke.default.vErrors}.length`,e),()=>t.assign(Ke.default.vErrors,null)))}ze.resetErrorsCount=_x;function Sx({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,Ke.default.errors,a=>{t.const(i,(0,pe._)`${Ke.default.vErrors}[${a}]`),t.if((0,pe._)`${i}.instancePath === undefined`,()=>t.assign((0,pe._)`${i}.instancePath`,(0,pe.strConcat)(Ke.default.instancePath,s.errorPath))),t.assign((0,pe._)`${i}.schemaPath`,(0,pe.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,pe._)`${i}.schema`,r),t.assign((0,pe._)`${i}.data`,n))})}ze.extendErrors=Sx;function _f(t,e){let r=t.const("err",e);t.if((0,pe._)`${Ke.default.vErrors} === null`,()=>t.assign(Ke.default.vErrors,(0,pe._)`[${r}]`),(0,pe._)`${Ke.default.vErrors}.push(${r})`),t.code((0,pe._)`${Ke.default.errors}++`)}function Sf(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,pe._)`new ${t.ValidationError}(${e})`):(r.assign((0,pe._)`${n}.errors`,e),r.return(!1))}var Sr={keyword:new pe.Name("keyword"),schemaPath:new pe.Name("schemaPath"),params:new pe.Name("params"),propertyName:new pe.Name("propertyName"),message:new pe.Name("message"),schema:new pe.Name("schema"),parentSchema:new pe.Name("parentSchema")};function kf(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,pe._)`{}`:kx(t,e,r)}function kx(t,e,r={}){let{gen:n,it:o}=t,s=[Tx(o,r),xx(t,r)];return Rx(t,e,s),n.object(...s)}function Tx({errorPath:t},{instancePath:e}){let r=e?(0,pe.str)`${t}${(0,Ys.getErrorPath)(e,Ys.Type.Str)}`:t;return[Ke.default.instancePath,(0,pe.strConcat)(Ke.default.instancePath,r)]}function xx({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,pe.str)`${e}/${t}`;return r&&(o=(0,pe.str)`${o}${(0,Ys.getErrorPath)(r,Ys.Type.Str)}`),[Sr.schemaPath,o]}function Rx(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:l,propertyName:d,topSchemaRef:p,schemaPath:f}=a;n.push([Sr.keyword,o],[Sr.params,typeof e=="function"?e(t):e||(0,pe._)`{}`]),l.messages&&n.push([Sr.message,typeof r=="function"?r(t):r]),l.verbose&&n.push([Sr.schema,i],[Sr.parentSchema,(0,pe._)`${p}${f}`],[Ke.default.data,s]),d&&n.push([Sr.propertyName,d])}});var xf=U(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});Zr.boolOrEmptySchema=Zr.topBoolOrEmptySchema=void 0;var $x=to(),Ex=re(),Px=Mt(),Ax={message:"boolean schema is false"};function Cx(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Tf(t,!1):typeof r=="object"&&r.$async===!0?e.return(Px.default.data):(e.assign((0,Ex._)`${n}.errors`,null),e.return(!0))}Zr.topBoolOrEmptySchema=Cx;function Ix(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Tf(t)):r.var(e,!0)}Zr.boolOrEmptySchema=Ix;function Tf(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,$x.reportError)(o,Ax,void 0,e)}});var uc=U(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});Qr.getRules=Qr.isJSONType=void 0;var Ox=["string","number","integer","boolean","null","object","array"],Nx=new Set(Ox);function Lx(t){return typeof t=="string"&&Nx.has(t)}Qr.isJSONType=Lx;function jx(){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:{}}}Qr.getRules=jx});var pc=U(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.shouldUseRule=rr.shouldUseGroup=rr.schemaHasRulesForType=void 0;function Dx({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Rf(t,n)}rr.schemaHasRulesForType=Dx;function Rf(t,e){return e.rules.some(r=>$f(t,r))}rr.shouldUseGroup=Rf;function $f(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))}rr.shouldUseRule=$f});var ro=U(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.reportTypeError=Be.checkDataTypes=Be.checkDataType=Be.coerceAndCheckDataType=Be.getJSONTypes=Be.getSchemaTypes=Be.DataType=void 0;var Ux=uc(),Mx=pc(),qx=to(),te=re(),Ef=ue(),en;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(en||(Be.DataType=en={}));function zx(t){let e=Pf(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}Be.getSchemaTypes=zx;function Pf(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(Ux.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Be.getJSONTypes=Pf;function Bx(t,e){let{gen:r,data:n,opts:o}=t,s=Fx(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,Mx.schemaHasRulesForType)(t,e[0]));if(i){let a=hc(e,n,o.strictNumbers,en.Wrong);r.if(a,()=>{s.length?Hx(t,e,s):fc(t)})}return i}Be.coerceAndCheckDataType=Bx;var Af=new Set(["string","number","integer","boolean","null"]);function Fx(t,e){return e?t.filter(r=>Af.has(r)||e==="array"&&r==="array"):[]}function Hx(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,te._)`typeof ${o}`),a=n.let("coerced",(0,te._)`undefined`);s.coerceTypes==="array"&&n.if((0,te._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,te._)`${o}[0]`).assign(i,(0,te._)`typeof ${o}`).if(hc(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,te._)`${a} !== undefined`);for(let d of r)(Af.has(d)||d==="array"&&s.coerceTypes==="array")&&l(d);n.else(),fc(t),n.endIf(),n.if((0,te._)`${a} !== undefined`,()=>{n.assign(o,a),Kx(t,a)});function l(d){switch(d){case"string":n.elseIf((0,te._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,te._)`"" + ${o}`).elseIf((0,te._)`${o} === null`).assign(a,(0,te._)`""`);return;case"number":n.elseIf((0,te._)`${i} == "boolean" || ${o} === null
2006
+ ]`;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 vl,yt,qT,Us=j(()=>{er();yt={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:()=>(vl===void 0&&(vl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),vl),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-_]*$/};qT=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});import{ZodFirstPartyTypeKind as Kn}from"zod/v3";function Ms(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===Kn.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:X(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??ke(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:X(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===Kn.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Ds(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===Kn.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===Kn.ZodBranded&&t.keyType._def.type._def.typeName===Kn.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Ls(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var qs=j(()=>{Pe();Us();js();lt()});function Mm(t,e){if(e.mapStrategy==="record")return Ms(t,e);let r=X(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||ke(e),n=X(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||ke(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var Sl=j(()=>{Pe();qs();lt()});function qm(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 kl=j(()=>{});function zm(t){return t.target==="openAi"?void 0:{not:ke({...t,currentPath:[...t.currentPath,"not"]})}}var Tl=j(()=>{lt()});function Bm(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var xl=j(()=>{});function Hm(t,e){if(e.target==="openApi3")return Fm(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Vn&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Vn[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 Fm(t,e)}var Vn,Fm,zs=j(()=>{Pe();Vn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Fm=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>X(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 Km(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:Vn[t.innerType._def.typeName],nullable:!0}:{type:[Vn[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=X(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=X(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var Rl=j(()=>{Pe();zs()});function Vm(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",ll(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ce(r,"minimum",n.value,n.message,e):ce(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ce(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ce(r,"maximum",n.value,n.message,e):ce(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ce(r,"maximum",n.value,n.message,e));break;case"multipleOf":ce(r,"multipleOf",n.value,n.message,e);break}return r}var $l=j(()=>{er()});function Gm(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 d=FT(l);d&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),d=!1);let p=X(l._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});p!==void 0&&(n.properties[a]=p,d||o.push(a))}o.length&&(n.required=o);let i=BT(t,e);return i!==void 0&&(n.additionalProperties=i),n}function BT(t,e){if(t.catchall._def.typeName!=="ZodNever")return X(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 FT(t){try{return t.isOptional()}catch{return!0}}var El=j(()=>{Pe()});var Wm,Pl=j(()=>{Pe();lt();Wm=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return X(t.innerType._def,e);let r=X(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:ke(e)},r]}:ke(e)}});var Jm,Al=j(()=>{Pe();Jm=(t,e)=>{if(e.pipeStrategy==="input")return X(t.in._def,e);if(e.pipeStrategy==="output")return X(t.out._def,e);let r=X(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=X(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function Ym(t,e){return X(t.type._def,e)}var Cl=j(()=>{Pe()});function Xm(t,e){let n={type:"array",uniqueItems:!0,items:X(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ce(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ce(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var Il=j(()=>{er();Pe()});function Zm(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>X(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:X(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>X(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var Ol=j(()=>{Pe()});function Qm(t){return{not:ke(t)}}var Nl=j(()=>{lt()});function ef(t){return ke(t)}var Ll=j(()=>{lt()});var tf,jl=j(()=>{Pe();tf=(t,e)=>X(t.innerType._def,e)});import{ZodFirstPartyTypeKind as le}from"zod/v3";var rf,Dl=j(()=>{lt();cl();dl();ul();js();pl();ml();fl();gl();yl();bl();wl();Sl();kl();Tl();xl();Rl();$l();El();Pl();Al();Cl();qs();Il();Us();Ol();Nl();zs();Ll();jl();rf=(t,e,r)=>{switch(e){case le.ZodString:return Ds(t,r);case le.ZodNumber:return Vm(t,r);case le.ZodObject:return Gm(t,r);case le.ZodBigInt:return Am(t,r);case le.ZodBoolean:return Cm();case le.ZodDate:return hl(t,r);case le.ZodUndefined:return Qm(r);case le.ZodNull:return Bm(r);case le.ZodArray:return Pm(t,r);case le.ZodUnion:case le.ZodDiscriminatedUnion:return Hm(t,r);case le.ZodIntersection:return jm(t,r);case le.ZodTuple:return Zm(t,r);case le.ZodRecord:return Ms(t,r);case le.ZodLiteral:return Dm(t,r);case le.ZodEnum:return Lm(t);case le.ZodNativeEnum:return qm(t);case le.ZodNullable:return Km(t,r);case le.ZodOptional:return Wm(t,r);case le.ZodMap:return Mm(t,r);case le.ZodSet:return Xm(t,r);case le.ZodLazy:return()=>t.getter()._def;case le.ZodPromise:return Ym(t,r);case le.ZodNaN:case le.ZodNever:return zm(r);case le.ZodEffects:return Nm(t,r);case le.ZodAny:return ke(r);case le.ZodUnknown:return ef(r);case le.ZodDefault:return Om(t,r);case le.ZodBranded:return Ls(t,r);case le.ZodReadonly:return tf(t,r);case le.ZodCatch:return Im(t,r);case le.ZodPipeline:return Jm(t,r);case le.ZodFunction:case le.ZodVoid:case le.ZodSymbol:return;default:return(n=>{})(e)}}});function X(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==Rm)return a}if(n&&!r){let a=HT(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=rf(t,t.typeName,e),i=typeof s=="function"?X(s(),e):s;if(i&&KT(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var HT,KT,Pe=j(()=>{Is();Dl();Ns();lt();HT=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Os(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`),ke(e)):e.$refStrategy==="seen"?ke(e):void 0}},KT=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var nf=j(()=>{});var Ul,Ml=j(()=>{Pe();al();lt();Ul=(t,e)=>{let r=Em(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[d,p])=>({...l,[d]:X(p._def,{...r,currentPath:[...r.basePath,r.definitionPath,d]},!0)??ke(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=X(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??ke(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 of=j(()=>{Is();al();er();Ns();Pe();nf();lt();cl();dl();ul();js();pl();ml();fl();gl();yl();bl();wl();Sl();kl();Tl();xl();Rl();$l();El();Pl();Al();Cl();jl();qs();Il();Us();Ol();Nl();zs();Ll();Dl();Ml();Ml()});import*as sf from"zod/v4-mini";function VT(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function ql(t,e){return $t(t)?sf.toJSONSchema(t,{target:VT(e?.target),io:e?.pipeStrategy??"input"}):Ul(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function zl(t){let r=Xt(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Fr(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Bl(t,e){let r=Yt(t,e);if(!r.success)throw r.error;return r.data}var Fl=j(()=>{Nn();of()});function af(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function lf(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];af(i)&&af(s)?r[o]={...i,...s}:r[o]=s}return r}var GT,Bs,cf=j(()=>{Nn();Jr();Tm();Fl();GT=6e4,Bs=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(fs,r=>{this._oncancel(r)}),this.setNotificationHandler(ys,r=>{this._onprogress(r)}),this.setRequestHandler(gs,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(bs,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new z(K.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(vs,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,d=l.id,p=this._requestResolvers.get(d);if(p)if(this._requestResolvers.delete(d),a.type==="response")p(l);else{let f=l,_=new z(f.error.code,f.error.message,f.error.data);p(_)}else{let f=a.type==="response"?"Response":"Error";this._onerror(new Error(`${f} handler missing for request ${d}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new z(K.InvalidParams,`Task not found: ${s}`);if(!Qt(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Qt(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Zt]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(_s,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(K.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(ks,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new z(K.InvalidParams,`Task not found: ${r.params.taskId}`);if(Qt(o.status))throw new z(K.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(K.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof z?o:new z(K.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(K.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),jn(s)||hm(s)?this._onresponse(s):Ga(s)?this._onrequest(s,i):pm(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(K.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?.[Zt]?.taskId;if(n===void 0){let p={jsonrpc:"2.0",id:e.id,error:{code:K.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:p,timestamp:Date.now()},o?.sessionId).catch(f=>this._onerror(new Error(`Failed to enqueue error response: ${f}`))):o?.send(p).catch(f=>this._onerror(new Error(`Failed to send an error response: ${f}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=cm(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,d={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async p=>{if(i.signal.aborted)return;let f={relatedRequestId:e.id};s&&(f.relatedTask={taskId:s}),await this.notification(p,f)},sendRequest:async(p,f,_)=>{if(i.signal.aborted)throw new z(K.ConnectionClosed,"Request was cancelled");let y={..._,relatedRequestId:e.id};s&&!y.relatedTask&&(y.relatedTask={taskId:s});let k=y.relatedTask?.taskId??s;return k&&l&&await l.updateTaskStatus(k,"input_required"),await this.request(p,f,y)},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,d)).then(async p=>{if(i.signal.aborted)return;let f={result:p,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:f,timestamp:Date.now()},o?.sessionId):await o?.send(f)},async p=>{if(i.signal.aborted)return;let f={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(p.code)?p.code:K.InternalError,message:p.message??"Internal error",...p.data!==void 0&&{data:p.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:f,timestamp:Date.now()},o?.sessionId):await o?.send(f)}).catch(p=>this._onerror(new Error(`Failed to send response: ${p}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,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),jn(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(jn(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),jn(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(K.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Kr,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new z(K.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Qt(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(K.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new z(K.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(d=>setTimeout(d,l)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof z?i:new z(K.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:l}=n??{};return new Promise((d,p)=>{let f=I=>{p(I)};if(!this._transport){f(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(I){f(I);return}n?.signal?.throwIfAborted();let _=this._requestMessageId++,y={...e,jsonrpc:"2.0",id:_};n?.onprogress&&(this._progressHandlers.set(_,n.onprogress),y.params={...e.params,_meta:{...e.params?._meta||{},progressToken:_}}),a&&(y.params={...y.params,task:a}),l&&(y.params={...y.params,_meta:{...y.params?._meta||{},[Zt]:l}});let k=I=>{this._responseHandlers.delete(_),this._progressHandlers.delete(_),this._cleanupTimeout(_),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:_,reason:String(I)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(Y=>this._onerror(new Error(`Failed to send cancellation: ${Y}`)));let D=I instanceof z?I:new z(K.RequestTimeout,String(I));p(D)};this._responseHandlers.set(_,I=>{if(!n?.signal?.aborted){if(I instanceof Error)return p(I);try{let D=Yt(r,I.result);D.success?d(D.data):p(D.error)}catch(D){p(D)}}}),n?.signal?.addEventListener("abort",()=>{k(n?.signal?.reason)});let R=n?.timeout??GT,$=()=>k(z.fromError(K.RequestTimeout,"Request timed out",{timeout:R}));this._setupTimeout(_,R,n?.maxTotalTimeout,$,n?.resetTimeoutOnProgress??!1);let P=l?.taskId;if(P){let I=D=>{let Y=this._responseHandlers.get(_);Y?Y(D):this._onerror(new Error(`Response handler missing for side-channeled request ${_}`))};this._requestResolvers.set(_,I),this._enqueueTaskMessage(P,{type:"request",message:y,timestamp:Date.now()}).catch(D=>{this._cleanupTimeout(_),p(D)})}else this._transport.send(y,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(I=>{this._cleanupTimeout(_),p(I)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},ws,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},Ss,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},gm,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||{},[Zt]: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||{},[Zt]: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||{},[Zt]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=zl(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Bl(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=zl(e);this._notificationHandlers.set(n,o=>{let s=Bl(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"&&Ga(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new z(K.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(K.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new z(K.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(K.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=zn.parse({method:"notifications/tasks/status",params:a});await this.notification(l),Qt(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(K.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Qt(a.status))throw new z(K.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 d=zn.parse({method:"notifications/tasks/status",params:l});await this.notification(d),Qt(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var Jn=U(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.regexpCode=he.getEsmExportName=he.getProperty=he.safeStringify=he.stringify=he.strConcat=he.addCodeArg=he.str=he._=he.nil=he._Code=he.Name=he.IDENTIFIER=he._CodeOrName=void 0;var Gn=class{};he._CodeOrName=Gn;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var br=class extends Gn{constructor(e){if(super(),!he.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}}};he.Name=br;var ct=class extends Gn{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 br&&(r[n.str]=(r[n.str]||0)+1),r),{})}};he._Code=ct;he.nil=new ct("");function df(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Kl(r,e[n]),r.push(t[++n]);return new ct(r)}he._=df;var Hl=new ct("+");function uf(t,...e){let r=[Wn(t[0])],n=0;for(;n<e.length;)r.push(Hl),Kl(r,e[n]),r.push(Hl,Wn(t[++n]));return WT(r),new ct(r)}he.str=uf;function Kl(t,e){e instanceof ct?t.push(...e._items):e instanceof br?t.push(e):t.push(XT(e))}he.addCodeArg=Kl;function WT(t){let e=1;for(;e<t.length-1;){if(t[e]===Hl){let r=JT(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function JT(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof br||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 br))return`"${t}${e.slice(1)}`}function YT(t,e){return e.emptyStr()?t:t.emptyStr()?e:uf`${t}${e}`}he.strConcat=YT;function XT(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Wn(Array.isArray(t)?t.join(","):t)}function ZT(t){return new ct(Wn(t))}he.stringify=ZT;function Wn(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}he.safeStringify=Wn;function QT(t){return typeof t=="string"&&he.IDENTIFIER.test(t)?new ct(`.${t}`):df`[${t}]`}he.getProperty=QT;function ex(t){if(typeof t=="string"&&he.IDENTIFIER.test(t))return new ct(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}he.getEsmExportName=ex;function tx(t){return new ct(t.toString())}he.regexpCode=tx});var Wl=U(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.ValueScope=Xe.ValueScopeName=Xe.Scope=Xe.varKinds=Xe.UsedValueState=void 0;var Ye=Jn(),Vl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Fs;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Fs||(Xe.UsedValueState=Fs={}));Xe.varKinds={const:new Ye.Name("const"),let:new Ye.Name("let"),var:new Ye.Name("var")};var Hs=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ye.Name?e:this.name(e)}name(e){return new Ye.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}}};Xe.Scope=Hs;var Ks=class extends Ye.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Ye._)`.${new Ye.Name(r)}[${n}]`}};Xe.ValueScopeName=Ks;var rx=(0,Ye._)`\n`,Gl=class extends Hs{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?rx:Ye.nil}}get(){return this._scope}name(e){return new Ks(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 p=a.get(i);if(p)return p}else a=this._values[s]=new Map;a.set(i,o);let l=this._scope[s]||(this._scope[s]=[]),d=l.length;return l[d]=r.ref,o.setValue(r,{property:s,itemIndex:d}),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,Ye._)`${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=Ye.nil;for(let i in e){let a=e[i];if(!a)continue;let l=n[i]=n[i]||new Map;a.forEach(d=>{if(l.has(d))return;l.set(d,Fs.Started);let p=r(d);if(p){let f=this.opts.es5?Xe.varKinds.var:Xe.varKinds.const;s=(0,Ye._)`${s}${f} ${d} = ${p};${this.opts._n}`}else if(p=o?.(d))s=(0,Ye._)`${s}${p}${this.opts._n}`;else throw new Vl(d);l.set(d,Fs.Completed)})}return s}};Xe.ValueScope=Gl});var re=U(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.or=ne.and=ne.not=ne.CodeGen=ne.operators=ne.varKinds=ne.ValueScopeName=ne.ValueScope=ne.Scope=ne.Name=ne.regexpCode=ne.stringify=ne.getProperty=ne.nil=ne.strConcat=ne.str=ne._=void 0;var de=Jn(),wt=Wl(),tr=Jn();Object.defineProperty(ne,"_",{enumerable:!0,get:function(){return tr._}});Object.defineProperty(ne,"str",{enumerable:!0,get:function(){return tr.str}});Object.defineProperty(ne,"strConcat",{enumerable:!0,get:function(){return tr.strConcat}});Object.defineProperty(ne,"nil",{enumerable:!0,get:function(){return tr.nil}});Object.defineProperty(ne,"getProperty",{enumerable:!0,get:function(){return tr.getProperty}});Object.defineProperty(ne,"stringify",{enumerable:!0,get:function(){return tr.stringify}});Object.defineProperty(ne,"regexpCode",{enumerable:!0,get:function(){return tr.regexpCode}});Object.defineProperty(ne,"Name",{enumerable:!0,get:function(){return tr.Name}});var Js=Wl();Object.defineProperty(ne,"Scope",{enumerable:!0,get:function(){return Js.Scope}});Object.defineProperty(ne,"ValueScope",{enumerable:!0,get:function(){return Js.ValueScope}});Object.defineProperty(ne,"ValueScopeName",{enumerable:!0,get:function(){return Js.ValueScopeName}});Object.defineProperty(ne,"varKinds",{enumerable:!0,get:function(){return Js.varKinds}});ne.operators={GT:new de._Code(">"),GTE:new de._Code(">="),LT:new de._Code("<"),LTE:new de._Code("<="),EQ:new de._Code("==="),NEQ:new de._Code("!=="),NOT:new de._Code("!"),OR:new de._Code("||"),AND:new de._Code("&&"),ADD:new de._Code("+")};var Dt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Jl=class extends Dt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?wt.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=Xr(this.rhs,e,r)),this}get names(){return this.rhs instanceof de._CodeOrName?this.rhs.names:{}}},Vs=class extends Dt{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 de.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Xr(this.rhs,e,r),this}get names(){let e=this.lhs instanceof de.Name?{}:{...this.lhs.names};return Ws(e,this.rhs)}},Yl=class extends Vs{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Xl=class extends Dt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Zl=class extends Dt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Ql=class extends Dt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},ec=class extends Dt{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=Xr(this.code,e,r),this}get names(){return this.code instanceof de._CodeOrName?this.code.names:{}}},Yn=class extends Dt{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)||(nx(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>_r(e,r.names),{})}},Ut=class extends Yn{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},tc=class extends Yn{},Yr=class extends Ut{};Yr.kind="else";var wr=class t extends Ut{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 Yr(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(pf(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=Xr(this.condition,e,r),this}get names(){let e=super.names;return Ws(e,this.condition),this.else&&_r(e,this.else.names),e}};wr.kind="if";var vr=class extends Ut{};vr.kind="for";var rc=class extends vr{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=Xr(this.iteration,e,r),this}get names(){return _r(super.names,this.iteration.names)}},nc=class extends vr{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?wt.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=Ws(super.names,this.from);return Ws(e,this.to)}},Gs=class extends vr{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=Xr(this.iterable,e,r),this}get names(){return _r(super.names,this.iterable.names)}},Xn=class extends Ut{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)}};Xn.kind="func";var Zn=class extends Yn{render(e){return"return "+super.render(e)}};Zn.kind="return";var oc=class extends Ut{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&&_r(e,this.catch.names),this.finally&&_r(e,this.finally.names),e}},Qn=class extends Ut{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Qn.kind="catch";var eo=class extends Ut{render(e){return"finally"+super.render(e)}};eo.kind="finally";var sc=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
2007
+ `:""},this._extScope=e,this._scope=new wt.Scope({parent:e}),this._nodes=[new tc]}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 Jl(e,s,n)),s}const(e,r,n){return this._def(wt.varKinds.const,e,r,n)}let(e,r,n){return this._def(wt.varKinds.let,e,r,n)}var(e,r,n){return this._def(wt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Vs(e,r,n))}add(e,r){return this._leafNode(new Yl(e,ne.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==de.nil&&this._leafNode(new ec(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,de.addCodeArg)(r,o));return r.push("}"),new de._Code(r)}if(e,r,n){if(this._blockNode(new wr(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 wr(e))}else(){return this._elseNode(new Yr)}endIf(){return this._endBlockNode(wr,Yr)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new rc(e),r)}forRange(e,r,n,o,s=this.opts.es5?wt.varKinds.var:wt.varKinds.let){let i=this._scope.toName(e);return this._for(new nc(s,i,r,n),()=>o(i))}forOf(e,r,n,o=wt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof de.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,de._)`${i}.length`,a=>{this.var(s,(0,de._)`${i}[${a}]`),n(s)})}return this._for(new Gs("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?wt.varKinds.var:wt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,de._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Gs("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(vr)}label(e){return this._leafNode(new Xl(e))}break(e){return this._leafNode(new Zl(e))}return(e){let r=new Zn;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Zn)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new oc;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Qn(s),r(s)}return n&&(this._currNode=o.finally=new eo,this.code(n)),this._endBlockNode(Qn,eo)}throw(e){return this._leafNode(new Ql(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=de.nil,n,o){return this._blockNode(new Xn(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Xn)}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 wr))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}};ne.CodeGen=sc;function _r(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Ws(t,e){return e instanceof de._CodeOrName?_r(t,e.names):t}function Xr(t,e,r){if(t instanceof de.Name)return n(t);if(!o(t))return t;return new de._Code(t._items.reduce((s,i)=>(i instanceof de.Name&&(i=n(i)),i instanceof de._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 de._Code&&s._items.some(i=>i instanceof de.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function nx(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function pf(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,de._)`!${ic(t)}`}ne.not=pf;var ox=hf(ne.operators.AND);function sx(...t){return t.reduce(ox)}ne.and=sx;var ix=hf(ne.operators.OR);function ax(...t){return t.reduce(ix)}ne.or=ax;function hf(t){return(e,r)=>e===de.nil?r:r===de.nil?e:(0,de._)`${ic(e)} ${t} ${ic(r)}`}function ic(t){return t instanceof de.Name?t:(0,de._)`(${t})`}});var ue=U(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.checkStrictMode=oe.getErrorPath=oe.Type=oe.useFunc=oe.setEvaluated=oe.evaluatedPropsToName=oe.mergeEvaluated=oe.eachItem=oe.unescapeJsonPointer=oe.escapeJsonPointer=oe.escapeFragment=oe.unescapeFragment=oe.schemaRefOrVal=oe.schemaHasRulesButRef=oe.schemaHasRules=oe.checkUnknownRules=oe.alwaysValidSchema=oe.toHash=void 0;var we=re(),lx=Jn();function cx(t){let e={};for(let r of t)e[r]=!0;return e}oe.toHash=cx;function dx(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(gf(t,e),!yf(e,t.self.RULES.all))}oe.alwaysValidSchema=dx;function gf(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]||vf(t,`unknown keyword: "${s}"`)}oe.checkUnknownRules=gf;function yf(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}oe.schemaHasRules=yf;function ux(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}oe.schemaHasRulesButRef=ux;function px({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,we._)`${r}`}return(0,we._)`${t}${e}${(0,we.getProperty)(n)}`}oe.schemaRefOrVal=px;function hx(t){return bf(decodeURIComponent(t))}oe.unescapeFragment=hx;function mx(t){return encodeURIComponent(lc(t))}oe.escapeFragment=mx;function lc(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}oe.escapeJsonPointer=lc;function bf(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}oe.unescapeJsonPointer=bf;function fx(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}oe.eachItem=fx;function mf({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let l=i===void 0?s:i instanceof we.Name?(s instanceof we.Name?t(o,s,i):e(o,s,i),i):s instanceof we.Name?(e(o,i,s),s):r(s,i);return a===we.Name&&!(l instanceof we.Name)?n(o,l):l}}oe.mergeEvaluated={props:mf({mergeNames:(t,e,r)=>t.if((0,we._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,we._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,we._)`${r} || {}`).code((0,we._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,we._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,we._)`${r} || {}`),cc(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:wf}),items:mf({mergeNames:(t,e,r)=>t.if((0,we._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,we._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,we._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,we._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function wf(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,we._)`{}`);return e!==void 0&&cc(t,r,e),r}oe.evaluatedPropsToName=wf;function cc(t,e,r){Object.keys(r).forEach(n=>t.assign((0,we._)`${e}${(0,we.getProperty)(n)}`,!0))}oe.setEvaluated=cc;var ff={};function gx(t,e){return t.scopeValue("func",{ref:e,code:ff[e.code]||(ff[e.code]=new lx._Code(e.code))})}oe.useFunc=gx;var ac;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(ac||(oe.Type=ac={}));function yx(t,e,r){if(t instanceof we.Name){let n=e===ac.Num;return r?n?(0,we._)`"[" + ${t} + "]"`:(0,we._)`"['" + ${t} + "']"`:n?(0,we._)`"/" + ${t}`:(0,we._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,we.getProperty)(t).toString():"/"+lc(t)}oe.getErrorPath=yx;function vf(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}oe.checkStrictMode=vf});var Mt=U(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});var qe=re(),bx={data:new qe.Name("data"),valCxt:new qe.Name("valCxt"),instancePath:new qe.Name("instancePath"),parentData:new qe.Name("parentData"),parentDataProperty:new qe.Name("parentDataProperty"),rootData:new qe.Name("rootData"),dynamicAnchors:new qe.Name("dynamicAnchors"),vErrors:new qe.Name("vErrors"),errors:new qe.Name("errors"),this:new qe.Name("this"),self:new qe.Name("self"),scope:new qe.Name("scope"),json:new qe.Name("json"),jsonPos:new qe.Name("jsonPos"),jsonLen:new qe.Name("jsonLen"),jsonPart:new qe.Name("jsonPart")};dc.default=bx});var to=U(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.extendErrors=ze.resetErrorsCount=ze.reportExtraError=ze.reportError=ze.keyword$DataError=ze.keywordError=void 0;var pe=re(),Ys=ue(),Ke=Mt();ze.keywordError={message:({keyword:t})=>(0,pe.str)`must pass "${t}" keyword validation`};ze.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,pe.str)`"${t}" keyword must be ${e} ($data)`:(0,pe.str)`"${t}" keyword is invalid ($data)`};function wx(t,e=ze.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,l=kf(t,e,r);n??(i||a)?_f(s,l):Sf(o,(0,pe._)`[${l}]`)}ze.reportError=wx;function vx(t,e=ze.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=kf(t,e,r);_f(o,a),s||i||Sf(n,Ke.default.vErrors)}ze.reportExtraError=vx;function _x(t,e){t.assign(Ke.default.errors,e),t.if((0,pe._)`${Ke.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,pe._)`${Ke.default.vErrors}.length`,e),()=>t.assign(Ke.default.vErrors,null)))}ze.resetErrorsCount=_x;function Sx({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,Ke.default.errors,a=>{t.const(i,(0,pe._)`${Ke.default.vErrors}[${a}]`),t.if((0,pe._)`${i}.instancePath === undefined`,()=>t.assign((0,pe._)`${i}.instancePath`,(0,pe.strConcat)(Ke.default.instancePath,s.errorPath))),t.assign((0,pe._)`${i}.schemaPath`,(0,pe.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,pe._)`${i}.schema`,r),t.assign((0,pe._)`${i}.data`,n))})}ze.extendErrors=Sx;function _f(t,e){let r=t.const("err",e);t.if((0,pe._)`${Ke.default.vErrors} === null`,()=>t.assign(Ke.default.vErrors,(0,pe._)`[${r}]`),(0,pe._)`${Ke.default.vErrors}.push(${r})`),t.code((0,pe._)`${Ke.default.errors}++`)}function Sf(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,pe._)`new ${t.ValidationError}(${e})`):(r.assign((0,pe._)`${n}.errors`,e),r.return(!1))}var Sr={keyword:new pe.Name("keyword"),schemaPath:new pe.Name("schemaPath"),params:new pe.Name("params"),propertyName:new pe.Name("propertyName"),message:new pe.Name("message"),schema:new pe.Name("schema"),parentSchema:new pe.Name("parentSchema")};function kf(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,pe._)`{}`:kx(t,e,r)}function kx(t,e,r={}){let{gen:n,it:o}=t,s=[Tx(o,r),xx(t,r)];return Rx(t,e,s),n.object(...s)}function Tx({errorPath:t},{instancePath:e}){let r=e?(0,pe.str)`${t}${(0,Ys.getErrorPath)(e,Ys.Type.Str)}`:t;return[Ke.default.instancePath,(0,pe.strConcat)(Ke.default.instancePath,r)]}function xx({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,pe.str)`${e}/${t}`;return r&&(o=(0,pe.str)`${o}${(0,Ys.getErrorPath)(r,Ys.Type.Str)}`),[Sr.schemaPath,o]}function Rx(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:l,propertyName:d,topSchemaRef:p,schemaPath:f}=a;n.push([Sr.keyword,o],[Sr.params,typeof e=="function"?e(t):e||(0,pe._)`{}`]),l.messages&&n.push([Sr.message,typeof r=="function"?r(t):r]),l.verbose&&n.push([Sr.schema,i],[Sr.parentSchema,(0,pe._)`${p}${f}`],[Ke.default.data,s]),d&&n.push([Sr.propertyName,d])}});var xf=U(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});Zr.boolOrEmptySchema=Zr.topBoolOrEmptySchema=void 0;var $x=to(),Ex=re(),Px=Mt(),Ax={message:"boolean schema is false"};function Cx(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Tf(t,!1):typeof r=="object"&&r.$async===!0?e.return(Px.default.data):(e.assign((0,Ex._)`${n}.errors`,null),e.return(!0))}Zr.topBoolOrEmptySchema=Cx;function Ix(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Tf(t)):r.var(e,!0)}Zr.boolOrEmptySchema=Ix;function Tf(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,$x.reportError)(o,Ax,void 0,e)}});var uc=U(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});Qr.getRules=Qr.isJSONType=void 0;var Ox=["string","number","integer","boolean","null","object","array"],Nx=new Set(Ox);function Lx(t){return typeof t=="string"&&Nx.has(t)}Qr.isJSONType=Lx;function jx(){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:{}}}Qr.getRules=jx});var pc=U(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.shouldUseRule=rr.shouldUseGroup=rr.schemaHasRulesForType=void 0;function Dx({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Rf(t,n)}rr.schemaHasRulesForType=Dx;function Rf(t,e){return e.rules.some(r=>$f(t,r))}rr.shouldUseGroup=Rf;function $f(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))}rr.shouldUseRule=$f});var ro=U(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.reportTypeError=Be.checkDataTypes=Be.checkDataType=Be.coerceAndCheckDataType=Be.getJSONTypes=Be.getSchemaTypes=Be.DataType=void 0;var Ux=uc(),Mx=pc(),qx=to(),te=re(),Ef=ue(),en;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(en||(Be.DataType=en={}));function zx(t){let e=Pf(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}Be.getSchemaTypes=zx;function Pf(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(Ux.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Be.getJSONTypes=Pf;function Bx(t,e){let{gen:r,data:n,opts:o}=t,s=Fx(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,Mx.schemaHasRulesForType)(t,e[0]));if(i){let a=mc(e,n,o.strictNumbers,en.Wrong);r.if(a,()=>{s.length?Hx(t,e,s):fc(t)})}return i}Be.coerceAndCheckDataType=Bx;var Af=new Set(["string","number","integer","boolean","null"]);function Fx(t,e){return e?t.filter(r=>Af.has(r)||e==="array"&&r==="array"):[]}function Hx(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,te._)`typeof ${o}`),a=n.let("coerced",(0,te._)`undefined`);s.coerceTypes==="array"&&n.if((0,te._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,te._)`${o}[0]`).assign(i,(0,te._)`typeof ${o}`).if(mc(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,te._)`${a} !== undefined`);for(let d of r)(Af.has(d)||d==="array"&&s.coerceTypes==="array")&&l(d);n.else(),fc(t),n.endIf(),n.if((0,te._)`${a} !== undefined`,()=>{n.assign(o,a),Kx(t,a)});function l(d){switch(d){case"string":n.elseIf((0,te._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,te._)`"" + ${o}`).elseIf((0,te._)`${o} === null`).assign(a,(0,te._)`""`);return;case"number":n.elseIf((0,te._)`${i} == "boolean" || ${o} === null
2008
2008
  || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,te._)`+${o}`);return;case"integer":n.elseIf((0,te._)`${i} === "boolean" || ${o} === null
2009
2009
  || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,te._)`+${o}`);return;case"boolean":n.elseIf((0,te._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,te._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,te._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,te._)`${i} === "string" || ${i} === "number"
2010
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,te._)`[${o}]`)}}}function Kx({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,te._)`${e} !== undefined`,()=>t.assign((0,te._)`${e}[${r}]`,n))}function mc(t,e,r,n=en.Correct){let o=n===en.Correct?te.operators.EQ:te.operators.NEQ,s;switch(t){case"null":return(0,te._)`${e} ${o} null`;case"array":s=(0,te._)`Array.isArray(${e})`;break;case"object":s=(0,te._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,te._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,te._)`typeof ${e} ${o} ${t}`}return n===en.Correct?s:(0,te.not)(s);function i(a=te.nil){return(0,te.and)((0,te._)`typeof ${e} == "number"`,a,r?(0,te._)`isFinite(${e})`:te.nil)}}Be.checkDataType=mc;function hc(t,e,r,n){if(t.length===1)return mc(t[0],e,r,n);let o,s=(0,Ef.toHash)(t);if(s.array&&s.object){let i=(0,te._)`typeof ${e} != "object"`;o=s.null?i:(0,te._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=te.nil;s.number&&delete s.integer;for(let i in s)o=(0,te.and)(o,mc(i,e,r,n));return o}Be.checkDataTypes=hc;var Vx={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,te._)`{type: ${t}}`:(0,te._)`{type: ${e}}`};function fc(t){let e=Gx(t);(0,qx.reportError)(e,Vx)}Be.reportTypeError=fc;function Gx(t){let{gen:e,data:r,schema:n}=t,o=(0,Ef.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var If=U(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});Xs.assignDefaults=void 0;var tn=re(),Wx=ue();function Jx(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Cf(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Cf(t,s,o.default))}Xs.assignDefaults=Jx;function Cf(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,tn._)`${s}${(0,tn.getProperty)(e)}`;if(o){(0,Wx.checkStrictMode)(t,`default is ignored for: ${a}`);return}let l=(0,tn._)`${a} === undefined`;i.useDefaults==="empty"&&(l=(0,tn._)`${l} || ${a} === null || ${a} === ""`),n.if(l,(0,tn._)`${a} = ${(0,tn.stringify)(r)}`)}});var dt=U(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.validateUnion=be.validateArray=be.usePattern=be.callValidateCode=be.schemaProperties=be.allSchemaProperties=be.noPropertyInData=be.propertyInData=be.isOwnProperty=be.hasPropFunc=be.reportMissingProp=be.checkMissingProp=be.checkReportMissingProp=void 0;var _e=re(),gc=ue(),nr=Mt(),Yx=ue();function Xx(t,e){let{gen:r,data:n,it:o}=t;r.if(bc(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,_e._)`${e}`},!0),t.error()})}be.checkReportMissingProp=Xx;function Zx({gen:t,data:e,it:{opts:r}},n,o){return(0,_e.or)(...n.map(s=>(0,_e.and)(bc(t,e,s,r.ownProperties),(0,_e._)`${o} = ${s}`)))}be.checkMissingProp=Zx;function Qx(t,e){t.setParams({missingProperty:e},!0),t.error()}be.reportMissingProp=Qx;function Of(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,_e._)`Object.prototype.hasOwnProperty`})}be.hasPropFunc=Of;function yc(t,e,r){return(0,_e._)`${Of(t)}.call(${e}, ${r})`}be.isOwnProperty=yc;function eR(t,e,r,n){let o=(0,_e._)`${e}${(0,_e.getProperty)(r)} !== undefined`;return n?(0,_e._)`${o} && ${yc(t,e,r)}`:o}be.propertyInData=eR;function bc(t,e,r,n){let o=(0,_e._)`${e}${(0,_e.getProperty)(r)} === undefined`;return n?(0,_e.or)(o,(0,_e.not)(yc(t,e,r))):o}be.noPropertyInData=bc;function Nf(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}be.allSchemaProperties=Nf;function tR(t,e){return Nf(e).filter(r=>!(0,gc.alwaysValidSchema)(t,e[r]))}be.schemaProperties=tR;function rR({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,l,d){let p=d?(0,_e._)`${t}, ${e}, ${n}${o}`:e,f=[[nr.default.instancePath,(0,_e.strConcat)(nr.default.instancePath,s)],[nr.default.parentData,i.parentData],[nr.default.parentDataProperty,i.parentDataProperty],[nr.default.rootData,nr.default.rootData]];i.opts.dynamicRef&&f.push([nr.default.dynamicAnchors,nr.default.dynamicAnchors]);let _=(0,_e._)`${p}, ${r.object(...f)}`;return l!==_e.nil?(0,_e._)`${a}.call(${l}, ${_})`:(0,_e._)`${a}(${_})`}be.callValidateCode=rR;var nR=(0,_e._)`new RegExp`;function oR({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,_e._)`${o.code==="new RegExp"?nR:(0,Yx.useFunc)(t,o)}(${r}, ${n})`})}be.usePattern=oR;function sR(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,_e._)`${r}.length`);e.forRange("i",0,l,d=>{t.subschema({keyword:n,dataProp:d,dataPropType:gc.Type.Num},s),e.if((0,_e.not)(s),a)})}}be.validateArray=sR;function iR(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,gc.alwaysValidSchema)(o,l))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((l,d)=>{let p=t.subschema({keyword:n,schemaProp:d,compositeRule:!0},a);e.assign(i,(0,_e._)`${i} || ${a}`),t.mergeValidEvaluated(p,a)||e.if((0,_e.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}be.validateUnion=iR});var Df=U(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.validateKeywordUsage=Et.validSchemaType=Et.funcKeywordCode=Et.macroKeywordCode=void 0;var Ve=re(),kr=Mt(),aR=dt(),lR=to();function cR(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),l=jf(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let d=r.name("valid");t.subschema({schema:a,schemaPath:Ve.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},d),t.pass(d,()=>t.error(!0))}Et.macroKeywordCode=cR;function dR(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:l}=t;pR(l,e);let d=!a&&e.compile?e.compile.call(l.self,s,i,l):e.validate,p=jf(n,o,d),f=n.let("valid");t.block$data(f,_),t.ok((r=e.valid)!==null&&r!==void 0?r:f);function _(){if(e.errors===!1)R(),e.modifying&&Lf(t),$(()=>t.error());else{let P=e.async?y():k();e.modifying&&Lf(t),$(()=>uR(t,P))}}function y(){let P=n.let("ruleErrs",null);return n.try(()=>R((0,Ve._)`await `),I=>n.assign(f,!1).if((0,Ve._)`${I} instanceof ${l.ValidationError}`,()=>n.assign(P,(0,Ve._)`${I}.errors`),()=>n.throw(I))),P}function k(){let P=(0,Ve._)`${p}.errors`;return n.assign(P,null),R(Ve.nil),P}function R(P=e.async?(0,Ve._)`await `:Ve.nil){let I=l.opts.passContext?kr.default.this:kr.default.self,D=!("compile"in e&&!a||e.schema===!1);n.assign(f,(0,Ve._)`${P}${(0,aR.callValidateCode)(t,p,I,D)}`,e.modifying)}function $(P){var I;n.if((0,Ve.not)((I=e.valid)!==null&&I!==void 0?I:f),P)}}Et.funcKeywordCode=dR;function Lf(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Ve._)`${n.parentData}[${n.parentDataProperty}]`))}function uR(t,e){let{gen:r}=t;r.if((0,Ve._)`Array.isArray(${e})`,()=>{r.assign(kr.default.vErrors,(0,Ve._)`${kr.default.vErrors} === null ? ${e} : ${kr.default.vErrors}.concat(${e})`).assign(kr.default.errors,(0,Ve._)`${kr.default.vErrors}.length`),(0,lR.extendErrors)(t)},()=>t.error())}function pR({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function jf(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,Ve.stringify)(r)})}function mR(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")}Et.validSchemaType=mR;function hR({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)}}Et.validateKeywordUsage=hR});var Mf=U(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.extendSubschemaMode=or.extendSubschemaData=or.getSubschema=void 0;var Pt=re(),Uf=ue();function fR(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,Pt._)`${t.schemaPath}${(0,Pt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Pt._)`${t.schemaPath}${(0,Pt.getProperty)(e)}${(0,Pt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Uf.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')}or.getSubschema=fR;function gR(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:d,dataPathArr:p,opts:f}=e,_=a.let("data",(0,Pt._)`${e.data}${(0,Pt.getProperty)(r)}`,!0);l(_),t.errorPath=(0,Pt.str)`${d}${(0,Uf.getErrorPath)(r,n,f.jsPropertySyntax)}`,t.parentDataProperty=(0,Pt._)`${r}`,t.dataPathArr=[...p,t.parentDataProperty]}if(o!==void 0){let d=o instanceof Pt.Name?o:a.let("data",o,!0);l(d),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function l(d){t.data=d,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,d]}}or.extendSubschemaData=gR;function yR(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}or.extendSubschemaMode=yR});var wc=U((WD,qf)=>{"use strict";qf.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 Bf=U((JD,zf)=>{"use strict";var sr=zf.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(){};Zs(e,n,o,t,"",t)};sr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};sr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};sr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};sr.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 Zs(t,e,r,n,o,s,i,a,l,d){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,l,d);for(var p in n){var f=n[p];if(Array.isArray(f)){if(p in sr.arrayKeywords)for(var _=0;_<f.length;_++)Zs(t,e,r,f[_],o+"/"+p+"/"+_,s,o,p,n,_)}else if(p in sr.propsKeywords){if(f&&typeof f=="object")for(var y in f)Zs(t,e,r,f[y],o+"/"+p+"/"+bR(y),s,o,p,n,y)}else(p in sr.keywords||t.allKeys&&!(p in sr.skipKeywords))&&Zs(t,e,r,f,o+"/"+p,s,o,p,n)}r(n,o,s,i,a,l,d)}}function bR(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var no=U(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.getSchemaRefs=Ze.resolveUrl=Ze.normalizeId=Ze._getFullPath=Ze.getFullPath=Ze.inlineRef=void 0;var wR=ue(),vR=wc(),_R=Bf(),SR=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function kR(t,e=!0){return typeof t=="boolean"?!0:e===!0?!vc(t):e?Ff(t)<=e:!1}Ze.inlineRef=kR;var TR=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function vc(t){for(let e in t){if(TR.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(vc)||typeof r=="object"&&vc(r))return!0}return!1}function Ff(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!SR.has(r)&&(typeof t[r]=="object"&&(0,wR.eachItem)(t[r],n=>e+=Ff(n)),e===1/0))return 1/0}return e}function Hf(t,e="",r){r!==!1&&(e=rn(e));let n=t.parse(e);return Kf(t,n)}Ze.getFullPath=Hf;function Kf(t,e){return t.serialize(e).split("#")[0]+"#"}Ze._getFullPath=Kf;var xR=/#\/?$/;function rn(t){return t?t.replace(xR,""):""}Ze.normalizeId=rn;function RR(t,e,r){return r=rn(r),t.resolve(e,r)}Ze.resolveUrl=RR;var $R=/^[a-z_][-a-z0-9._]*$/i;function ER(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=rn(t[r]||e),s={"":o},i=Hf(n,o,!1),a={},l=new Set;return _R(t,{allKeys:!0},(f,_,y,k)=>{if(k===void 0)return;let R=i+_,$=s[k];typeof f[r]=="string"&&($=P.call(this,f[r])),I.call(this,f.$anchor),I.call(this,f.$dynamicAnchor),s[_]=$;function P(D){let Y=this.opts.uriResolver.resolve;if(D=rn($?Y($,D):D),l.has(D))throw p(D);l.add(D);let F=this.refs[D];return typeof F=="string"&&(F=this.refs[F]),typeof F=="object"?d(f,F.schema,D):D!==rn(R)&&(D[0]==="#"?(d(f,a[D],D),a[D]=f):this.refs[D]=R),D}function I(D){if(typeof D=="string"){if(!$R.test(D))throw new Error(`invalid anchor "${D}"`);P.call(this,`#${D}`)}}}),a;function d(f,_,y){if(_!==void 0&&!vR(f,_))throw p(y)}function p(f){return new Error(`reference "${f}" resolves to more than one schema`)}}Ze.getSchemaRefs=ER});var io=U(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.getData=ir.KeywordCxt=ir.validateFunctionCode=void 0;var Yf=xf(),Vf=ro(),Sc=pc(),Qs=ro(),PR=If(),so=Df(),_c=Mf(),B=re(),ee=Mt(),AR=no(),qt=ue(),oo=to();function CR(t){if(Qf(t)&&(eg(t),Zf(t))){NR(t);return}Xf(t,()=>(0,Yf.topBoolOrEmptySchema)(t))}ir.validateFunctionCode=CR;function Xf({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,B._)`${ee.default.data}, ${ee.default.valCxt}`,n.$async,()=>{t.code((0,B._)`"use strict"; ${Gf(r,o)}`),OR(t,o),t.code(s)}):t.func(e,(0,B._)`${ee.default.data}, ${IR(o)}`,n.$async,()=>t.code(Gf(r,o)).code(s))}function IR(t){return(0,B._)`{${ee.default.instancePath}="", ${ee.default.parentData}, ${ee.default.parentDataProperty}, ${ee.default.rootData}=${ee.default.data}${t.dynamicRef?(0,B._)`, ${ee.default.dynamicAnchors}={}`:B.nil}}={}`}function OR(t,e){t.if(ee.default.valCxt,()=>{t.var(ee.default.instancePath,(0,B._)`${ee.default.valCxt}.${ee.default.instancePath}`),t.var(ee.default.parentData,(0,B._)`${ee.default.valCxt}.${ee.default.parentData}`),t.var(ee.default.parentDataProperty,(0,B._)`${ee.default.valCxt}.${ee.default.parentDataProperty}`),t.var(ee.default.rootData,(0,B._)`${ee.default.valCxt}.${ee.default.rootData}`),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,B._)`${ee.default.valCxt}.${ee.default.dynamicAnchors}`)},()=>{t.var(ee.default.instancePath,(0,B._)`""`),t.var(ee.default.parentData,(0,B._)`undefined`),t.var(ee.default.parentDataProperty,(0,B._)`undefined`),t.var(ee.default.rootData,ee.default.data),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,B._)`{}`)})}function NR(t){let{schema:e,opts:r,gen:n}=t;Xf(t,()=>{r.$comment&&e.$comment&&rg(t),MR(t),n.let(ee.default.vErrors,null),n.let(ee.default.errors,0),r.unevaluated&&LR(t),tg(t),BR(t)})}function LR(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,B._)`${r}.evaluated`),e.if((0,B._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,B._)`${t.evaluated}.props`,(0,B._)`undefined`)),e.if((0,B._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,B._)`${t.evaluated}.items`,(0,B._)`undefined`))}function Gf(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,B._)`/*# sourceURL=${r} */`:B.nil}function jR(t,e){if(Qf(t)&&(eg(t),Zf(t))){DR(t,e);return}(0,Yf.boolOrEmptySchema)(t,e)}function Zf({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 Qf(t){return typeof t.schema!="boolean"}function DR(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&rg(t),qR(t),zR(t);let s=n.const("_errs",ee.default.errors);tg(t,s),n.var(e,(0,B._)`${s} === ${ee.default.errors}`)}function eg(t){(0,qt.checkUnknownRules)(t),UR(t)}function tg(t,e){if(t.opts.jtd)return Wf(t,[],!1,e);let r=(0,Vf.getSchemaTypes)(t.schema),n=(0,Vf.coerceAndCheckDataType)(t,r);Wf(t,r,!n,e)}function UR(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,qt.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function MR(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,qt.checkStrictMode)(t,"default is ignored in the schema root")}function qR(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,AR.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function zR(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function rg({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,B._)`${ee.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,B.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,B._)`${ee.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function BR(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,B._)`${ee.default.errors} === 0`,()=>e.return(ee.default.data),()=>e.throw((0,B._)`new ${o}(${ee.default.vErrors})`)):(e.assign((0,B._)`${n}.errors`,ee.default.vErrors),s.unevaluated&&FR(t),e.return((0,B._)`${ee.default.errors} === 0`))}function FR({gen:t,evaluated:e,props:r,items:n}){r instanceof B.Name&&t.assign((0,B._)`${e}.props`,r),n instanceof B.Name&&t.assign((0,B._)`${e}.items`,n)}function Wf(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:l,self:d}=t,{RULES:p}=d;if(s.$ref&&(l.ignoreKeywordsWithRef||!(0,qt.schemaHasRulesButRef)(s,p))){o.block(()=>og(t,"$ref",p.all.$ref.definition));return}l.jtd||HR(t,e),o.block(()=>{for(let _ of p.rules)f(_);f(p.post)});function f(_){(0,Sc.shouldUseGroup)(s,_)&&(_.type?(o.if((0,Qs.checkDataType)(_.type,i,l.strictNumbers)),Jf(t,_),e.length===1&&e[0]===_.type&&r&&(o.else(),(0,Qs.reportTypeError)(t)),o.endIf()):Jf(t,_),a||o.if((0,B._)`${ee.default.errors} === ${n||0}`))}}function Jf(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,PR.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Sc.shouldUseRule)(n,s)&&og(t,s.keyword,s.definition,e.type)})}function HR(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(KR(t,e),t.opts.allowUnionTypes||VR(t,e),GR(t,t.dataTypes))}function KR(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{ng(t.dataTypes,r)||kc(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),JR(t,e)}}function VR(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&kc(t,"use allowUnionTypes to allow union type keyword")}function GR(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Sc.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>WR(e,i))&&kc(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function WR(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function ng(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function JR(t,e){let r=[];for(let n of t.dataTypes)ng(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function kc(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,qt.checkStrictMode)(t,e,t.opts.strictTypes)}var ei=class{constructor(e,r,n){if((0,so.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,qt.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",sg(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,so.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",ee.default.errors))}result(e,r,n){this.failResult((0,B.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,B.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,B._)`${r} !== undefined && (${(0,B.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?oo.reportExtraError:oo.reportError)(this,this.def.error,r)}$dataError(){(0,oo.reportError)(this,this.def.$dataError||oo.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,oo.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=B.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=B.nil,r=B.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,B.or)((0,B._)`${o} === undefined`,r)),e!==B.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==B.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,B.or)(i(),a());function i(){if(n.length){if(!(r instanceof B.Name))throw new Error("ajv implementation error");let l=Array.isArray(n)?n:[n];return(0,B._)`${(0,Qs.checkDataTypes)(l,r,s.opts.strictNumbers,Qs.DataType.Wrong)}`}return B.nil}function a(){if(o.validateSchema){let l=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,B._)`!${l}(${r})`}return B.nil}}subschema(e,r){let n=(0,_c.getSubschema)(this.it,e);(0,_c.extendSubschemaData)(n,this.it,e),(0,_c.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return jR(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=qt.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=qt.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,B.Name)),!0}};ir.KeywordCxt=ei;function og(t,e,r,n){let o=new ei(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,so.funcKeywordCode)(o,r):"macro"in r?(0,so.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,so.funcKeywordCode)(o,r)}var YR=/^\/(?:[^~]|~0|~1)*$/,XR=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function sg(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return ee.default.rootData;if(t[0]==="/"){if(!YR.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ee.default.rootData}else{let d=XR.exec(t);if(!d)throw new Error(`Invalid JSON-pointer: ${t}`);let p=+d[1];if(o=d[2],o==="#"){if(p>=e)throw new Error(l("property/index",p));return n[e-p]}if(p>e)throw new Error(l("data",p));if(s=r[e-p],!o)return s}let i=s,a=o.split("/");for(let d of a)d&&(s=(0,B._)`${s}${(0,B.getProperty)((0,qt.unescapeJsonPointer)(d))}`,i=(0,B._)`${i} && ${s}`);return i;function l(d,p){return`Cannot access ${d} ${p} levels up, current level is ${e}`}}ir.getData=sg});var ti=U(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var Tc=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};xc.default=Tc});var ao=U(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var Rc=no(),$c=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Rc.resolveUrl)(e,r,n),this.missingSchema=(0,Rc.normalizeId)((0,Rc.getFullPath)(e,this.missingRef))}};Ec.default=$c});var ni=U(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.resolveSchema=ut.getCompilingSchema=ut.resolveRef=ut.compileSchema=ut.SchemaEnv=void 0;var vt=re(),ZR=ti(),Tr=Mt(),_t=no(),ig=ue(),QR=io(),nn=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,_t.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};ut.SchemaEnv=nn;function Ac(t){let e=ag.call(this,t);if(e)return e;let r=(0,_t.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new vt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:ZR.default,code:(0,vt._)`require("ajv/dist/runtime/validation_error").default`}));let l=i.scopeName("validate");t.validateName=l;let d={gen:i,allErrors:this.opts.allErrors,data:Tr.default.data,parentData:Tr.default.parentData,parentDataProperty:Tr.default.parentDataProperty,dataNames:[Tr.default.data],dataPathArr:[vt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,vt.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:vt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,vt._)`""`,opts:this.opts,self:this},p;try{this._compilations.add(t),(0,QR.validateFunctionCode)(d),i.optimize(this.opts.code.optimize);let f=i.toString();p=`${i.scopeRefs(Tr.default.scope)}return ${f}`,this.opts.code.process&&(p=this.opts.code.process(p,t));let y=new Function(`${Tr.default.self}`,`${Tr.default.scope}`,p)(this,this.scope.get());if(this.scope.value(l,{ref:y}),y.errors=null,y.schema=t.schema,y.schemaEnv=t,t.$async&&(y.$async=!0),this.opts.code.source===!0&&(y.source={validateName:l,validateCode:f,scopeValues:i._values}),this.opts.unevaluated){let{props:k,items:R}=d;y.evaluated={props:k instanceof vt.Name?void 0:k,items:R instanceof vt.Name?void 0:R,dynamicProps:k instanceof vt.Name,dynamicItems:R instanceof vt.Name},y.source&&(y.source.evaluated=(0,vt.stringify)(y.evaluated))}return t.validate=y,t}catch(f){throw delete t.validate,delete t.validateName,p&&this.logger.error("Error compiling schema, function code:",p),f}finally{this._compilations.delete(t)}}ut.compileSchema=Ac;function e$(t,e,r){var n;r=(0,_t.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=n$.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 nn({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=t$.call(this,s)}ut.resolveRef=e$;function t$(t){return(0,_t.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Ac.call(this,t)}function ag(t){for(let e of this._compilations)if(r$(e,t))return e}ut.getCompilingSchema=ag;function r$(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function n$(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||ri.call(this,t,e)}function ri(t,e){let r=this.opts.uriResolver.parse(e),n=(0,_t._getFullPath)(this.opts.uriResolver,r),o=(0,_t.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Pc.call(this,r,t);let s=(0,_t.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=ri.call(this,t,i);return typeof a?.schema!="object"?void 0:Pc.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Ac.call(this,i),s===(0,_t.normalizeId)(e)){let{schema:a}=i,{schemaId:l}=this.opts,d=a[l];return d&&(o=(0,_t.resolveUrl)(this.opts.uriResolver,o,d)),new nn({schema:a,schemaId:l,root:t,baseId:o})}return Pc.call(this,r,i)}}ut.resolveSchema=ri;var o$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Pc(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,ig.unescapeFragment)(a)];if(l===void 0)return;r=l;let d=typeof r=="object"&&r[this.opts.schemaId];!o$.has(a)&&d&&(e=(0,_t.resolveUrl)(this.opts.uriResolver,e,d))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,ig.schemaHasRulesButRef)(r,this.RULES)){let a=(0,_t.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=ri.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new nn({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var lg=U((t1,s$)=>{s$.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 Oc=U((r1,hg)=>{"use strict";var i$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),dg=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),Cc=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),ug=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),a$=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Ic(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 l$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function cg(t){return t.length=0,!0}function c$(t,e,r){if(t.length){let n=Ic(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function d$(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=c$;for(let l=0;l<t.length;l++){let d=t[l];if(!(d==="["||d==="]"))if(d===":"){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(d==="%"){if(!a(o,n,r))break;a=cg}else{o.push(d);continue}}return o.length&&(a===cg?r.zone=o.join(""):i?n.push(o.join("")):n.push(Ic(o))),r.address=n.join(""),r}function pg(t){if(u$(t,":")<2)return{host:t,isIPV6:!1};let e=d$(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 u$(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function p$(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 m$={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},h$=/[@/?#:]/g,f$=/[@/?#]/g;function mg(t,e){let r=e?f$:h$;return r.lastIndex=0,t.replace(r,n=>m$[n])}function g$(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(Cc(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&ug(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function y$(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(Cc(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&ug(s)?e+=s:e+="%"+o,r+=2;continue}}a$(t[r])?e+=t[r]:e+=escape(t[r])}return e}function b$(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(Cc(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function w$(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!dg(r)){let n=pg(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=mg(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}hg.exports={nonSimpleDomain:l$,recomposeAuthority:w$,reescapeHostDelimiters:mg,normalizePercentEncoding:g$,normalizePathEncoding:y$,escapePreservingEscapes:b$,removeDotSegments:p$,isIPv4:dg,isUUID:i$,normalizeIPv6:pg,stringArrayToHexStripped:Ic}});var wg=U((n1,bg)=>{"use strict";var{isUUID:v$}=Oc(),_$=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,S$=["http","https","ws","wss","urn","urn:uuid"];function k$(t){return S$.indexOf(t)!==-1}function Nc(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 fg(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function gg(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 T$(t){return t.secure=Nc(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function x$(t){if((t.port===(Nc(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 R$(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(_$);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=Lc(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function $$(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=Lc(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 E$(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!v$(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function P$(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var yg={scheme:"http",domainHost:!0,parse:fg,serialize:gg},A$={scheme:"https",domainHost:yg.domainHost,parse:fg,serialize:gg},oi={scheme:"ws",domainHost:!0,parse:T$,serialize:x$},C$={scheme:"wss",domainHost:oi.domainHost,parse:oi.parse,serialize:oi.serialize},I$={scheme:"urn",parse:R$,serialize:$$,skipNormalize:!0},O$={scheme:"urn:uuid",parse:E$,serialize:P$,skipNormalize:!0},si={http:yg,https:A$,ws:oi,wss:C$,urn:I$,"urn:uuid":O$};Object.setPrototypeOf(si,null);function Lc(t){return t&&(si[t]||si[t.toLowerCase()])||void 0}bg.exports={wsIsSecure:Nc,SCHEMES:si,isValidSchemeName:k$,getSchemeHandler:Lc}});var Tg=U((o1,li)=>{"use strict";var{normalizeIPv6:N$,removeDotSegments:lo,recomposeAuthority:L$,normalizePercentEncoding:j$,normalizePathEncoding:D$,escapePreservingEscapes:U$,reescapeHostDelimiters:M$,isIPv4:q$,nonSimpleDomain:z$}=Oc(),{SCHEMES:B$,getSchemeHandler:_g}=wg();function F$(t,e){return typeof t=="string"?t=Y$(t,e):typeof t=="object"&&(t=ai(xr(t,e),e)),t}function H$(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=ii(t,n),{parsed:i,malformedAuthorityOrPort:a}=ii(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let l=Sg(o,i,n,!0);return n.skipEscape=!0,xr(l,n)}function Sg(t,e,r,n){let o={};return n||(t=ai(xr(t,r),r),e=ai(xr(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=lo(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=lo(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=lo(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=lo(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 K$(t,e,r){let n=vg(t,r),o=vg(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function xr(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=_g(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=j$(r.path):(r.path=U$(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=L$(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=lo(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 V$=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,G$=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,W$=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function J$(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 ii(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(G$);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(W$);if(a!==null){let d=a[1],p=d.replace(/[\t\n\r]/g,"");p.length>=2&&(p.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):d.length!==p.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let l=t.match(V$);if(l){n.scheme=l[1],n.userinfo=l[3],n.host=l[4],n.port=parseInt(l[5],10),n.path=l[6]||"",n.query=l[7],n.fragment=l[8],isNaN(n.port)&&(n.port=l[5]);let d=J$(n,l);if(d!==void 0&&(n.error=n.error||d,o=!0),n.host)if(q$(n.host)===!1){let _=N$(n.host);n.host=_.host.toLowerCase(),s=_.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=_g(r.scheme||n.scheme);if(!r.unicodeSupport&&(!p||!p.unicodeSupport)&&n.host&&(r.domainHost||p&&p.domainHost)&&s===!1&&z$(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(f){n.error=n.error||"Host's domain name can not be converted to ASCII: "+f}if((!p||p&&!p.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=M$(unescape(n.host),s))),n.path&&(n.path=D$(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 ai(t,e){return ii(t,e).parsed}function Y$(t,e){return kg(t,e).normalized}function kg(t,e){let{parsed:r,malformedAuthorityOrPort:n}=ii(t,e);return{normalized:n?t:xr(r,e),malformedAuthorityOrPort:n}}function vg(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=kg(t,e);return n?void 0:r}if(typeof t=="object")return xr(t,e)}var jc={SCHEMES:B$,normalize:F$,resolve:H$,resolveComponent:Sg,equal:K$,serialize:xr,parse:ai};li.exports=jc;li.exports.default=jc;li.exports.fastUri=jc});var Rg=U(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});var xg=Tg();xg.code='require("ajv/dist/runtime/uri").default';Dc.default=xg});var Ng=U(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.CodeGen=Ue.Name=Ue.nil=Ue.stringify=Ue.str=Ue._=Ue.KeywordCxt=void 0;var X$=io();Object.defineProperty(Ue,"KeywordCxt",{enumerable:!0,get:function(){return X$.KeywordCxt}});var on=re();Object.defineProperty(Ue,"_",{enumerable:!0,get:function(){return on._}});Object.defineProperty(Ue,"str",{enumerable:!0,get:function(){return on.str}});Object.defineProperty(Ue,"stringify",{enumerable:!0,get:function(){return on.stringify}});Object.defineProperty(Ue,"nil",{enumerable:!0,get:function(){return on.nil}});Object.defineProperty(Ue,"Name",{enumerable:!0,get:function(){return on.Name}});Object.defineProperty(Ue,"CodeGen",{enumerable:!0,get:function(){return on.CodeGen}});var Z$=ti(),Cg=ao(),Q$=uc(),co=ni(),eE=re(),uo=no(),ci=ro(),Mc=ue(),$g=lg(),tE=Rg(),Ig=(t,e)=>new RegExp(t,e);Ig.code="new RegExp";var rE=["removeAdditional","useDefaults","coerceTypes"],nE=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),oE={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."},sE={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Eg=200;function iE(t){var e,r,n,o,s,i,a,l,d,p,f,_,y,k,R,$,P,I,D,Y,F,Oe,Ce,Bt,Ft;let Ht=t.strict,hn=(e=t.code)===null||e===void 0?void 0:e.optimize,dr=hn===!0||hn===void 0?1:hn||0,Tt=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Ig,Li=(o=t.uriResolver)!==null&&o!==void 0?o:tE.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Ht)!==null&&i!==void 0?i:!0,strictNumbers:(l=(a=t.strictNumbers)!==null&&a!==void 0?a:Ht)!==null&&l!==void 0?l:!0,strictTypes:(p=(d=t.strictTypes)!==null&&d!==void 0?d:Ht)!==null&&p!==void 0?p:"log",strictTuples:(_=(f=t.strictTuples)!==null&&f!==void 0?f:Ht)!==null&&_!==void 0?_:"log",strictRequired:(k=(y=t.strictRequired)!==null&&y!==void 0?y:Ht)!==null&&k!==void 0?k:!1,code:t.code?{...t.code,optimize:dr,regExp:Tt}:{optimize:dr,regExp:Tt},loopRequired:(R=t.loopRequired)!==null&&R!==void 0?R:Eg,loopEnum:($=t.loopEnum)!==null&&$!==void 0?$:Eg,meta:(P=t.meta)!==null&&P!==void 0?P:!0,messages:(I=t.messages)!==null&&I!==void 0?I:!0,inlineRefs:(D=t.inlineRefs)!==null&&D!==void 0?D:!0,schemaId:(Y=t.schemaId)!==null&&Y!==void 0?Y:"$id",addUsedSchema:(F=t.addUsedSchema)!==null&&F!==void 0?F:!0,validateSchema:(Oe=t.validateSchema)!==null&&Oe!==void 0?Oe:!0,validateFormats:(Ce=t.validateFormats)!==null&&Ce!==void 0?Ce:!0,unicodeRegExp:(Bt=t.unicodeRegExp)!==null&&Bt!==void 0?Bt:!0,int32range:(Ft=t.int32range)!==null&&Ft!==void 0?Ft:!0,uriResolver:Li}}var po=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,...iE(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new eE.ValueScope({scope:{},prefixes:nE,es5:r,lines:n}),this.logger=pE(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Q$.getRules)(),Pg.call(this,oE,e,"NOT SUPPORTED"),Pg.call(this,sE,e,"DEPRECATED","warn"),this._metaOpts=dE.call(this),e.formats&&lE.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&cE.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),aE.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=$g;n==="id"&&(o={...$g},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(p,f){await s.call(this,p.$schema);let _=this._addSchema(p,f);return _.validate||i.call(this,_)}async function s(p){p&&!this.getSchema(p)&&await o.call(this,{$ref:p},!0)}async function i(p){try{return this._compileSchemaEnv(p)}catch(f){if(!(f instanceof Cg.default))throw f;return a.call(this,f),await l.call(this,f.missingSchema),i.call(this,p)}}function a({missingSchema:p,missingRef:f}){if(this.refs[p])throw new Error(`AnySchema ${p} is loaded but ${f} cannot be resolved`)}async function l(p){let f=await d.call(this,p);this.refs[p]||await s.call(this,f.$schema),this.refs[p]||this.addSchema(f,p,r)}async function d(p){let f=this._loading[p];if(f)return f;try{return await(this._loading[p]=n(p))}finally{delete this._loading[p]}}}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,uo.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=Ag.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new co.SchemaEnv({schema:{},schemaId:n});if(r=co.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=Ag.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,uo.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(hE.call(this,n,r),!r)return(0,Mc.eachItem)(n,s=>Uc.call(this,s)),this;gE.call(this,r);let o={...r,type:(0,ci.getJSONTypes)(r.type),schemaType:(0,ci.getJSONTypes)(r.schemaType)};return(0,Mc.eachItem)(n,o.type.length===0?s=>Uc.call(this,s,o):s=>o.type.forEach(i=>Uc.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:d}=l.definition,p=i[a];d&&p&&(i[a]=Og(p))}}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,uo.normalizeId)(i||n);let d=uo.getSchemaRefs.call(this,e,n);return l=new co.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:d}),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):co.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{co.compileSchema.call(this,e)}finally{this.opts=r}}};po.ValidationError=Z$.default;po.MissingRefError=Cg.default;Ue.default=po;function Pg(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 Ag(t){return t=(0,uo.normalizeId)(t),this.schemas[t]||this.refs[t]}function aE(){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 lE(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function cE(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 dE(){let t={...this.opts};for(let e of rE)delete t[e];return t}var uE={log(){},warn(){},error(){}};function pE(t){if(t===!1)return uE;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 mE=/^[a-z_$][a-z0-9_$:-]*$/i;function hE(t,e){let{RULES:r}=this;if((0,Mc.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!mE.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 Uc(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,ci.getJSONTypes)(e.type),schemaType:(0,ci.getJSONTypes)(e.schemaType)}};e.before?fE.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 fE(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 gE(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Og(e)),t.validateSchema=this.compile(e,!0))}var yE={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Og(t){return{anyOf:[t,yE]}}});var Lg=U(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var bE={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};qc.default=bE});var Mg=U(Rr=>{"use strict";Object.defineProperty(Rr,"__esModule",{value:!0});Rr.callRef=Rr.getValidate=void 0;var wE=ao(),jg=dt(),Qe=re(),sn=Mt(),Dg=ni(),di=ue(),vE={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:d}=s;if((r==="#"||r==="#/")&&o===d.baseId)return f();let p=Dg.resolveRef.call(l,d,o,r);if(p===void 0)throw new wE.default(n.opts.uriResolver,o,r);if(p instanceof Dg.SchemaEnv)return _(p);return y(p);function f(){if(s===d)return ui(t,i,s,s.$async);let k=e.scopeValue("root",{ref:d});return ui(t,(0,Qe._)`${k}.validate`,d,d.$async)}function _(k){let R=Ug(t,k);ui(t,R,k,k.$async)}function y(k){let R=e.scopeValue("schema",a.code.source===!0?{ref:k,code:(0,Qe.stringify)(k)}:{ref:k}),$=e.name("valid"),P=t.subschema({schema:k,dataTypes:[],schemaPath:Qe.nil,topSchemaRef:R,errSchemaPath:r},$);t.mergeEvaluated(P),t.ok($)}}};function Ug(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Qe._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Rr.getValidate=Ug;function ui(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:l}=s,d=l.passContext?sn.default.this:Qe.nil;n?p():f();function p(){if(!a.$async)throw new Error("async schema referenced by sync schema");let k=o.let("valid");o.try(()=>{o.code((0,Qe._)`await ${(0,jg.callValidateCode)(t,e,d)}`),y(e),i||o.assign(k,!0)},R=>{o.if((0,Qe._)`!(${R} instanceof ${s.ValidationError})`,()=>o.throw(R)),_(R),i||o.assign(k,!1)}),t.ok(k)}function f(){t.result((0,jg.callValidateCode)(t,e,d),()=>y(e),()=>_(e))}function _(k){let R=(0,Qe._)`${k}.errors`;o.assign(sn.default.vErrors,(0,Qe._)`${sn.default.vErrors} === null ? ${R} : ${sn.default.vErrors}.concat(${R})`),o.assign(sn.default.errors,(0,Qe._)`${sn.default.vErrors}.length`)}function y(k){var R;if(!s.opts.unevaluated)return;let $=(R=r?.validate)===null||R===void 0?void 0:R.evaluated;if(s.props!==!0)if($&&!$.dynamicProps)$.props!==void 0&&(s.props=di.mergeEvaluated.props(o,$.props,s.props));else{let P=o.var("props",(0,Qe._)`${k}.evaluated.props`);s.props=di.mergeEvaluated.props(o,P,s.props,Qe.Name)}if(s.items!==!0)if($&&!$.dynamicItems)$.items!==void 0&&(s.items=di.mergeEvaluated.items(o,$.items,s.items));else{let P=o.var("items",(0,Qe._)`${k}.evaluated.items`);s.items=di.mergeEvaluated.items(o,P,s.items,Qe.Name)}}}Rr.callRef=ui;Rr.default=vE});var qg=U(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var _E=Lg(),SE=Mg(),kE=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",_E.default,SE.default];zc.default=kE});var zg=U(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var pi=re(),ar=pi.operators,mi={maximum:{okStr:"<=",ok:ar.LTE,fail:ar.GT},minimum:{okStr:">=",ok:ar.GTE,fail:ar.LT},exclusiveMaximum:{okStr:"<",ok:ar.LT,fail:ar.GTE},exclusiveMinimum:{okStr:">",ok:ar.GT,fail:ar.LTE}},TE={message:({keyword:t,schemaCode:e})=>(0,pi.str)`must be ${mi[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,pi._)`{comparison: ${mi[t].okStr}, limit: ${e}}`},xE={keyword:Object.keys(mi),type:"number",schemaType:"number",$data:!0,error:TE,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,pi._)`${r} ${mi[e].fail} ${n} || isNaN(${r})`)}};Bc.default=xE});var Bg=U(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});var mo=re(),RE={message:({schemaCode:t})=>(0,mo.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,mo._)`{multipleOf: ${t}}`},$E={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:RE,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,mo._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,mo._)`${i} !== parseInt(${i})`;t.fail$data((0,mo._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Fc.default=$E});var Hg=U(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});function Fg(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}Hc.default=Fg;Fg.code='require("ajv/dist/runtime/ucs2length").default'});var Kg=U(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});var $r=re(),EE=ue(),PE=Hg(),AE={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,$r.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,$r._)`{limit: ${t}}`},CE={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:AE,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?$r.operators.GT:$r.operators.LT,i=o.opts.unicode===!1?(0,$r._)`${r}.length`:(0,$r._)`${(0,EE.useFunc)(t.gen,PE.default)}(${r})`;t.fail$data((0,$r._)`${i} ${s} ${n}`)}};Kc.default=CE});var Vg=U(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});var IE=dt(),OE=ue(),an=re(),NE={message:({schemaCode:t})=>(0,an.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,an._)`{pattern: ${t}}`},LE={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:NE,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,d=l.code==="new RegExp"?(0,an._)`new RegExp`:(0,OE.useFunc)(e,l),p=e.let("valid");e.try(()=>e.assign(p,(0,an._)`${d}(${s}, ${a}).test(${r})`),()=>e.assign(p,!1)),t.fail$data((0,an._)`!${p}`)}else{let l=(0,IE.usePattern)(t,o);t.fail$data((0,an._)`!${l}.test(${r})`)}}};Vc.default=LE});var Gg=U(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var ho=re(),jE={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,ho.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,ho._)`{limit: ${t}}`},DE={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:jE,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?ho.operators.GT:ho.operators.LT;t.fail$data((0,ho._)`Object.keys(${r}).length ${o} ${n}`)}};Gc.default=DE});var Wg=U(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var fo=dt(),go=re(),UE=ue(),ME={message:({params:{missingProperty:t}})=>(0,go.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,go._)`{missingProperty: ${t}}`},qE={keyword:"required",type:"object",schemaType:"array",$data:!0,error:ME,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?d():p(),a.strictRequired){let y=t.parentSchema.properties,{definedProperties:k}=t.it;for(let R of r)if(y?.[R]===void 0&&!k.has(R)){let $=i.schemaEnv.baseId+i.errSchemaPath,P=`required property "${R}" is not defined at "${$}" (strictRequired)`;(0,UE.checkStrictMode)(i,P,i.opts.strictRequired)}}function d(){if(l||s)t.block$data(go.nil,f);else for(let y of r)(0,fo.checkReportMissingProp)(t,y)}function p(){let y=e.let("missing");if(l||s){let k=e.let("valid",!0);t.block$data(k,()=>_(y,k)),t.ok(k)}else e.if((0,fo.checkMissingProp)(t,r,y)),(0,fo.reportMissingProp)(t,y),e.else()}function f(){e.forOf("prop",n,y=>{t.setParams({missingProperty:y}),e.if((0,fo.noPropertyInData)(e,o,y,a.ownProperties),()=>t.error())})}function _(y,k){t.setParams({missingProperty:y}),e.forOf(y,n,()=>{e.assign(k,(0,fo.propertyInData)(e,o,y,a.ownProperties)),e.if((0,go.not)(k),()=>{t.error(),e.break()})},go.nil)}}};Wc.default=qE});var Jg=U(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});var yo=re(),zE={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,yo.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,yo._)`{limit: ${t}}`},BE={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:zE,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?yo.operators.GT:yo.operators.LT;t.fail$data((0,yo._)`${r}.length ${o} ${n}`)}};Jc.default=BE});var hi=U(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});var Yg=wc();Yg.code='require("ajv/dist/runtime/equal").default';Yc.default=Yg});var Xg=U(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});var Xc=ro(),Me=re(),FE=ue(),HE=hi(),KE={message:({params:{i:t,j:e}})=>(0,Me.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Me._)`{i: ${t}, j: ${e}}`},VE={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:KE,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"),d=s.items?(0,Xc.getSchemaTypes)(s.items):[];t.block$data(l,p,(0,Me._)`${i} === false`),t.ok(l);function p(){let k=e.let("i",(0,Me._)`${r}.length`),R=e.let("j");t.setParams({i:k,j:R}),e.assign(l,!0),e.if((0,Me._)`${k} > 1`,()=>(f()?_:y)(k,R))}function f(){return d.length>0&&!d.some(k=>k==="object"||k==="array")}function _(k,R){let $=e.name("item"),P=(0,Xc.checkDataTypes)(d,$,a.opts.strictNumbers,Xc.DataType.Wrong),I=e.const("indices",(0,Me._)`{}`);e.for((0,Me._)`;${k}--;`,()=>{e.let($,(0,Me._)`${r}[${k}]`),e.if(P,(0,Me._)`continue`),d.length>1&&e.if((0,Me._)`typeof ${$} == "string"`,(0,Me._)`${$} += "_"`),e.if((0,Me._)`typeof ${I}[${$}] == "number"`,()=>{e.assign(R,(0,Me._)`${I}[${$}]`),t.error(),e.assign(l,!1).break()}).code((0,Me._)`${I}[${$}] = ${k}`)})}function y(k,R){let $=(0,FE.useFunc)(e,HE.default),P=e.name("outer");e.label(P).for((0,Me._)`;${k}--;`,()=>e.for((0,Me._)`${R} = ${k}; ${R}--;`,()=>e.if((0,Me._)`${$}(${r}[${k}], ${r}[${R}])`,()=>{t.error(),e.assign(l,!1).break(P)})))}}};Zc.default=VE});var Zg=U(ed=>{"use strict";Object.defineProperty(ed,"__esModule",{value:!0});var Qc=re(),GE=ue(),WE=hi(),JE={message:"must be equal to constant",params:({schemaCode:t})=>(0,Qc._)`{allowedValue: ${t}}`},YE={keyword:"const",$data:!0,error:JE,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Qc._)`!${(0,GE.useFunc)(e,WE.default)}(${r}, ${o})`):t.fail((0,Qc._)`${s} !== ${r}`)}};ed.default=YE});var Qg=U(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var bo=re(),XE=ue(),ZE=hi(),QE={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,bo._)`{allowedValues: ${t}}`},e0={keyword:"enum",schemaType:"array",$data:!0,error:QE,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,d=()=>l??(l=(0,XE.useFunc)(e,ZE.default)),p;if(a||n)p=e.let("valid"),t.block$data(p,f);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let y=e.const("vSchema",s);p=(0,bo.or)(...o.map((k,R)=>_(y,R)))}t.pass(p);function f(){e.assign(p,!1),e.forOf("v",s,y=>e.if((0,bo._)`${d()}(${r}, ${y})`,()=>e.assign(p,!0).break()))}function _(y,k){let R=o[k];return typeof R=="object"&&R!==null?(0,bo._)`${d()}(${r}, ${y}[${k}])`:(0,bo._)`${r} === ${R}`}}};td.default=e0});var ey=U(rd=>{"use strict";Object.defineProperty(rd,"__esModule",{value:!0});var t0=zg(),r0=Bg(),n0=Kg(),o0=Vg(),s0=Gg(),i0=Wg(),a0=Jg(),l0=Xg(),c0=Zg(),d0=Qg(),u0=[t0.default,r0.default,n0.default,o0.default,s0.default,i0.default,a0.default,l0.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},c0.default,d0.default];rd.default=u0});var od=U(wo=>{"use strict";Object.defineProperty(wo,"__esModule",{value:!0});wo.validateAdditionalItems=void 0;var Er=re(),nd=ue(),p0={message:({params:{len:t}})=>(0,Er.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Er._)`{limit: ${t}}`},m0={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:p0,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,nd.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}ty(t,n)}};function ty(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Er._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Er._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,nd.alwaysValidSchema)(i,n)){let d=r.var("valid",(0,Er._)`${a} <= ${e.length}`);r.if((0,Er.not)(d),()=>l(d)),t.ok(d)}function l(d){r.forRange("i",e.length,a,p=>{t.subschema({keyword:s,dataProp:p,dataPropType:nd.Type.Num},d),i.allErrors||r.if((0,Er.not)(d),()=>r.break())})}}wo.validateAdditionalItems=ty;wo.default=m0});var sd=U(vo=>{"use strict";Object.defineProperty(vo,"__esModule",{value:!0});vo.validateTuple=void 0;var ry=re(),fi=ue(),h0=dt(),f0={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return ny(t,"additionalItems",e);r.items=!0,!(0,fi.alwaysValidSchema)(r,e)&&t.ok((0,h0.validateArray)(t))}};function ny(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;p(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=fi.mergeEvaluated.items(n,r.length,a.items));let l=n.name("valid"),d=n.const("len",(0,ry._)`${s}.length`);r.forEach((f,_)=>{(0,fi.alwaysValidSchema)(a,f)||(n.if((0,ry._)`${d} > ${_}`,()=>t.subschema({keyword:i,schemaProp:_,dataProp:_},l)),t.ok(l))});function p(f){let{opts:_,errSchemaPath:y}=a,k=r.length,R=k===f.minItems&&(k===f.maxItems||f[e]===!1);if(_.strictTuples&&!R){let $=`"${i}" is ${k}-tuple, but minItems or maxItems/${e} are not specified or different at path "${y}"`;(0,fi.checkStrictMode)(a,$,_.strictTuples)}}}vo.validateTuple=ny;vo.default=f0});var oy=U(id=>{"use strict";Object.defineProperty(id,"__esModule",{value:!0});var g0=sd(),y0={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,g0.validateTuple)(t,"items")};id.default=y0});var iy=U(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});var sy=re(),b0=ue(),w0=dt(),v0=od(),_0={message:({params:{len:t}})=>(0,sy.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,sy._)`{limit: ${t}}`},S0={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:_0,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,b0.alwaysValidSchema)(n,e)&&(o?(0,v0.validateAdditionalItems)(t,o):t.ok((0,w0.validateArray)(t)))}};ad.default=S0});var ay=U(ld=>{"use strict";Object.defineProperty(ld,"__esModule",{value:!0});var pt=re(),gi=ue(),k0={message:({params:{min:t,max:e}})=>e===void 0?(0,pt.str)`must contain at least ${t} valid item(s)`:(0,pt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,pt._)`{minContains: ${t}}`:(0,pt._)`{minContains: ${t}, maxContains: ${e}}`},T0={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:k0,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:l,maxContains:d}=n;s.opts.next?(i=l===void 0?1:l,a=d):i=1;let p=e.const("len",(0,pt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,gi.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,gi.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,gi.alwaysValidSchema)(s,r)){let R=(0,pt._)`${p} >= ${i}`;a!==void 0&&(R=(0,pt._)`${R} && ${p} <= ${a}`),t.pass(R);return}s.items=!0;let f=e.name("valid");a===void 0&&i===1?y(f,()=>e.if(f,()=>e.break())):i===0?(e.let(f,!0),a!==void 0&&e.if((0,pt._)`${o}.length > 0`,_)):(e.let(f,!1),_()),t.result(f,()=>t.reset());function _(){let R=e.name("_valid"),$=e.let("count",0);y(R,()=>e.if(R,()=>k($)))}function y(R,$){e.forRange("i",0,p,P=>{t.subschema({keyword:"contains",dataProp:P,dataPropType:gi.Type.Num,compositeRule:!0},R),$()})}function k(R){e.code((0,pt._)`${R}++`),a===void 0?e.if((0,pt._)`${R} >= ${i}`,()=>e.assign(f,!0).break()):(e.if((0,pt._)`${R} > ${a}`,()=>e.assign(f,!1).break()),i===1?e.assign(f,!0):e.if((0,pt._)`${R} >= ${i}`,()=>e.assign(f,!0)))}}};ld.default=T0});var dy=U(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.validateSchemaDeps=At.validatePropertyDeps=At.error=void 0;var cd=re(),x0=ue(),_o=dt();At.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,cd.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,cd._)`{property: ${t},
2010
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,te._)`[${o}]`)}}}function Kx({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,te._)`${e} !== undefined`,()=>t.assign((0,te._)`${e}[${r}]`,n))}function hc(t,e,r,n=en.Correct){let o=n===en.Correct?te.operators.EQ:te.operators.NEQ,s;switch(t){case"null":return(0,te._)`${e} ${o} null`;case"array":s=(0,te._)`Array.isArray(${e})`;break;case"object":s=(0,te._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,te._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,te._)`typeof ${e} ${o} ${t}`}return n===en.Correct?s:(0,te.not)(s);function i(a=te.nil){return(0,te.and)((0,te._)`typeof ${e} == "number"`,a,r?(0,te._)`isFinite(${e})`:te.nil)}}Be.checkDataType=hc;function mc(t,e,r,n){if(t.length===1)return hc(t[0],e,r,n);let o,s=(0,Ef.toHash)(t);if(s.array&&s.object){let i=(0,te._)`typeof ${e} != "object"`;o=s.null?i:(0,te._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=te.nil;s.number&&delete s.integer;for(let i in s)o=(0,te.and)(o,hc(i,e,r,n));return o}Be.checkDataTypes=mc;var Vx={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,te._)`{type: ${t}}`:(0,te._)`{type: ${e}}`};function fc(t){let e=Gx(t);(0,qx.reportError)(e,Vx)}Be.reportTypeError=fc;function Gx(t){let{gen:e,data:r,schema:n}=t,o=(0,Ef.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var If=U(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});Xs.assignDefaults=void 0;var tn=re(),Wx=ue();function Jx(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Cf(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Cf(t,s,o.default))}Xs.assignDefaults=Jx;function Cf(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,tn._)`${s}${(0,tn.getProperty)(e)}`;if(o){(0,Wx.checkStrictMode)(t,`default is ignored for: ${a}`);return}let l=(0,tn._)`${a} === undefined`;i.useDefaults==="empty"&&(l=(0,tn._)`${l} || ${a} === null || ${a} === ""`),n.if(l,(0,tn._)`${a} = ${(0,tn.stringify)(r)}`)}});var dt=U(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.validateUnion=be.validateArray=be.usePattern=be.callValidateCode=be.schemaProperties=be.allSchemaProperties=be.noPropertyInData=be.propertyInData=be.isOwnProperty=be.hasPropFunc=be.reportMissingProp=be.checkMissingProp=be.checkReportMissingProp=void 0;var _e=re(),gc=ue(),nr=Mt(),Yx=ue();function Xx(t,e){let{gen:r,data:n,it:o}=t;r.if(bc(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,_e._)`${e}`},!0),t.error()})}be.checkReportMissingProp=Xx;function Zx({gen:t,data:e,it:{opts:r}},n,o){return(0,_e.or)(...n.map(s=>(0,_e.and)(bc(t,e,s,r.ownProperties),(0,_e._)`${o} = ${s}`)))}be.checkMissingProp=Zx;function Qx(t,e){t.setParams({missingProperty:e},!0),t.error()}be.reportMissingProp=Qx;function Of(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,_e._)`Object.prototype.hasOwnProperty`})}be.hasPropFunc=Of;function yc(t,e,r){return(0,_e._)`${Of(t)}.call(${e}, ${r})`}be.isOwnProperty=yc;function eR(t,e,r,n){let o=(0,_e._)`${e}${(0,_e.getProperty)(r)} !== undefined`;return n?(0,_e._)`${o} && ${yc(t,e,r)}`:o}be.propertyInData=eR;function bc(t,e,r,n){let o=(0,_e._)`${e}${(0,_e.getProperty)(r)} === undefined`;return n?(0,_e.or)(o,(0,_e.not)(yc(t,e,r))):o}be.noPropertyInData=bc;function Nf(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}be.allSchemaProperties=Nf;function tR(t,e){return Nf(e).filter(r=>!(0,gc.alwaysValidSchema)(t,e[r]))}be.schemaProperties=tR;function rR({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,l,d){let p=d?(0,_e._)`${t}, ${e}, ${n}${o}`:e,f=[[nr.default.instancePath,(0,_e.strConcat)(nr.default.instancePath,s)],[nr.default.parentData,i.parentData],[nr.default.parentDataProperty,i.parentDataProperty],[nr.default.rootData,nr.default.rootData]];i.opts.dynamicRef&&f.push([nr.default.dynamicAnchors,nr.default.dynamicAnchors]);let _=(0,_e._)`${p}, ${r.object(...f)}`;return l!==_e.nil?(0,_e._)`${a}.call(${l}, ${_})`:(0,_e._)`${a}(${_})`}be.callValidateCode=rR;var nR=(0,_e._)`new RegExp`;function oR({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,_e._)`${o.code==="new RegExp"?nR:(0,Yx.useFunc)(t,o)}(${r}, ${n})`})}be.usePattern=oR;function sR(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,_e._)`${r}.length`);e.forRange("i",0,l,d=>{t.subschema({keyword:n,dataProp:d,dataPropType:gc.Type.Num},s),e.if((0,_e.not)(s),a)})}}be.validateArray=sR;function iR(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,gc.alwaysValidSchema)(o,l))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((l,d)=>{let p=t.subschema({keyword:n,schemaProp:d,compositeRule:!0},a);e.assign(i,(0,_e._)`${i} || ${a}`),t.mergeValidEvaluated(p,a)||e.if((0,_e.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}be.validateUnion=iR});var Df=U(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.validateKeywordUsage=Et.validSchemaType=Et.funcKeywordCode=Et.macroKeywordCode=void 0;var Ve=re(),kr=Mt(),aR=dt(),lR=to();function cR(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),l=jf(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let d=r.name("valid");t.subschema({schema:a,schemaPath:Ve.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},d),t.pass(d,()=>t.error(!0))}Et.macroKeywordCode=cR;function dR(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:l}=t;pR(l,e);let d=!a&&e.compile?e.compile.call(l.self,s,i,l):e.validate,p=jf(n,o,d),f=n.let("valid");t.block$data(f,_),t.ok((r=e.valid)!==null&&r!==void 0?r:f);function _(){if(e.errors===!1)R(),e.modifying&&Lf(t),$(()=>t.error());else{let P=e.async?y():k();e.modifying&&Lf(t),$(()=>uR(t,P))}}function y(){let P=n.let("ruleErrs",null);return n.try(()=>R((0,Ve._)`await `),I=>n.assign(f,!1).if((0,Ve._)`${I} instanceof ${l.ValidationError}`,()=>n.assign(P,(0,Ve._)`${I}.errors`),()=>n.throw(I))),P}function k(){let P=(0,Ve._)`${p}.errors`;return n.assign(P,null),R(Ve.nil),P}function R(P=e.async?(0,Ve._)`await `:Ve.nil){let I=l.opts.passContext?kr.default.this:kr.default.self,D=!("compile"in e&&!a||e.schema===!1);n.assign(f,(0,Ve._)`${P}${(0,aR.callValidateCode)(t,p,I,D)}`,e.modifying)}function $(P){var I;n.if((0,Ve.not)((I=e.valid)!==null&&I!==void 0?I:f),P)}}Et.funcKeywordCode=dR;function Lf(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Ve._)`${n.parentData}[${n.parentDataProperty}]`))}function uR(t,e){let{gen:r}=t;r.if((0,Ve._)`Array.isArray(${e})`,()=>{r.assign(kr.default.vErrors,(0,Ve._)`${kr.default.vErrors} === null ? ${e} : ${kr.default.vErrors}.concat(${e})`).assign(kr.default.errors,(0,Ve._)`${kr.default.vErrors}.length`),(0,lR.extendErrors)(t)},()=>t.error())}function pR({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function jf(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,Ve.stringify)(r)})}function hR(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")}Et.validSchemaType=hR;function mR({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)}}Et.validateKeywordUsage=mR});var Mf=U(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.extendSubschemaMode=or.extendSubschemaData=or.getSubschema=void 0;var Pt=re(),Uf=ue();function fR(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,Pt._)`${t.schemaPath}${(0,Pt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Pt._)`${t.schemaPath}${(0,Pt.getProperty)(e)}${(0,Pt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Uf.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')}or.getSubschema=fR;function gR(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:d,dataPathArr:p,opts:f}=e,_=a.let("data",(0,Pt._)`${e.data}${(0,Pt.getProperty)(r)}`,!0);l(_),t.errorPath=(0,Pt.str)`${d}${(0,Uf.getErrorPath)(r,n,f.jsPropertySyntax)}`,t.parentDataProperty=(0,Pt._)`${r}`,t.dataPathArr=[...p,t.parentDataProperty]}if(o!==void 0){let d=o instanceof Pt.Name?o:a.let("data",o,!0);l(d),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function l(d){t.data=d,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,d]}}or.extendSubschemaData=gR;function yR(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}or.extendSubschemaMode=yR});var wc=U((WD,qf)=>{"use strict";qf.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 Bf=U((JD,zf)=>{"use strict";var sr=zf.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(){};Zs(e,n,o,t,"",t)};sr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};sr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};sr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};sr.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 Zs(t,e,r,n,o,s,i,a,l,d){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,l,d);for(var p in n){var f=n[p];if(Array.isArray(f)){if(p in sr.arrayKeywords)for(var _=0;_<f.length;_++)Zs(t,e,r,f[_],o+"/"+p+"/"+_,s,o,p,n,_)}else if(p in sr.propsKeywords){if(f&&typeof f=="object")for(var y in f)Zs(t,e,r,f[y],o+"/"+p+"/"+bR(y),s,o,p,n,y)}else(p in sr.keywords||t.allKeys&&!(p in sr.skipKeywords))&&Zs(t,e,r,f,o+"/"+p,s,o,p,n)}r(n,o,s,i,a,l,d)}}function bR(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var no=U(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.getSchemaRefs=Ze.resolveUrl=Ze.normalizeId=Ze._getFullPath=Ze.getFullPath=Ze.inlineRef=void 0;var wR=ue(),vR=wc(),_R=Bf(),SR=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function kR(t,e=!0){return typeof t=="boolean"?!0:e===!0?!vc(t):e?Ff(t)<=e:!1}Ze.inlineRef=kR;var TR=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function vc(t){for(let e in t){if(TR.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(vc)||typeof r=="object"&&vc(r))return!0}return!1}function Ff(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!SR.has(r)&&(typeof t[r]=="object"&&(0,wR.eachItem)(t[r],n=>e+=Ff(n)),e===1/0))return 1/0}return e}function Hf(t,e="",r){r!==!1&&(e=rn(e));let n=t.parse(e);return Kf(t,n)}Ze.getFullPath=Hf;function Kf(t,e){return t.serialize(e).split("#")[0]+"#"}Ze._getFullPath=Kf;var xR=/#\/?$/;function rn(t){return t?t.replace(xR,""):""}Ze.normalizeId=rn;function RR(t,e,r){return r=rn(r),t.resolve(e,r)}Ze.resolveUrl=RR;var $R=/^[a-z_][-a-z0-9._]*$/i;function ER(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=rn(t[r]||e),s={"":o},i=Hf(n,o,!1),a={},l=new Set;return _R(t,{allKeys:!0},(f,_,y,k)=>{if(k===void 0)return;let R=i+_,$=s[k];typeof f[r]=="string"&&($=P.call(this,f[r])),I.call(this,f.$anchor),I.call(this,f.$dynamicAnchor),s[_]=$;function P(D){let Y=this.opts.uriResolver.resolve;if(D=rn($?Y($,D):D),l.has(D))throw p(D);l.add(D);let F=this.refs[D];return typeof F=="string"&&(F=this.refs[F]),typeof F=="object"?d(f,F.schema,D):D!==rn(R)&&(D[0]==="#"?(d(f,a[D],D),a[D]=f):this.refs[D]=R),D}function I(D){if(typeof D=="string"){if(!$R.test(D))throw new Error(`invalid anchor "${D}"`);P.call(this,`#${D}`)}}}),a;function d(f,_,y){if(_!==void 0&&!vR(f,_))throw p(y)}function p(f){return new Error(`reference "${f}" resolves to more than one schema`)}}Ze.getSchemaRefs=ER});var io=U(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.getData=ir.KeywordCxt=ir.validateFunctionCode=void 0;var Yf=xf(),Vf=ro(),Sc=pc(),Qs=ro(),PR=If(),so=Df(),_c=Mf(),B=re(),ee=Mt(),AR=no(),qt=ue(),oo=to();function CR(t){if(Qf(t)&&(eg(t),Zf(t))){NR(t);return}Xf(t,()=>(0,Yf.topBoolOrEmptySchema)(t))}ir.validateFunctionCode=CR;function Xf({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,B._)`${ee.default.data}, ${ee.default.valCxt}`,n.$async,()=>{t.code((0,B._)`"use strict"; ${Gf(r,o)}`),OR(t,o),t.code(s)}):t.func(e,(0,B._)`${ee.default.data}, ${IR(o)}`,n.$async,()=>t.code(Gf(r,o)).code(s))}function IR(t){return(0,B._)`{${ee.default.instancePath}="", ${ee.default.parentData}, ${ee.default.parentDataProperty}, ${ee.default.rootData}=${ee.default.data}${t.dynamicRef?(0,B._)`, ${ee.default.dynamicAnchors}={}`:B.nil}}={}`}function OR(t,e){t.if(ee.default.valCxt,()=>{t.var(ee.default.instancePath,(0,B._)`${ee.default.valCxt}.${ee.default.instancePath}`),t.var(ee.default.parentData,(0,B._)`${ee.default.valCxt}.${ee.default.parentData}`),t.var(ee.default.parentDataProperty,(0,B._)`${ee.default.valCxt}.${ee.default.parentDataProperty}`),t.var(ee.default.rootData,(0,B._)`${ee.default.valCxt}.${ee.default.rootData}`),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,B._)`${ee.default.valCxt}.${ee.default.dynamicAnchors}`)},()=>{t.var(ee.default.instancePath,(0,B._)`""`),t.var(ee.default.parentData,(0,B._)`undefined`),t.var(ee.default.parentDataProperty,(0,B._)`undefined`),t.var(ee.default.rootData,ee.default.data),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,B._)`{}`)})}function NR(t){let{schema:e,opts:r,gen:n}=t;Xf(t,()=>{r.$comment&&e.$comment&&rg(t),MR(t),n.let(ee.default.vErrors,null),n.let(ee.default.errors,0),r.unevaluated&&LR(t),tg(t),BR(t)})}function LR(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,B._)`${r}.evaluated`),e.if((0,B._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,B._)`${t.evaluated}.props`,(0,B._)`undefined`)),e.if((0,B._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,B._)`${t.evaluated}.items`,(0,B._)`undefined`))}function Gf(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,B._)`/*# sourceURL=${r} */`:B.nil}function jR(t,e){if(Qf(t)&&(eg(t),Zf(t))){DR(t,e);return}(0,Yf.boolOrEmptySchema)(t,e)}function Zf({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 Qf(t){return typeof t.schema!="boolean"}function DR(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&rg(t),qR(t),zR(t);let s=n.const("_errs",ee.default.errors);tg(t,s),n.var(e,(0,B._)`${s} === ${ee.default.errors}`)}function eg(t){(0,qt.checkUnknownRules)(t),UR(t)}function tg(t,e){if(t.opts.jtd)return Wf(t,[],!1,e);let r=(0,Vf.getSchemaTypes)(t.schema),n=(0,Vf.coerceAndCheckDataType)(t,r);Wf(t,r,!n,e)}function UR(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,qt.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function MR(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,qt.checkStrictMode)(t,"default is ignored in the schema root")}function qR(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,AR.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function zR(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function rg({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,B._)`${ee.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,B.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,B._)`${ee.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function BR(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,B._)`${ee.default.errors} === 0`,()=>e.return(ee.default.data),()=>e.throw((0,B._)`new ${o}(${ee.default.vErrors})`)):(e.assign((0,B._)`${n}.errors`,ee.default.vErrors),s.unevaluated&&FR(t),e.return((0,B._)`${ee.default.errors} === 0`))}function FR({gen:t,evaluated:e,props:r,items:n}){r instanceof B.Name&&t.assign((0,B._)`${e}.props`,r),n instanceof B.Name&&t.assign((0,B._)`${e}.items`,n)}function Wf(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:l,self:d}=t,{RULES:p}=d;if(s.$ref&&(l.ignoreKeywordsWithRef||!(0,qt.schemaHasRulesButRef)(s,p))){o.block(()=>og(t,"$ref",p.all.$ref.definition));return}l.jtd||HR(t,e),o.block(()=>{for(let _ of p.rules)f(_);f(p.post)});function f(_){(0,Sc.shouldUseGroup)(s,_)&&(_.type?(o.if((0,Qs.checkDataType)(_.type,i,l.strictNumbers)),Jf(t,_),e.length===1&&e[0]===_.type&&r&&(o.else(),(0,Qs.reportTypeError)(t)),o.endIf()):Jf(t,_),a||o.if((0,B._)`${ee.default.errors} === ${n||0}`))}}function Jf(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,PR.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Sc.shouldUseRule)(n,s)&&og(t,s.keyword,s.definition,e.type)})}function HR(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(KR(t,e),t.opts.allowUnionTypes||VR(t,e),GR(t,t.dataTypes))}function KR(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{ng(t.dataTypes,r)||kc(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),JR(t,e)}}function VR(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&kc(t,"use allowUnionTypes to allow union type keyword")}function GR(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Sc.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>WR(e,i))&&kc(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function WR(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function ng(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function JR(t,e){let r=[];for(let n of t.dataTypes)ng(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function kc(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,qt.checkStrictMode)(t,e,t.opts.strictTypes)}var ei=class{constructor(e,r,n){if((0,so.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,qt.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",sg(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,so.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",ee.default.errors))}result(e,r,n){this.failResult((0,B.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,B.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,B._)`${r} !== undefined && (${(0,B.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?oo.reportExtraError:oo.reportError)(this,this.def.error,r)}$dataError(){(0,oo.reportError)(this,this.def.$dataError||oo.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,oo.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=B.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=B.nil,r=B.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,B.or)((0,B._)`${o} === undefined`,r)),e!==B.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==B.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,B.or)(i(),a());function i(){if(n.length){if(!(r instanceof B.Name))throw new Error("ajv implementation error");let l=Array.isArray(n)?n:[n];return(0,B._)`${(0,Qs.checkDataTypes)(l,r,s.opts.strictNumbers,Qs.DataType.Wrong)}`}return B.nil}function a(){if(o.validateSchema){let l=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,B._)`!${l}(${r})`}return B.nil}}subschema(e,r){let n=(0,_c.getSubschema)(this.it,e);(0,_c.extendSubschemaData)(n,this.it,e),(0,_c.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return jR(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=qt.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=qt.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,B.Name)),!0}};ir.KeywordCxt=ei;function og(t,e,r,n){let o=new ei(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,so.funcKeywordCode)(o,r):"macro"in r?(0,so.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,so.funcKeywordCode)(o,r)}var YR=/^\/(?:[^~]|~0|~1)*$/,XR=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function sg(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return ee.default.rootData;if(t[0]==="/"){if(!YR.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ee.default.rootData}else{let d=XR.exec(t);if(!d)throw new Error(`Invalid JSON-pointer: ${t}`);let p=+d[1];if(o=d[2],o==="#"){if(p>=e)throw new Error(l("property/index",p));return n[e-p]}if(p>e)throw new Error(l("data",p));if(s=r[e-p],!o)return s}let i=s,a=o.split("/");for(let d of a)d&&(s=(0,B._)`${s}${(0,B.getProperty)((0,qt.unescapeJsonPointer)(d))}`,i=(0,B._)`${i} && ${s}`);return i;function l(d,p){return`Cannot access ${d} ${p} levels up, current level is ${e}`}}ir.getData=sg});var ti=U(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var Tc=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};xc.default=Tc});var ao=U(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var Rc=no(),$c=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Rc.resolveUrl)(e,r,n),this.missingSchema=(0,Rc.normalizeId)((0,Rc.getFullPath)(e,this.missingRef))}};Ec.default=$c});var ni=U(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.resolveSchema=ut.getCompilingSchema=ut.resolveRef=ut.compileSchema=ut.SchemaEnv=void 0;var vt=re(),ZR=ti(),Tr=Mt(),_t=no(),ig=ue(),QR=io(),nn=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,_t.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};ut.SchemaEnv=nn;function Ac(t){let e=ag.call(this,t);if(e)return e;let r=(0,_t.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new vt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:ZR.default,code:(0,vt._)`require("ajv/dist/runtime/validation_error").default`}));let l=i.scopeName("validate");t.validateName=l;let d={gen:i,allErrors:this.opts.allErrors,data:Tr.default.data,parentData:Tr.default.parentData,parentDataProperty:Tr.default.parentDataProperty,dataNames:[Tr.default.data],dataPathArr:[vt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,vt.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:vt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,vt._)`""`,opts:this.opts,self:this},p;try{this._compilations.add(t),(0,QR.validateFunctionCode)(d),i.optimize(this.opts.code.optimize);let f=i.toString();p=`${i.scopeRefs(Tr.default.scope)}return ${f}`,this.opts.code.process&&(p=this.opts.code.process(p,t));let y=new Function(`${Tr.default.self}`,`${Tr.default.scope}`,p)(this,this.scope.get());if(this.scope.value(l,{ref:y}),y.errors=null,y.schema=t.schema,y.schemaEnv=t,t.$async&&(y.$async=!0),this.opts.code.source===!0&&(y.source={validateName:l,validateCode:f,scopeValues:i._values}),this.opts.unevaluated){let{props:k,items:R}=d;y.evaluated={props:k instanceof vt.Name?void 0:k,items:R instanceof vt.Name?void 0:R,dynamicProps:k instanceof vt.Name,dynamicItems:R instanceof vt.Name},y.source&&(y.source.evaluated=(0,vt.stringify)(y.evaluated))}return t.validate=y,t}catch(f){throw delete t.validate,delete t.validateName,p&&this.logger.error("Error compiling schema, function code:",p),f}finally{this._compilations.delete(t)}}ut.compileSchema=Ac;function e$(t,e,r){var n;r=(0,_t.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=n$.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 nn({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=t$.call(this,s)}ut.resolveRef=e$;function t$(t){return(0,_t.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Ac.call(this,t)}function ag(t){for(let e of this._compilations)if(r$(e,t))return e}ut.getCompilingSchema=ag;function r$(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function n$(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||ri.call(this,t,e)}function ri(t,e){let r=this.opts.uriResolver.parse(e),n=(0,_t._getFullPath)(this.opts.uriResolver,r),o=(0,_t.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Pc.call(this,r,t);let s=(0,_t.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=ri.call(this,t,i);return typeof a?.schema!="object"?void 0:Pc.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Ac.call(this,i),s===(0,_t.normalizeId)(e)){let{schema:a}=i,{schemaId:l}=this.opts,d=a[l];return d&&(o=(0,_t.resolveUrl)(this.opts.uriResolver,o,d)),new nn({schema:a,schemaId:l,root:t,baseId:o})}return Pc.call(this,r,i)}}ut.resolveSchema=ri;var o$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Pc(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,ig.unescapeFragment)(a)];if(l===void 0)return;r=l;let d=typeof r=="object"&&r[this.opts.schemaId];!o$.has(a)&&d&&(e=(0,_t.resolveUrl)(this.opts.uriResolver,e,d))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,ig.schemaHasRulesButRef)(r,this.RULES)){let a=(0,_t.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=ri.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new nn({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var lg=U((t1,s$)=>{s$.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 Oc=U((r1,mg)=>{"use strict";var i$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),dg=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),Cc=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),ug=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),a$=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Ic(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 l$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function cg(t){return t.length=0,!0}function c$(t,e,r){if(t.length){let n=Ic(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function d$(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=c$;for(let l=0;l<t.length;l++){let d=t[l];if(!(d==="["||d==="]"))if(d===":"){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(d==="%"){if(!a(o,n,r))break;a=cg}else{o.push(d);continue}}return o.length&&(a===cg?r.zone=o.join(""):i?n.push(o.join("")):n.push(Ic(o))),r.address=n.join(""),r}function pg(t){if(u$(t,":")<2)return{host:t,isIPV6:!1};let e=d$(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 u$(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function p$(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 h$={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},m$=/[@/?#:]/g,f$=/[@/?#]/g;function hg(t,e){let r=e?f$:m$;return r.lastIndex=0,t.replace(r,n=>h$[n])}function g$(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(Cc(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&ug(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function y$(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(Cc(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&ug(s)?e+=s:e+="%"+o,r+=2;continue}}a$(t[r])?e+=t[r]:e+=escape(t[r])}return e}function b$(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(Cc(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function w$(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!dg(r)){let n=pg(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=hg(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}mg.exports={nonSimpleDomain:l$,recomposeAuthority:w$,reescapeHostDelimiters:hg,normalizePercentEncoding:g$,normalizePathEncoding:y$,escapePreservingEscapes:b$,removeDotSegments:p$,isIPv4:dg,isUUID:i$,normalizeIPv6:pg,stringArrayToHexStripped:Ic}});var wg=U((n1,bg)=>{"use strict";var{isUUID:v$}=Oc(),_$=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,S$=["http","https","ws","wss","urn","urn:uuid"];function k$(t){return S$.indexOf(t)!==-1}function Nc(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 fg(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function gg(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 T$(t){return t.secure=Nc(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function x$(t){if((t.port===(Nc(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 R$(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(_$);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=Lc(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function $$(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=Lc(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 E$(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!v$(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function P$(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var yg={scheme:"http",domainHost:!0,parse:fg,serialize:gg},A$={scheme:"https",domainHost:yg.domainHost,parse:fg,serialize:gg},oi={scheme:"ws",domainHost:!0,parse:T$,serialize:x$},C$={scheme:"wss",domainHost:oi.domainHost,parse:oi.parse,serialize:oi.serialize},I$={scheme:"urn",parse:R$,serialize:$$,skipNormalize:!0},O$={scheme:"urn:uuid",parse:E$,serialize:P$,skipNormalize:!0},si={http:yg,https:A$,ws:oi,wss:C$,urn:I$,"urn:uuid":O$};Object.setPrototypeOf(si,null);function Lc(t){return t&&(si[t]||si[t.toLowerCase()])||void 0}bg.exports={wsIsSecure:Nc,SCHEMES:si,isValidSchemeName:k$,getSchemeHandler:Lc}});var Tg=U((o1,li)=>{"use strict";var{normalizeIPv6:N$,removeDotSegments:lo,recomposeAuthority:L$,normalizePercentEncoding:j$,normalizePathEncoding:D$,escapePreservingEscapes:U$,reescapeHostDelimiters:M$,isIPv4:q$,nonSimpleDomain:z$}=Oc(),{SCHEMES:B$,getSchemeHandler:_g}=wg();function F$(t,e){return typeof t=="string"?t=Y$(t,e):typeof t=="object"&&(t=ai(xr(t,e),e)),t}function H$(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=ii(t,n),{parsed:i,malformedAuthorityOrPort:a}=ii(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let l=Sg(o,i,n,!0);return n.skipEscape=!0,xr(l,n)}function Sg(t,e,r,n){let o={};return n||(t=ai(xr(t,r),r),e=ai(xr(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=lo(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=lo(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=lo(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=lo(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 K$(t,e,r){let n=vg(t,r),o=vg(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function xr(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=_g(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=j$(r.path):(r.path=U$(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=L$(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=lo(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 V$=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,G$=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,W$=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function J$(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 ii(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(G$);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(W$);if(a!==null){let d=a[1],p=d.replace(/[\t\n\r]/g,"");p.length>=2&&(p.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):d.length!==p.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let l=t.match(V$);if(l){n.scheme=l[1],n.userinfo=l[3],n.host=l[4],n.port=parseInt(l[5],10),n.path=l[6]||"",n.query=l[7],n.fragment=l[8],isNaN(n.port)&&(n.port=l[5]);let d=J$(n,l);if(d!==void 0&&(n.error=n.error||d,o=!0),n.host)if(q$(n.host)===!1){let _=N$(n.host);n.host=_.host.toLowerCase(),s=_.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=_g(r.scheme||n.scheme);if(!r.unicodeSupport&&(!p||!p.unicodeSupport)&&n.host&&(r.domainHost||p&&p.domainHost)&&s===!1&&z$(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(f){n.error=n.error||"Host's domain name can not be converted to ASCII: "+f}if((!p||p&&!p.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=M$(unescape(n.host),s))),n.path&&(n.path=D$(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 ai(t,e){return ii(t,e).parsed}function Y$(t,e){return kg(t,e).normalized}function kg(t,e){let{parsed:r,malformedAuthorityOrPort:n}=ii(t,e);return{normalized:n?t:xr(r,e),malformedAuthorityOrPort:n}}function vg(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=kg(t,e);return n?void 0:r}if(typeof t=="object")return xr(t,e)}var jc={SCHEMES:B$,normalize:F$,resolve:H$,resolveComponent:Sg,equal:K$,serialize:xr,parse:ai};li.exports=jc;li.exports.default=jc;li.exports.fastUri=jc});var Rg=U(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});var xg=Tg();xg.code='require("ajv/dist/runtime/uri").default';Dc.default=xg});var Ng=U(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.CodeGen=Ue.Name=Ue.nil=Ue.stringify=Ue.str=Ue._=Ue.KeywordCxt=void 0;var X$=io();Object.defineProperty(Ue,"KeywordCxt",{enumerable:!0,get:function(){return X$.KeywordCxt}});var on=re();Object.defineProperty(Ue,"_",{enumerable:!0,get:function(){return on._}});Object.defineProperty(Ue,"str",{enumerable:!0,get:function(){return on.str}});Object.defineProperty(Ue,"stringify",{enumerable:!0,get:function(){return on.stringify}});Object.defineProperty(Ue,"nil",{enumerable:!0,get:function(){return on.nil}});Object.defineProperty(Ue,"Name",{enumerable:!0,get:function(){return on.Name}});Object.defineProperty(Ue,"CodeGen",{enumerable:!0,get:function(){return on.CodeGen}});var Z$=ti(),Cg=ao(),Q$=uc(),co=ni(),eE=re(),uo=no(),ci=ro(),Mc=ue(),$g=lg(),tE=Rg(),Ig=(t,e)=>new RegExp(t,e);Ig.code="new RegExp";var rE=["removeAdditional","useDefaults","coerceTypes"],nE=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),oE={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."},sE={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Eg=200;function iE(t){var e,r,n,o,s,i,a,l,d,p,f,_,y,k,R,$,P,I,D,Y,F,Oe,Ce,Bt,Ft;let Ht=t.strict,mn=(e=t.code)===null||e===void 0?void 0:e.optimize,dr=mn===!0||mn===void 0?1:mn||0,Tt=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Ig,Li=(o=t.uriResolver)!==null&&o!==void 0?o:tE.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Ht)!==null&&i!==void 0?i:!0,strictNumbers:(l=(a=t.strictNumbers)!==null&&a!==void 0?a:Ht)!==null&&l!==void 0?l:!0,strictTypes:(p=(d=t.strictTypes)!==null&&d!==void 0?d:Ht)!==null&&p!==void 0?p:"log",strictTuples:(_=(f=t.strictTuples)!==null&&f!==void 0?f:Ht)!==null&&_!==void 0?_:"log",strictRequired:(k=(y=t.strictRequired)!==null&&y!==void 0?y:Ht)!==null&&k!==void 0?k:!1,code:t.code?{...t.code,optimize:dr,regExp:Tt}:{optimize:dr,regExp:Tt},loopRequired:(R=t.loopRequired)!==null&&R!==void 0?R:Eg,loopEnum:($=t.loopEnum)!==null&&$!==void 0?$:Eg,meta:(P=t.meta)!==null&&P!==void 0?P:!0,messages:(I=t.messages)!==null&&I!==void 0?I:!0,inlineRefs:(D=t.inlineRefs)!==null&&D!==void 0?D:!0,schemaId:(Y=t.schemaId)!==null&&Y!==void 0?Y:"$id",addUsedSchema:(F=t.addUsedSchema)!==null&&F!==void 0?F:!0,validateSchema:(Oe=t.validateSchema)!==null&&Oe!==void 0?Oe:!0,validateFormats:(Ce=t.validateFormats)!==null&&Ce!==void 0?Ce:!0,unicodeRegExp:(Bt=t.unicodeRegExp)!==null&&Bt!==void 0?Bt:!0,int32range:(Ft=t.int32range)!==null&&Ft!==void 0?Ft:!0,uriResolver:Li}}var po=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,...iE(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new eE.ValueScope({scope:{},prefixes:nE,es5:r,lines:n}),this.logger=pE(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Q$.getRules)(),Pg.call(this,oE,e,"NOT SUPPORTED"),Pg.call(this,sE,e,"DEPRECATED","warn"),this._metaOpts=dE.call(this),e.formats&&lE.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&cE.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),aE.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=$g;n==="id"&&(o={...$g},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(p,f){await s.call(this,p.$schema);let _=this._addSchema(p,f);return _.validate||i.call(this,_)}async function s(p){p&&!this.getSchema(p)&&await o.call(this,{$ref:p},!0)}async function i(p){try{return this._compileSchemaEnv(p)}catch(f){if(!(f instanceof Cg.default))throw f;return a.call(this,f),await l.call(this,f.missingSchema),i.call(this,p)}}function a({missingSchema:p,missingRef:f}){if(this.refs[p])throw new Error(`AnySchema ${p} is loaded but ${f} cannot be resolved`)}async function l(p){let f=await d.call(this,p);this.refs[p]||await s.call(this,f.$schema),this.refs[p]||this.addSchema(f,p,r)}async function d(p){let f=this._loading[p];if(f)return f;try{return await(this._loading[p]=n(p))}finally{delete this._loading[p]}}}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,uo.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=Ag.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new co.SchemaEnv({schema:{},schemaId:n});if(r=co.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=Ag.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,uo.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(mE.call(this,n,r),!r)return(0,Mc.eachItem)(n,s=>Uc.call(this,s)),this;gE.call(this,r);let o={...r,type:(0,ci.getJSONTypes)(r.type),schemaType:(0,ci.getJSONTypes)(r.schemaType)};return(0,Mc.eachItem)(n,o.type.length===0?s=>Uc.call(this,s,o):s=>o.type.forEach(i=>Uc.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:d}=l.definition,p=i[a];d&&p&&(i[a]=Og(p))}}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,uo.normalizeId)(i||n);let d=uo.getSchemaRefs.call(this,e,n);return l=new co.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:d}),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):co.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{co.compileSchema.call(this,e)}finally{this.opts=r}}};po.ValidationError=Z$.default;po.MissingRefError=Cg.default;Ue.default=po;function Pg(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 Ag(t){return t=(0,uo.normalizeId)(t),this.schemas[t]||this.refs[t]}function aE(){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 lE(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function cE(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 dE(){let t={...this.opts};for(let e of rE)delete t[e];return t}var uE={log(){},warn(){},error(){}};function pE(t){if(t===!1)return uE;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 hE=/^[a-z_$][a-z0-9_$:-]*$/i;function mE(t,e){let{RULES:r}=this;if((0,Mc.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!hE.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 Uc(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,ci.getJSONTypes)(e.type),schemaType:(0,ci.getJSONTypes)(e.schemaType)}};e.before?fE.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 fE(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 gE(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Og(e)),t.validateSchema=this.compile(e,!0))}var yE={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Og(t){return{anyOf:[t,yE]}}});var Lg=U(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var bE={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};qc.default=bE});var Mg=U(Rr=>{"use strict";Object.defineProperty(Rr,"__esModule",{value:!0});Rr.callRef=Rr.getValidate=void 0;var wE=ao(),jg=dt(),Qe=re(),sn=Mt(),Dg=ni(),di=ue(),vE={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:d}=s;if((r==="#"||r==="#/")&&o===d.baseId)return f();let p=Dg.resolveRef.call(l,d,o,r);if(p===void 0)throw new wE.default(n.opts.uriResolver,o,r);if(p instanceof Dg.SchemaEnv)return _(p);return y(p);function f(){if(s===d)return ui(t,i,s,s.$async);let k=e.scopeValue("root",{ref:d});return ui(t,(0,Qe._)`${k}.validate`,d,d.$async)}function _(k){let R=Ug(t,k);ui(t,R,k,k.$async)}function y(k){let R=e.scopeValue("schema",a.code.source===!0?{ref:k,code:(0,Qe.stringify)(k)}:{ref:k}),$=e.name("valid"),P=t.subschema({schema:k,dataTypes:[],schemaPath:Qe.nil,topSchemaRef:R,errSchemaPath:r},$);t.mergeEvaluated(P),t.ok($)}}};function Ug(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Qe._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Rr.getValidate=Ug;function ui(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:l}=s,d=l.passContext?sn.default.this:Qe.nil;n?p():f();function p(){if(!a.$async)throw new Error("async schema referenced by sync schema");let k=o.let("valid");o.try(()=>{o.code((0,Qe._)`await ${(0,jg.callValidateCode)(t,e,d)}`),y(e),i||o.assign(k,!0)},R=>{o.if((0,Qe._)`!(${R} instanceof ${s.ValidationError})`,()=>o.throw(R)),_(R),i||o.assign(k,!1)}),t.ok(k)}function f(){t.result((0,jg.callValidateCode)(t,e,d),()=>y(e),()=>_(e))}function _(k){let R=(0,Qe._)`${k}.errors`;o.assign(sn.default.vErrors,(0,Qe._)`${sn.default.vErrors} === null ? ${R} : ${sn.default.vErrors}.concat(${R})`),o.assign(sn.default.errors,(0,Qe._)`${sn.default.vErrors}.length`)}function y(k){var R;if(!s.opts.unevaluated)return;let $=(R=r?.validate)===null||R===void 0?void 0:R.evaluated;if(s.props!==!0)if($&&!$.dynamicProps)$.props!==void 0&&(s.props=di.mergeEvaluated.props(o,$.props,s.props));else{let P=o.var("props",(0,Qe._)`${k}.evaluated.props`);s.props=di.mergeEvaluated.props(o,P,s.props,Qe.Name)}if(s.items!==!0)if($&&!$.dynamicItems)$.items!==void 0&&(s.items=di.mergeEvaluated.items(o,$.items,s.items));else{let P=o.var("items",(0,Qe._)`${k}.evaluated.items`);s.items=di.mergeEvaluated.items(o,P,s.items,Qe.Name)}}}Rr.callRef=ui;Rr.default=vE});var qg=U(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var _E=Lg(),SE=Mg(),kE=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",_E.default,SE.default];zc.default=kE});var zg=U(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var pi=re(),ar=pi.operators,hi={maximum:{okStr:"<=",ok:ar.LTE,fail:ar.GT},minimum:{okStr:">=",ok:ar.GTE,fail:ar.LT},exclusiveMaximum:{okStr:"<",ok:ar.LT,fail:ar.GTE},exclusiveMinimum:{okStr:">",ok:ar.GT,fail:ar.LTE}},TE={message:({keyword:t,schemaCode:e})=>(0,pi.str)`must be ${hi[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,pi._)`{comparison: ${hi[t].okStr}, limit: ${e}}`},xE={keyword:Object.keys(hi),type:"number",schemaType:"number",$data:!0,error:TE,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,pi._)`${r} ${hi[e].fail} ${n} || isNaN(${r})`)}};Bc.default=xE});var Bg=U(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});var ho=re(),RE={message:({schemaCode:t})=>(0,ho.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ho._)`{multipleOf: ${t}}`},$E={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:RE,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,ho._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,ho._)`${i} !== parseInt(${i})`;t.fail$data((0,ho._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Fc.default=$E});var Hg=U(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});function Fg(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}Hc.default=Fg;Fg.code='require("ajv/dist/runtime/ucs2length").default'});var Kg=U(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});var $r=re(),EE=ue(),PE=Hg(),AE={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,$r.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,$r._)`{limit: ${t}}`},CE={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:AE,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?$r.operators.GT:$r.operators.LT,i=o.opts.unicode===!1?(0,$r._)`${r}.length`:(0,$r._)`${(0,EE.useFunc)(t.gen,PE.default)}(${r})`;t.fail$data((0,$r._)`${i} ${s} ${n}`)}};Kc.default=CE});var Vg=U(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});var IE=dt(),OE=ue(),an=re(),NE={message:({schemaCode:t})=>(0,an.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,an._)`{pattern: ${t}}`},LE={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:NE,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,d=l.code==="new RegExp"?(0,an._)`new RegExp`:(0,OE.useFunc)(e,l),p=e.let("valid");e.try(()=>e.assign(p,(0,an._)`${d}(${s}, ${a}).test(${r})`),()=>e.assign(p,!1)),t.fail$data((0,an._)`!${p}`)}else{let l=(0,IE.usePattern)(t,o);t.fail$data((0,an._)`!${l}.test(${r})`)}}};Vc.default=LE});var Gg=U(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var mo=re(),jE={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,mo.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,mo._)`{limit: ${t}}`},DE={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:jE,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?mo.operators.GT:mo.operators.LT;t.fail$data((0,mo._)`Object.keys(${r}).length ${o} ${n}`)}};Gc.default=DE});var Wg=U(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var fo=dt(),go=re(),UE=ue(),ME={message:({params:{missingProperty:t}})=>(0,go.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,go._)`{missingProperty: ${t}}`},qE={keyword:"required",type:"object",schemaType:"array",$data:!0,error:ME,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?d():p(),a.strictRequired){let y=t.parentSchema.properties,{definedProperties:k}=t.it;for(let R of r)if(y?.[R]===void 0&&!k.has(R)){let $=i.schemaEnv.baseId+i.errSchemaPath,P=`required property "${R}" is not defined at "${$}" (strictRequired)`;(0,UE.checkStrictMode)(i,P,i.opts.strictRequired)}}function d(){if(l||s)t.block$data(go.nil,f);else for(let y of r)(0,fo.checkReportMissingProp)(t,y)}function p(){let y=e.let("missing");if(l||s){let k=e.let("valid",!0);t.block$data(k,()=>_(y,k)),t.ok(k)}else e.if((0,fo.checkMissingProp)(t,r,y)),(0,fo.reportMissingProp)(t,y),e.else()}function f(){e.forOf("prop",n,y=>{t.setParams({missingProperty:y}),e.if((0,fo.noPropertyInData)(e,o,y,a.ownProperties),()=>t.error())})}function _(y,k){t.setParams({missingProperty:y}),e.forOf(y,n,()=>{e.assign(k,(0,fo.propertyInData)(e,o,y,a.ownProperties)),e.if((0,go.not)(k),()=>{t.error(),e.break()})},go.nil)}}};Wc.default=qE});var Jg=U(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});var yo=re(),zE={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,yo.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,yo._)`{limit: ${t}}`},BE={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:zE,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?yo.operators.GT:yo.operators.LT;t.fail$data((0,yo._)`${r}.length ${o} ${n}`)}};Jc.default=BE});var mi=U(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});var Yg=wc();Yg.code='require("ajv/dist/runtime/equal").default';Yc.default=Yg});var Xg=U(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});var Xc=ro(),Me=re(),FE=ue(),HE=mi(),KE={message:({params:{i:t,j:e}})=>(0,Me.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Me._)`{i: ${t}, j: ${e}}`},VE={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:KE,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"),d=s.items?(0,Xc.getSchemaTypes)(s.items):[];t.block$data(l,p,(0,Me._)`${i} === false`),t.ok(l);function p(){let k=e.let("i",(0,Me._)`${r}.length`),R=e.let("j");t.setParams({i:k,j:R}),e.assign(l,!0),e.if((0,Me._)`${k} > 1`,()=>(f()?_:y)(k,R))}function f(){return d.length>0&&!d.some(k=>k==="object"||k==="array")}function _(k,R){let $=e.name("item"),P=(0,Xc.checkDataTypes)(d,$,a.opts.strictNumbers,Xc.DataType.Wrong),I=e.const("indices",(0,Me._)`{}`);e.for((0,Me._)`;${k}--;`,()=>{e.let($,(0,Me._)`${r}[${k}]`),e.if(P,(0,Me._)`continue`),d.length>1&&e.if((0,Me._)`typeof ${$} == "string"`,(0,Me._)`${$} += "_"`),e.if((0,Me._)`typeof ${I}[${$}] == "number"`,()=>{e.assign(R,(0,Me._)`${I}[${$}]`),t.error(),e.assign(l,!1).break()}).code((0,Me._)`${I}[${$}] = ${k}`)})}function y(k,R){let $=(0,FE.useFunc)(e,HE.default),P=e.name("outer");e.label(P).for((0,Me._)`;${k}--;`,()=>e.for((0,Me._)`${R} = ${k}; ${R}--;`,()=>e.if((0,Me._)`${$}(${r}[${k}], ${r}[${R}])`,()=>{t.error(),e.assign(l,!1).break(P)})))}}};Zc.default=VE});var Zg=U(ed=>{"use strict";Object.defineProperty(ed,"__esModule",{value:!0});var Qc=re(),GE=ue(),WE=mi(),JE={message:"must be equal to constant",params:({schemaCode:t})=>(0,Qc._)`{allowedValue: ${t}}`},YE={keyword:"const",$data:!0,error:JE,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Qc._)`!${(0,GE.useFunc)(e,WE.default)}(${r}, ${o})`):t.fail((0,Qc._)`${s} !== ${r}`)}};ed.default=YE});var Qg=U(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var bo=re(),XE=ue(),ZE=mi(),QE={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,bo._)`{allowedValues: ${t}}`},e0={keyword:"enum",schemaType:"array",$data:!0,error:QE,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,d=()=>l??(l=(0,XE.useFunc)(e,ZE.default)),p;if(a||n)p=e.let("valid"),t.block$data(p,f);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let y=e.const("vSchema",s);p=(0,bo.or)(...o.map((k,R)=>_(y,R)))}t.pass(p);function f(){e.assign(p,!1),e.forOf("v",s,y=>e.if((0,bo._)`${d()}(${r}, ${y})`,()=>e.assign(p,!0).break()))}function _(y,k){let R=o[k];return typeof R=="object"&&R!==null?(0,bo._)`${d()}(${r}, ${y}[${k}])`:(0,bo._)`${r} === ${R}`}}};td.default=e0});var ey=U(rd=>{"use strict";Object.defineProperty(rd,"__esModule",{value:!0});var t0=zg(),r0=Bg(),n0=Kg(),o0=Vg(),s0=Gg(),i0=Wg(),a0=Jg(),l0=Xg(),c0=Zg(),d0=Qg(),u0=[t0.default,r0.default,n0.default,o0.default,s0.default,i0.default,a0.default,l0.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},c0.default,d0.default];rd.default=u0});var od=U(wo=>{"use strict";Object.defineProperty(wo,"__esModule",{value:!0});wo.validateAdditionalItems=void 0;var Er=re(),nd=ue(),p0={message:({params:{len:t}})=>(0,Er.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Er._)`{limit: ${t}}`},h0={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:p0,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,nd.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}ty(t,n)}};function ty(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Er._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Er._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,nd.alwaysValidSchema)(i,n)){let d=r.var("valid",(0,Er._)`${a} <= ${e.length}`);r.if((0,Er.not)(d),()=>l(d)),t.ok(d)}function l(d){r.forRange("i",e.length,a,p=>{t.subschema({keyword:s,dataProp:p,dataPropType:nd.Type.Num},d),i.allErrors||r.if((0,Er.not)(d),()=>r.break())})}}wo.validateAdditionalItems=ty;wo.default=h0});var sd=U(vo=>{"use strict";Object.defineProperty(vo,"__esModule",{value:!0});vo.validateTuple=void 0;var ry=re(),fi=ue(),m0=dt(),f0={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return ny(t,"additionalItems",e);r.items=!0,!(0,fi.alwaysValidSchema)(r,e)&&t.ok((0,m0.validateArray)(t))}};function ny(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;p(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=fi.mergeEvaluated.items(n,r.length,a.items));let l=n.name("valid"),d=n.const("len",(0,ry._)`${s}.length`);r.forEach((f,_)=>{(0,fi.alwaysValidSchema)(a,f)||(n.if((0,ry._)`${d} > ${_}`,()=>t.subschema({keyword:i,schemaProp:_,dataProp:_},l)),t.ok(l))});function p(f){let{opts:_,errSchemaPath:y}=a,k=r.length,R=k===f.minItems&&(k===f.maxItems||f[e]===!1);if(_.strictTuples&&!R){let $=`"${i}" is ${k}-tuple, but minItems or maxItems/${e} are not specified or different at path "${y}"`;(0,fi.checkStrictMode)(a,$,_.strictTuples)}}}vo.validateTuple=ny;vo.default=f0});var oy=U(id=>{"use strict";Object.defineProperty(id,"__esModule",{value:!0});var g0=sd(),y0={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,g0.validateTuple)(t,"items")};id.default=y0});var iy=U(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});var sy=re(),b0=ue(),w0=dt(),v0=od(),_0={message:({params:{len:t}})=>(0,sy.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,sy._)`{limit: ${t}}`},S0={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:_0,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,b0.alwaysValidSchema)(n,e)&&(o?(0,v0.validateAdditionalItems)(t,o):t.ok((0,w0.validateArray)(t)))}};ad.default=S0});var ay=U(ld=>{"use strict";Object.defineProperty(ld,"__esModule",{value:!0});var pt=re(),gi=ue(),k0={message:({params:{min:t,max:e}})=>e===void 0?(0,pt.str)`must contain at least ${t} valid item(s)`:(0,pt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,pt._)`{minContains: ${t}}`:(0,pt._)`{minContains: ${t}, maxContains: ${e}}`},T0={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:k0,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:l,maxContains:d}=n;s.opts.next?(i=l===void 0?1:l,a=d):i=1;let p=e.const("len",(0,pt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,gi.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,gi.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,gi.alwaysValidSchema)(s,r)){let R=(0,pt._)`${p} >= ${i}`;a!==void 0&&(R=(0,pt._)`${R} && ${p} <= ${a}`),t.pass(R);return}s.items=!0;let f=e.name("valid");a===void 0&&i===1?y(f,()=>e.if(f,()=>e.break())):i===0?(e.let(f,!0),a!==void 0&&e.if((0,pt._)`${o}.length > 0`,_)):(e.let(f,!1),_()),t.result(f,()=>t.reset());function _(){let R=e.name("_valid"),$=e.let("count",0);y(R,()=>e.if(R,()=>k($)))}function y(R,$){e.forRange("i",0,p,P=>{t.subschema({keyword:"contains",dataProp:P,dataPropType:gi.Type.Num,compositeRule:!0},R),$()})}function k(R){e.code((0,pt._)`${R}++`),a===void 0?e.if((0,pt._)`${R} >= ${i}`,()=>e.assign(f,!0).break()):(e.if((0,pt._)`${R} > ${a}`,()=>e.assign(f,!1).break()),i===1?e.assign(f,!0):e.if((0,pt._)`${R} >= ${i}`,()=>e.assign(f,!0)))}}};ld.default=T0});var dy=U(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.validateSchemaDeps=At.validatePropertyDeps=At.error=void 0;var cd=re(),x0=ue(),_o=dt();At.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,cd.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,cd._)`{property: ${t},
2011
2011
  missingProperty: ${n},
2012
2012
  depsCount: ${e},
2013
- deps: ${r}}`};var R0={keyword:"dependencies",type:"object",schemaType:"object",error:At.error,code(t){let[e,r]=$0(t);ly(t,e),cy(t,r)}};function $0({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 ly(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,_o.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(l,()=>{for(let d of a)(0,_o.checkReportMissingProp)(t,d)}):(r.if((0,cd._)`${l} && (${(0,_o.checkMissingProp)(t,a,s)})`),(0,_o.reportMissingProp)(t,s),r.else())}}At.validatePropertyDeps=ly;function cy(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,x0.alwaysValidSchema)(s,e[a])||(r.if((0,_o.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))}At.validateSchemaDeps=cy;At.default=R0});var py=U(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});var uy=re(),E0=ue(),P0={message:"property name must be valid",params:({params:t})=>(0,uy._)`{propertyName: ${t.propertyName}}`},A0={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:P0,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,E0.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,uy.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};dd.default=A0});var pd=U(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});var yi=dt(),St=re(),C0=Mt(),bi=ue(),I0={message:"must NOT have additional properties",params:({params:t})=>(0,St._)`{additionalProperty: ${t.additionalProperty}}`},O0={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:I0,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,bi.alwaysValidSchema)(i,r))return;let d=(0,yi.allSchemaProperties)(n.properties),p=(0,yi.allSchemaProperties)(n.patternProperties);f(),t.ok((0,St._)`${s} === ${C0.default.errors}`);function f(){e.forIn("key",o,$=>{!d.length&&!p.length?k($):e.if(_($),()=>k($))})}function _($){let P;if(d.length>8){let I=(0,bi.schemaRefOrVal)(i,n.properties,"properties");P=(0,yi.isOwnProperty)(e,I,$)}else d.length?P=(0,St.or)(...d.map(I=>(0,St._)`${$} === ${I}`)):P=St.nil;return p.length&&(P=(0,St.or)(P,...p.map(I=>(0,St._)`${(0,yi.usePattern)(t,I)}.test(${$})`))),(0,St.not)(P)}function y($){e.code((0,St._)`delete ${o}[${$}]`)}function k($){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){y($);return}if(r===!1){t.setParams({additionalProperty:$}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,bi.alwaysValidSchema)(i,r)){let P=e.name("valid");l.removeAdditional==="failing"?(R($,P,!1),e.if((0,St.not)(P),()=>{t.reset(),y($)})):(R($,P),a||e.if((0,St.not)(P),()=>e.break()))}}function R($,P,I){let D={keyword:"additionalProperties",dataProp:$,dataPropType:bi.Type.Str};I===!1&&Object.assign(D,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(D,P)}}};ud.default=O0});var fy=U(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var N0=io(),my=dt(),md=ue(),hy=pd(),L0={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&&hy.default.code(new N0.KeywordCxt(s,hy.default,"additionalProperties"));let i=(0,my.allSchemaProperties)(r);for(let f of i)s.definedProperties.add(f);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=md.mergeEvaluated.props(e,(0,md.toHash)(i),s.props));let a=i.filter(f=>!(0,md.alwaysValidSchema)(s,r[f]));if(a.length===0)return;let l=e.name("valid");for(let f of a)d(f)?p(f):(e.if((0,my.propertyInData)(e,o,f,s.opts.ownProperties)),p(f),s.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(f),t.ok(l);function d(f){return s.opts.useDefaults&&!s.compositeRule&&r[f].default!==void 0}function p(f){t.subschema({keyword:"properties",schemaProp:f,dataProp:f},l)}}};hd.default=L0});var wy=U(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var gy=dt(),wi=re(),yy=ue(),by=ue(),j0={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,gy.allSchemaProperties)(r),l=a.filter(R=>(0,yy.alwaysValidSchema)(s,r[R]));if(a.length===0||l.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let d=i.strictSchema&&!i.allowMatchingProperties&&o.properties,p=e.name("valid");s.props!==!0&&!(s.props instanceof wi.Name)&&(s.props=(0,by.evaluatedPropsToName)(e,s.props));let{props:f}=s;_();function _(){for(let R of a)d&&y(R),s.allErrors?k(R):(e.var(p,!0),k(R),e.if(p))}function y(R){for(let $ in d)new RegExp(R).test($)&&(0,yy.checkStrictMode)(s,`property ${$} matches pattern ${R} (use allowMatchingProperties)`)}function k(R){e.forIn("key",n,$=>{e.if((0,wi._)`${(0,gy.usePattern)(t,R)}.test(${$})`,()=>{let P=l.includes(R);P||t.subschema({keyword:"patternProperties",schemaProp:R,dataProp:$,dataPropType:by.Type.Str},p),s.opts.unevaluated&&f!==!0?e.assign((0,wi._)`${f}[${$}]`,!0):!P&&!s.allErrors&&e.if((0,wi.not)(p),()=>e.break())})})}}};fd.default=j0});var vy=U(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});var D0=ue(),U0={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,D0.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"}};gd.default=U0});var _y=U(yd=>{"use strict";Object.defineProperty(yd,"__esModule",{value:!0});var M0=dt(),q0={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:M0.validateUnion,error:{message:"must match a schema in anyOf"}};yd.default=q0});var Sy=U(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var vi=re(),z0=ue(),B0={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,vi._)`{passingSchemas: ${t.passing}}`},F0={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:B0,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(d),t.result(i,()=>t.reset(),()=>t.error(!0));function d(){s.forEach((p,f)=>{let _;(0,z0.alwaysValidSchema)(o,p)?e.var(l,!0):_=t.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},l),f>0&&e.if((0,vi._)`${l} && ${i}`).assign(i,!1).assign(a,(0,vi._)`[${a}, ${f}]`).else(),e.if(l,()=>{e.assign(i,!0),e.assign(a,f),_&&t.mergeEvaluated(_,vi.Name)})})}}};bd.default=F0});var ky=U(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var H0=ue(),K0={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,H0.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};wd.default=K0});var Ry=U(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var _i=re(),xy=ue(),V0={message:({params:t})=>(0,_i.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,_i._)`{failingKeyword: ${t.ifClause}}`},G0={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:V0,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,xy.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Ty(n,"then"),s=Ty(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(l(),t.reset(),o&&s){let p=e.let("ifClause");t.setParams({ifClause:p}),e.if(a,d("then",p),d("else",p))}else o?e.if(a,d("then")):e.if((0,_i.not)(a),d("else"));t.pass(i,()=>t.error(!0));function l(){let p=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(p)}function d(p,f){return()=>{let _=t.subschema({keyword:p},a);e.assign(i,a),t.mergeValidEvaluated(_,i),f?e.assign(f,(0,_i._)`${p}`):t.setParams({ifClause:p})}}}};function Ty(t,e){let r=t.schema[e];return r!==void 0&&!(0,xy.alwaysValidSchema)(t,r)}vd.default=G0});var $y=U(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var W0=ue(),J0={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,W0.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};_d.default=J0});var Ey=U(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var Y0=od(),X0=oy(),Z0=sd(),Q0=iy(),eP=ay(),tP=dy(),rP=py(),nP=pd(),oP=fy(),sP=wy(),iP=vy(),aP=_y(),lP=Sy(),cP=ky(),dP=Ry(),uP=$y();function pP(t=!1){let e=[iP.default,aP.default,lP.default,cP.default,dP.default,uP.default,rP.default,nP.default,tP.default,oP.default,sP.default];return t?e.push(X0.default,Q0.default):e.push(Y0.default,Z0.default),e.push(eP.default),e}Sd.default=pP});var Py=U(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var xe=re(),mP={message:({schemaCode:t})=>(0,xe.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,xe._)`{format: ${t}}`},hP={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:mP,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:l,errSchemaPath:d,schemaEnv:p,self:f}=a;if(!l.validateFormats)return;o?_():y();function _(){let k=r.scopeValue("formats",{ref:f.formats,code:l.code.formats}),R=r.const("fDef",(0,xe._)`${k}[${i}]`),$=r.let("fType"),P=r.let("format");r.if((0,xe._)`typeof ${R} == "object" && !(${R} instanceof RegExp)`,()=>r.assign($,(0,xe._)`${R}.type || "string"`).assign(P,(0,xe._)`${R}.validate`),()=>r.assign($,(0,xe._)`"string"`).assign(P,R)),t.fail$data((0,xe.or)(I(),D()));function I(){return l.strictSchema===!1?xe.nil:(0,xe._)`${i} && !${P}`}function D(){let Y=p.$async?(0,xe._)`(${R}.async ? await ${P}(${n}) : ${P}(${n}))`:(0,xe._)`${P}(${n})`,F=(0,xe._)`(typeof ${P} == "function" ? ${Y} : ${P}.test(${n}))`;return(0,xe._)`${P} && ${P} !== true && ${$} === ${e} && !${F}`}}function y(){let k=f.formats[s];if(!k){I();return}if(k===!0)return;let[R,$,P]=D(k);R===e&&t.pass(Y());function I(){if(l.strictSchema===!1){f.logger.warn(F());return}throw new Error(F());function F(){return`unknown format "${s}" ignored in schema at path "${d}"`}}function D(F){let Oe=F instanceof RegExp?(0,xe.regexpCode)(F):l.code.formats?(0,xe._)`${l.code.formats}${(0,xe.getProperty)(s)}`:void 0,Ce=r.scopeValue("formats",{key:s,ref:F,code:Oe});return typeof F=="object"&&!(F instanceof RegExp)?[F.type||"string",F.validate,(0,xe._)`${Ce}.validate`]:["string",F,Ce]}function Y(){if(typeof k=="object"&&!(k instanceof RegExp)&&k.async){if(!p.$async)throw new Error("async format in sync schema");return(0,xe._)`await ${P}(${n})`}return typeof $=="function"?(0,xe._)`${P}(${n})`:(0,xe._)`${P}.test(${n})`}}}};kd.default=hP});var Ay=U(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var fP=Py(),gP=[fP.default];Td.default=gP});var Cy=U(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.contentVocabulary=ln.metadataVocabulary=void 0;ln.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ln.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Oy=U(xd=>{"use strict";Object.defineProperty(xd,"__esModule",{value:!0});var yP=qg(),bP=ey(),wP=Ey(),vP=Ay(),Iy=Cy(),_P=[yP.default,bP.default,(0,wP.default)(),vP.default,Iy.metadataVocabulary,Iy.contentVocabulary];xd.default=_P});var Ly=U(Si=>{"use strict";Object.defineProperty(Si,"__esModule",{value:!0});Si.DiscrError=void 0;var Ny;(function(t){t.Tag="tag",t.Mapping="mapping"})(Ny||(Si.DiscrError=Ny={}))});var Dy=U($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});var cn=re(),Rd=Ly(),jy=ni(),SP=ao(),kP=ue(),TP={message:({params:{discrError:t,tagName:e}})=>t===Rd.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,cn._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},xP={keyword:"discriminator",type:"object",schemaType:"object",error:TP,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),d=e.const("tag",(0,cn._)`${r}${(0,cn.getProperty)(a)}`);e.if((0,cn._)`typeof ${d} == "string"`,()=>p(),()=>t.error(!1,{discrError:Rd.DiscrError.Tag,tag:d,tagName:a})),t.ok(l);function p(){let y=_();e.if(!1);for(let k in y)e.elseIf((0,cn._)`${d} === ${k}`),e.assign(l,f(y[k]));e.else(),t.error(!1,{discrError:Rd.DiscrError.Mapping,tag:d,tagName:a}),e.endIf()}function f(y){let k=e.name("valid"),R=t.subschema({keyword:"oneOf",schemaProp:y},k);return t.mergeEvaluated(R,cn.Name),k}function _(){var y;let k={},R=P(o),$=!0;for(let Y=0;Y<i.length;Y++){let F=i[Y];if(F?.$ref&&!(0,kP.schemaHasRulesButRef)(F,s.self.RULES)){let Ce=F.$ref;if(F=jy.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Ce),F instanceof jy.SchemaEnv&&(F=F.schema),F===void 0)throw new SP.default(s.opts.uriResolver,s.baseId,Ce)}let Oe=(y=F?.properties)===null||y===void 0?void 0:y[a];if(typeof Oe!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);$=$&&(R||P(F)),I(Oe,Y)}if(!$)throw new Error(`discriminator: "${a}" must be required`);return k;function P({required:Y}){return Array.isArray(Y)&&Y.includes(a)}function I(Y,F){if(Y.const)D(Y.const,F);else if(Y.enum)for(let Oe of Y.enum)D(Oe,F);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function D(Y,F){if(typeof Y!="string"||Y in k)throw new Error(`discriminator: "${a}" values must be unique strings`);k[Y]=F}}}};$d.default=xP});var Uy=U((V1,RP)=>{RP.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 Pd=U((Se,Ed)=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.MissingRefError=Se.ValidationError=Se.CodeGen=Se.Name=Se.nil=Se.stringify=Se.str=Se._=Se.KeywordCxt=Se.Ajv=void 0;var $P=Ng(),EP=Oy(),PP=Dy(),My=Uy(),AP=["/properties"],ki="http://json-schema.org/draft-07/schema",dn=class extends $P.default{_addVocabularies(){super._addVocabularies(),EP.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(PP.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(My,AP):My;this.addMetaSchema(e,ki,!1),this.refs["http://json-schema.org/schema"]=ki}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(ki)?ki:void 0)}};Se.Ajv=dn;Ed.exports=Se=dn;Ed.exports.Ajv=dn;Object.defineProperty(Se,"__esModule",{value:!0});Se.default=dn;var CP=io();Object.defineProperty(Se,"KeywordCxt",{enumerable:!0,get:function(){return CP.KeywordCxt}});var un=re();Object.defineProperty(Se,"_",{enumerable:!0,get:function(){return un._}});Object.defineProperty(Se,"str",{enumerable:!0,get:function(){return un.str}});Object.defineProperty(Se,"stringify",{enumerable:!0,get:function(){return un.stringify}});Object.defineProperty(Se,"nil",{enumerable:!0,get:function(){return un.nil}});Object.defineProperty(Se,"Name",{enumerable:!0,get:function(){return un.Name}});Object.defineProperty(Se,"CodeGen",{enumerable:!0,get:function(){return un.CodeGen}});var IP=ti();Object.defineProperty(Se,"ValidationError",{enumerable:!0,get:function(){return IP.default}});var OP=ao();Object.defineProperty(Se,"MissingRefError",{enumerable:!0,get:function(){return OP.default}})});var Gy=U(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.formatNames=It.fastFormats=It.fullFormats=void 0;function Ct(t,e){return{validate:t,compare:e}}It.fullFormats={date:Ct(Fy,Od),time:Ct(Cd(!0),Nd),"date-time":Ct(qy(!0),Ky),"iso-time":Ct(Cd(),Hy),"iso-date-time":Ct(qy(),Vy),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:MP,"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:VP,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:qP,int32:{type:"number",validate:FP},int64:{type:"number",validate:HP},float:{type:"number",validate:By},double:{type:"number",validate:By},password:!0,binary:!0};It.fastFormats={...It.fullFormats,date:Ct(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Od),time:Ct(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Nd),"date-time":Ct(/^\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,Ky),"iso-time":Ct(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Hy),"iso-date-time":Ct(/^\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,Vy),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};It.formatNames=Object.keys(It.fullFormats);function NP(t){return t%4===0&&(t%100!==0||t%400===0)}var LP=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,jP=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Fy(t){let e=LP.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&&NP(r)?29:jP[n])}function Od(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Ad=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Cd(t){return function(r){let n=Ad.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],l=n[5]==="-"?-1:1,d=+(n[6]||0),p=+(n[7]||0);if(d>23||p>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let f=s-p*l,_=o-d*l-(f<0?1:0);return(_===23||_===-1)&&(f===59||f===-1)&&i<61}}function Nd(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 Hy(t,e){if(!(t&&e))return;let r=Ad.exec(t),n=Ad.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 Id=/t|\s/i;function qy(t){let e=Cd(t);return function(n){let o=n.split(Id);return o.length===2&&Fy(o[0])&&e(o[1])}}function Ky(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function Vy(t,e){if(!(t&&e))return;let[r,n]=t.split(Id),[o,s]=e.split(Id),i=Od(r,o);if(i!==void 0)return i||Nd(n,s)}var DP=/\/|:/,UP=/^(?:[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 MP(t){return DP.test(t)&&UP.test(t)}var zy=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function qP(t){return zy.lastIndex=0,zy.test(t)}var zP=-(2**31),BP=2**31-1;function FP(t){return Number.isInteger(t)&&t<=BP&&t>=zP}function HP(t){return Number.isInteger(t)}function By(){return!0}var KP=/[^\\]\\Z/;function VP(t){if(KP.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Wy=U(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.formatLimitDefinition=void 0;var GP=Pd(),kt=re(),lr=kt.operators,Ti={formatMaximum:{okStr:"<=",ok:lr.LTE,fail:lr.GT},formatMinimum:{okStr:">=",ok:lr.GTE,fail:lr.LT},formatExclusiveMaximum:{okStr:"<",ok:lr.LT,fail:lr.GTE},formatExclusiveMinimum:{okStr:">",ok:lr.GT,fail:lr.LTE}},WP={message:({keyword:t,schemaCode:e})=>(0,kt.str)`should be ${Ti[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,kt._)`{comparison: ${Ti[t].okStr}, limit: ${e}}`};pn.formatLimitDefinition={keyword:Object.keys(Ti),type:"string",schemaType:"string",$data:!0,error:WP,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 GP.KeywordCxt(s,a.RULES.all.format.definition,"format");l.$data?d():p();function d(){let _=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),y=e.const("fmt",(0,kt._)`${_}[${l.schemaCode}]`);t.fail$data((0,kt.or)((0,kt._)`typeof ${y} != "object"`,(0,kt._)`${y} instanceof RegExp`,(0,kt._)`typeof ${y}.compare != "function"`,f(y)))}function p(){let _=l.schema,y=a.formats[_];if(!y||y===!0)return;if(typeof y!="object"||y instanceof RegExp||typeof y.compare!="function")throw new Error(`"${o}": format "${_}" does not define "compare" function`);let k=e.scopeValue("formats",{key:_,ref:y,code:i.code.formats?(0,kt._)`${i.code.formats}${(0,kt.getProperty)(_)}`:void 0});t.fail$data(f(k))}function f(_){return(0,kt._)`${_}.compare(${r}, ${n}) ${Ti[o].fail} 0`}},dependencies:["format"]};var JP=t=>(t.addKeyword(pn.formatLimitDefinition),t);pn.default=JP});var Zy=U((So,Xy)=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});var mn=Gy(),YP=Wy(),Ld=re(),Jy=new Ld.Name("fullFormats"),XP=new Ld.Name("fastFormats"),jd=(t,e={keywords:!0})=>{if(Array.isArray(e))return Yy(t,e,mn.fullFormats,Jy),t;let[r,n]=e.mode==="fast"?[mn.fastFormats,XP]:[mn.fullFormats,Jy],o=e.formats||mn.formatNames;return Yy(t,o,r,n),e.keywords&&(0,YP.default)(t),t};jd.get=(t,e="full")=>{let n=(e==="fast"?mn.fastFormats:mn.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Yy(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Ld._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}Xy.exports=So=jd;Object.defineProperty(So,"__esModule",{value:!0});So.default=jd});function ZP(){let t=new Qy.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,eb.default)(t),t}var Qy,eb,xi,tb=j(()=>{Qy=Xd(Pd(),1),eb=Xd(Zy(),1);xi=class{constructor(e){this._ajv=e??ZP()}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 Ri,rb=j(()=>{Jr();Ri=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(p=>p.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,l=a?Array.isArray(a.content)?a.content:[a.content]:[],d=l.some(p=>p.type==="tool_use");if(i){if(s.some(p=>p.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!d)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(d){let p=new Set(l.filter(_=>_.type==="tool_use").map(_=>_.id)),f=new Set(s.filter(_=>_.type==="tool_result").map(_=>_.toolUseId));if(p.size!==f.size||![...p].every(_=>f.has(_)))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},Hn,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},Wr,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 nb(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 ob(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 sb=j(()=>{});var $i,ib=j(()=>{cf();Jr();tb();Nn();rb();sb();$i=class extends Bs{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Fn.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 xi,this.setRequestHandler(Ya,n=>this._oninitialize(n)),this.setNotificationHandler(Xa,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(ol,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Fn.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ri(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=lf(this._capabilities,e)}setRequestHandler(e,r){let o=Xt(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Fr(o);if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(l,d)=>{let p=Yt(Gr,l);if(!p.success){let k=p.error instanceof Error?p.error.message:String(p.error);throw new z(K.InvalidParams,`Invalid tools/call request: ${k}`)}let{params:f}=p.data,_=await Promise.resolve(r(l,d));if(f.task){let k=Yt(Kr,_);if(!k.success){let R=k.error instanceof Error?k.error.message:String(k.error);throw new z(K.InvalidParams,`Invalid task creation result: ${R}`)}return k.data}let y=Yt(As,_);if(!y.success){let k=y.error instanceof Error?y.error.message:String(y.error);throw new z(K.InvalidParams,`Invalid tools/call result: ${k}`)}return y.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){ob(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&nb(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:ih.includes(r)?r:Ka,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"},hs)}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(d=>d.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],l=a.some(d=>d.type==="tool_use");if(s){if(o.some(d=>d.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let d=new Set(a.filter(f=>f.type==="tool_use").map(f=>f.id)),p=new Set(o.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(d.size!==p.size||![...d].every(f=>p.has(f)))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},sl,r):this.request({method:"sampling/createMessage",params:e},Hn,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},Wr,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},Wr,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(K.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof z?i:new z(K.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},il,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 Dd(t){return!!t&&typeof t=="object"&&lb in t}function cb(t){return t[lb]?.complete}var lb,ab,db=j(()=>{lb=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(ab||(ab={}))});var ub=j(()=>{});function eA(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"),!QP.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 tA(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 Ud(t){let e=eA(t);return tA(t,e.warnings),e.isValid}var QP,pb=j(()=>{QP=/^[A-Za-z0-9._-]{1,128}$/});var Ei,mb=j(()=>{Ei=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 rA}from"zod";function gb(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function yb(t){return"_def"in t||"_zod"in t||gb(t)}function Md(t){return typeof t!="object"||t===null||yb(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(gb)}function hb(t){if(t){if(Md(t))return yr(t);if(!yb(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function oA(t){let e=Xt(t);return e?Object.entries(e).map(([r,n])=>{let o=oh(n),s=sh(n);return{name:r,description:o,required:!s}}):[]}function cr(t){let r=Xt(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Fr(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function fb(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Pi,nA,ko,bb=j(()=>{ib();Nn();Fl();Jr();db();ub();pb();mb();Pi=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 $i(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Ei(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(cr(Ps)),this.server.assertCanSetRequestHandler(cr(Gr)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ps,()=>({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=Br(r.inputSchema);return o?ql(o,{strictUnions:!0,pipeStrategy:"input"}):nA})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Br(r.outputSchema);o&&(n.outputSchema=ql(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Gr,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new z(K.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new z(K.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(K.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new z(K.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===K.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=Br(e.inputSchema)??e.inputSchema,i=await cs(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",l=ds(a);throw new z(K.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(K.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Br(e.outputSchema),s=await cs(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=ds(i);throw new z(K.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,d=a.task,p=d.pollInterval??5e3;for(;d.status!=="completed"&&d.status!=="failed"&&d.status!=="cancelled";){await new Promise(_=>setTimeout(_,p));let f=await n.taskStore.getTask(l);if(!f)throw new z(K.InternalError,`Task ${l} not found during polling`);d=f}return await n.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(cr(Cs)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Cs,async e=>{switch(e.params.ref.type){case"ref/prompt":return Sh(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return kh(e),this.handleResourceCompletion(e,e.params.ref);default:throw new z(K.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(K.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new z(K.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return ko;let s=Xt(n.argsSchema)?.[e.params.argument.name];if(!Dd(s))return ko;let i=cb(s);if(!i)return ko;let a=await i(e.params.argument.value,e.params.context);return fb(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 ko;throw new z(K.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return ko;let s=await o(e.params.argument.value,e.params.context);return fb(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(cr(Ts)),this.server.assertCanSetRequestHandler(cr(xs)),this.server.assertCanSetRequestHandler(cr(Rs)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ts,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(xs,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Rs,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new z(K.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(K.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(cr($s)),this.server.assertCanSetRequestHandler(cr(Es)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler($s,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?oA(r.argsSchema):void 0}))})),this.server.setRequestHandler(Es,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new z(K.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new z(K.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Br(n.argsSchema),s=await cs(o,e.params.arguments);if(!s.success){let l="error"in s?s.error:"Unknown error",d=ds(l);throw new z(K.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${d}`)}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:d=>{typeof d.name<"u"&&d.name!==e&&(delete this._registeredResourceTemplates[e],d.name&&(this._registeredResourceTemplates[d.name]=i)),typeof d.title<"u"&&(i.title=d.title),typeof d.template<"u"&&(i.resourceTemplate=d.template),typeof d.metadata<"u"&&(i.metadata=d.metadata),typeof d.callback<"u"&&(i.readCallback=d.callback),typeof d.enabled<"u"&&(i.enabled=d.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(d=>!!n.completeCallback(d))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:yr(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=yr(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 d=l instanceof rA?l._def?.innerType:l;return Dd(d)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,l,d){Ud(e);let p={title:r,description:n,inputSchema:hb(o),outputSchema:hb(s),annotations:i,execution:a,_meta:l,handler:d,enabled:!0,disable:()=>p.update({enabled:!1}),enable:()=>p.update({enabled:!0}),remove:()=>p.update({name:null}),update:f=>{typeof f.name<"u"&&f.name!==e&&(typeof f.name=="string"&&Ud(f.name),delete this._registeredTools[e],f.name&&(this._registeredTools[f.name]=p)),typeof f.title<"u"&&(p.title=f.title),typeof f.description<"u"&&(p.description=f.description),typeof f.paramsSchema<"u"&&(p.inputSchema=yr(f.paramsSchema)),typeof f.outputSchema<"u"&&(p.outputSchema=yr(f.outputSchema)),typeof f.callback<"u"&&(p.handler=f.callback),typeof f.annotations<"u"&&(p.annotations=f.annotations),typeof f._meta<"u"&&(p._meta=f._meta),typeof f.enabled<"u"&&(p.enabled=f.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=p,this.setToolRequestHandlers(),this.sendToolListChanged(),p}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let l=r[0];if(Md(l))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Md(r[0])&&(i=r.shift());else if(typeof l=="object"&&l!==null){if(Object.values(l).some(d=>typeof d=="object"&&d!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,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:d}=r;return this._createRegisteredTool(e,o,s,i,a,l,{taskSupport:"forbidden"},d,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let 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()}},nA={type:"object",properties:{}};ko={completion:{values:[],hasMore:!1}}});function iA(t){return hh.parse(JSON.parse(t))}function wb(t){return JSON.stringify(t)+`
2013
+ deps: ${r}}`};var R0={keyword:"dependencies",type:"object",schemaType:"object",error:At.error,code(t){let[e,r]=$0(t);ly(t,e),cy(t,r)}};function $0({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 ly(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,_o.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(l,()=>{for(let d of a)(0,_o.checkReportMissingProp)(t,d)}):(r.if((0,cd._)`${l} && (${(0,_o.checkMissingProp)(t,a,s)})`),(0,_o.reportMissingProp)(t,s),r.else())}}At.validatePropertyDeps=ly;function cy(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,x0.alwaysValidSchema)(s,e[a])||(r.if((0,_o.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))}At.validateSchemaDeps=cy;At.default=R0});var py=U(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});var uy=re(),E0=ue(),P0={message:"property name must be valid",params:({params:t})=>(0,uy._)`{propertyName: ${t.propertyName}}`},A0={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:P0,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,E0.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,uy.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};dd.default=A0});var pd=U(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});var yi=dt(),St=re(),C0=Mt(),bi=ue(),I0={message:"must NOT have additional properties",params:({params:t})=>(0,St._)`{additionalProperty: ${t.additionalProperty}}`},O0={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:I0,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,bi.alwaysValidSchema)(i,r))return;let d=(0,yi.allSchemaProperties)(n.properties),p=(0,yi.allSchemaProperties)(n.patternProperties);f(),t.ok((0,St._)`${s} === ${C0.default.errors}`);function f(){e.forIn("key",o,$=>{!d.length&&!p.length?k($):e.if(_($),()=>k($))})}function _($){let P;if(d.length>8){let I=(0,bi.schemaRefOrVal)(i,n.properties,"properties");P=(0,yi.isOwnProperty)(e,I,$)}else d.length?P=(0,St.or)(...d.map(I=>(0,St._)`${$} === ${I}`)):P=St.nil;return p.length&&(P=(0,St.or)(P,...p.map(I=>(0,St._)`${(0,yi.usePattern)(t,I)}.test(${$})`))),(0,St.not)(P)}function y($){e.code((0,St._)`delete ${o}[${$}]`)}function k($){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){y($);return}if(r===!1){t.setParams({additionalProperty:$}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,bi.alwaysValidSchema)(i,r)){let P=e.name("valid");l.removeAdditional==="failing"?(R($,P,!1),e.if((0,St.not)(P),()=>{t.reset(),y($)})):(R($,P),a||e.if((0,St.not)(P),()=>e.break()))}}function R($,P,I){let D={keyword:"additionalProperties",dataProp:$,dataPropType:bi.Type.Str};I===!1&&Object.assign(D,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(D,P)}}};ud.default=O0});var fy=U(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});var N0=io(),hy=dt(),hd=ue(),my=pd(),L0={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&&my.default.code(new N0.KeywordCxt(s,my.default,"additionalProperties"));let i=(0,hy.allSchemaProperties)(r);for(let f of i)s.definedProperties.add(f);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=hd.mergeEvaluated.props(e,(0,hd.toHash)(i),s.props));let a=i.filter(f=>!(0,hd.alwaysValidSchema)(s,r[f]));if(a.length===0)return;let l=e.name("valid");for(let f of a)d(f)?p(f):(e.if((0,hy.propertyInData)(e,o,f,s.opts.ownProperties)),p(f),s.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(f),t.ok(l);function d(f){return s.opts.useDefaults&&!s.compositeRule&&r[f].default!==void 0}function p(f){t.subschema({keyword:"properties",schemaProp:f,dataProp:f},l)}}};md.default=L0});var wy=U(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var gy=dt(),wi=re(),yy=ue(),by=ue(),j0={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,gy.allSchemaProperties)(r),l=a.filter(R=>(0,yy.alwaysValidSchema)(s,r[R]));if(a.length===0||l.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let d=i.strictSchema&&!i.allowMatchingProperties&&o.properties,p=e.name("valid");s.props!==!0&&!(s.props instanceof wi.Name)&&(s.props=(0,by.evaluatedPropsToName)(e,s.props));let{props:f}=s;_();function _(){for(let R of a)d&&y(R),s.allErrors?k(R):(e.var(p,!0),k(R),e.if(p))}function y(R){for(let $ in d)new RegExp(R).test($)&&(0,yy.checkStrictMode)(s,`property ${$} matches pattern ${R} (use allowMatchingProperties)`)}function k(R){e.forIn("key",n,$=>{e.if((0,wi._)`${(0,gy.usePattern)(t,R)}.test(${$})`,()=>{let P=l.includes(R);P||t.subschema({keyword:"patternProperties",schemaProp:R,dataProp:$,dataPropType:by.Type.Str},p),s.opts.unevaluated&&f!==!0?e.assign((0,wi._)`${f}[${$}]`,!0):!P&&!s.allErrors&&e.if((0,wi.not)(p),()=>e.break())})})}}};fd.default=j0});var vy=U(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});var D0=ue(),U0={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,D0.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"}};gd.default=U0});var _y=U(yd=>{"use strict";Object.defineProperty(yd,"__esModule",{value:!0});var M0=dt(),q0={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:M0.validateUnion,error:{message:"must match a schema in anyOf"}};yd.default=q0});var Sy=U(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var vi=re(),z0=ue(),B0={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,vi._)`{passingSchemas: ${t.passing}}`},F0={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:B0,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(d),t.result(i,()=>t.reset(),()=>t.error(!0));function d(){s.forEach((p,f)=>{let _;(0,z0.alwaysValidSchema)(o,p)?e.var(l,!0):_=t.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},l),f>0&&e.if((0,vi._)`${l} && ${i}`).assign(i,!1).assign(a,(0,vi._)`[${a}, ${f}]`).else(),e.if(l,()=>{e.assign(i,!0),e.assign(a,f),_&&t.mergeEvaluated(_,vi.Name)})})}}};bd.default=F0});var ky=U(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var H0=ue(),K0={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,H0.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};wd.default=K0});var Ry=U(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var _i=re(),xy=ue(),V0={message:({params:t})=>(0,_i.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,_i._)`{failingKeyword: ${t.ifClause}}`},G0={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:V0,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,xy.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Ty(n,"then"),s=Ty(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(l(),t.reset(),o&&s){let p=e.let("ifClause");t.setParams({ifClause:p}),e.if(a,d("then",p),d("else",p))}else o?e.if(a,d("then")):e.if((0,_i.not)(a),d("else"));t.pass(i,()=>t.error(!0));function l(){let p=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(p)}function d(p,f){return()=>{let _=t.subschema({keyword:p},a);e.assign(i,a),t.mergeValidEvaluated(_,i),f?e.assign(f,(0,_i._)`${p}`):t.setParams({ifClause:p})}}}};function Ty(t,e){let r=t.schema[e];return r!==void 0&&!(0,xy.alwaysValidSchema)(t,r)}vd.default=G0});var $y=U(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var W0=ue(),J0={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,W0.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};_d.default=J0});var Ey=U(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var Y0=od(),X0=oy(),Z0=sd(),Q0=iy(),eP=ay(),tP=dy(),rP=py(),nP=pd(),oP=fy(),sP=wy(),iP=vy(),aP=_y(),lP=Sy(),cP=ky(),dP=Ry(),uP=$y();function pP(t=!1){let e=[iP.default,aP.default,lP.default,cP.default,dP.default,uP.default,rP.default,nP.default,tP.default,oP.default,sP.default];return t?e.push(X0.default,Q0.default):e.push(Y0.default,Z0.default),e.push(eP.default),e}Sd.default=pP});var Py=U(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var xe=re(),hP={message:({schemaCode:t})=>(0,xe.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,xe._)`{format: ${t}}`},mP={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:hP,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:l,errSchemaPath:d,schemaEnv:p,self:f}=a;if(!l.validateFormats)return;o?_():y();function _(){let k=r.scopeValue("formats",{ref:f.formats,code:l.code.formats}),R=r.const("fDef",(0,xe._)`${k}[${i}]`),$=r.let("fType"),P=r.let("format");r.if((0,xe._)`typeof ${R} == "object" && !(${R} instanceof RegExp)`,()=>r.assign($,(0,xe._)`${R}.type || "string"`).assign(P,(0,xe._)`${R}.validate`),()=>r.assign($,(0,xe._)`"string"`).assign(P,R)),t.fail$data((0,xe.or)(I(),D()));function I(){return l.strictSchema===!1?xe.nil:(0,xe._)`${i} && !${P}`}function D(){let Y=p.$async?(0,xe._)`(${R}.async ? await ${P}(${n}) : ${P}(${n}))`:(0,xe._)`${P}(${n})`,F=(0,xe._)`(typeof ${P} == "function" ? ${Y} : ${P}.test(${n}))`;return(0,xe._)`${P} && ${P} !== true && ${$} === ${e} && !${F}`}}function y(){let k=f.formats[s];if(!k){I();return}if(k===!0)return;let[R,$,P]=D(k);R===e&&t.pass(Y());function I(){if(l.strictSchema===!1){f.logger.warn(F());return}throw new Error(F());function F(){return`unknown format "${s}" ignored in schema at path "${d}"`}}function D(F){let Oe=F instanceof RegExp?(0,xe.regexpCode)(F):l.code.formats?(0,xe._)`${l.code.formats}${(0,xe.getProperty)(s)}`:void 0,Ce=r.scopeValue("formats",{key:s,ref:F,code:Oe});return typeof F=="object"&&!(F instanceof RegExp)?[F.type||"string",F.validate,(0,xe._)`${Ce}.validate`]:["string",F,Ce]}function Y(){if(typeof k=="object"&&!(k instanceof RegExp)&&k.async){if(!p.$async)throw new Error("async format in sync schema");return(0,xe._)`await ${P}(${n})`}return typeof $=="function"?(0,xe._)`${P}(${n})`:(0,xe._)`${P}.test(${n})`}}}};kd.default=mP});var Ay=U(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var fP=Py(),gP=[fP.default];Td.default=gP});var Cy=U(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.contentVocabulary=ln.metadataVocabulary=void 0;ln.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ln.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Oy=U(xd=>{"use strict";Object.defineProperty(xd,"__esModule",{value:!0});var yP=qg(),bP=ey(),wP=Ey(),vP=Ay(),Iy=Cy(),_P=[yP.default,bP.default,(0,wP.default)(),vP.default,Iy.metadataVocabulary,Iy.contentVocabulary];xd.default=_P});var Ly=U(Si=>{"use strict";Object.defineProperty(Si,"__esModule",{value:!0});Si.DiscrError=void 0;var Ny;(function(t){t.Tag="tag",t.Mapping="mapping"})(Ny||(Si.DiscrError=Ny={}))});var Dy=U($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});var cn=re(),Rd=Ly(),jy=ni(),SP=ao(),kP=ue(),TP={message:({params:{discrError:t,tagName:e}})=>t===Rd.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,cn._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},xP={keyword:"discriminator",type:"object",schemaType:"object",error:TP,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),d=e.const("tag",(0,cn._)`${r}${(0,cn.getProperty)(a)}`);e.if((0,cn._)`typeof ${d} == "string"`,()=>p(),()=>t.error(!1,{discrError:Rd.DiscrError.Tag,tag:d,tagName:a})),t.ok(l);function p(){let y=_();e.if(!1);for(let k in y)e.elseIf((0,cn._)`${d} === ${k}`),e.assign(l,f(y[k]));e.else(),t.error(!1,{discrError:Rd.DiscrError.Mapping,tag:d,tagName:a}),e.endIf()}function f(y){let k=e.name("valid"),R=t.subschema({keyword:"oneOf",schemaProp:y},k);return t.mergeEvaluated(R,cn.Name),k}function _(){var y;let k={},R=P(o),$=!0;for(let Y=0;Y<i.length;Y++){let F=i[Y];if(F?.$ref&&!(0,kP.schemaHasRulesButRef)(F,s.self.RULES)){let Ce=F.$ref;if(F=jy.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Ce),F instanceof jy.SchemaEnv&&(F=F.schema),F===void 0)throw new SP.default(s.opts.uriResolver,s.baseId,Ce)}let Oe=(y=F?.properties)===null||y===void 0?void 0:y[a];if(typeof Oe!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);$=$&&(R||P(F)),I(Oe,Y)}if(!$)throw new Error(`discriminator: "${a}" must be required`);return k;function P({required:Y}){return Array.isArray(Y)&&Y.includes(a)}function I(Y,F){if(Y.const)D(Y.const,F);else if(Y.enum)for(let Oe of Y.enum)D(Oe,F);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function D(Y,F){if(typeof Y!="string"||Y in k)throw new Error(`discriminator: "${a}" values must be unique strings`);k[Y]=F}}}};$d.default=xP});var Uy=U((V1,RP)=>{RP.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 Pd=U((Se,Ed)=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.MissingRefError=Se.ValidationError=Se.CodeGen=Se.Name=Se.nil=Se.stringify=Se.str=Se._=Se.KeywordCxt=Se.Ajv=void 0;var $P=Ng(),EP=Oy(),PP=Dy(),My=Uy(),AP=["/properties"],ki="http://json-schema.org/draft-07/schema",dn=class extends $P.default{_addVocabularies(){super._addVocabularies(),EP.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(PP.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(My,AP):My;this.addMetaSchema(e,ki,!1),this.refs["http://json-schema.org/schema"]=ki}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(ki)?ki:void 0)}};Se.Ajv=dn;Ed.exports=Se=dn;Ed.exports.Ajv=dn;Object.defineProperty(Se,"__esModule",{value:!0});Se.default=dn;var CP=io();Object.defineProperty(Se,"KeywordCxt",{enumerable:!0,get:function(){return CP.KeywordCxt}});var un=re();Object.defineProperty(Se,"_",{enumerable:!0,get:function(){return un._}});Object.defineProperty(Se,"str",{enumerable:!0,get:function(){return un.str}});Object.defineProperty(Se,"stringify",{enumerable:!0,get:function(){return un.stringify}});Object.defineProperty(Se,"nil",{enumerable:!0,get:function(){return un.nil}});Object.defineProperty(Se,"Name",{enumerable:!0,get:function(){return un.Name}});Object.defineProperty(Se,"CodeGen",{enumerable:!0,get:function(){return un.CodeGen}});var IP=ti();Object.defineProperty(Se,"ValidationError",{enumerable:!0,get:function(){return IP.default}});var OP=ao();Object.defineProperty(Se,"MissingRefError",{enumerable:!0,get:function(){return OP.default}})});var Gy=U(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.formatNames=It.fastFormats=It.fullFormats=void 0;function Ct(t,e){return{validate:t,compare:e}}It.fullFormats={date:Ct(Fy,Od),time:Ct(Cd(!0),Nd),"date-time":Ct(qy(!0),Ky),"iso-time":Ct(Cd(),Hy),"iso-date-time":Ct(qy(),Vy),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:MP,"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:VP,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:qP,int32:{type:"number",validate:FP},int64:{type:"number",validate:HP},float:{type:"number",validate:By},double:{type:"number",validate:By},password:!0,binary:!0};It.fastFormats={...It.fullFormats,date:Ct(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Od),time:Ct(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Nd),"date-time":Ct(/^\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,Ky),"iso-time":Ct(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Hy),"iso-date-time":Ct(/^\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,Vy),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};It.formatNames=Object.keys(It.fullFormats);function NP(t){return t%4===0&&(t%100!==0||t%400===0)}var LP=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,jP=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Fy(t){let e=LP.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&&NP(r)?29:jP[n])}function Od(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Ad=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Cd(t){return function(r){let n=Ad.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],l=n[5]==="-"?-1:1,d=+(n[6]||0),p=+(n[7]||0);if(d>23||p>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let f=s-p*l,_=o-d*l-(f<0?1:0);return(_===23||_===-1)&&(f===59||f===-1)&&i<61}}function Nd(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 Hy(t,e){if(!(t&&e))return;let r=Ad.exec(t),n=Ad.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 Id=/t|\s/i;function qy(t){let e=Cd(t);return function(n){let o=n.split(Id);return o.length===2&&Fy(o[0])&&e(o[1])}}function Ky(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function Vy(t,e){if(!(t&&e))return;let[r,n]=t.split(Id),[o,s]=e.split(Id),i=Od(r,o);if(i!==void 0)return i||Nd(n,s)}var DP=/\/|:/,UP=/^(?:[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 MP(t){return DP.test(t)&&UP.test(t)}var zy=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function qP(t){return zy.lastIndex=0,zy.test(t)}var zP=-(2**31),BP=2**31-1;function FP(t){return Number.isInteger(t)&&t<=BP&&t>=zP}function HP(t){return Number.isInteger(t)}function By(){return!0}var KP=/[^\\]\\Z/;function VP(t){if(KP.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Wy=U(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.formatLimitDefinition=void 0;var GP=Pd(),kt=re(),lr=kt.operators,Ti={formatMaximum:{okStr:"<=",ok:lr.LTE,fail:lr.GT},formatMinimum:{okStr:">=",ok:lr.GTE,fail:lr.LT},formatExclusiveMaximum:{okStr:"<",ok:lr.LT,fail:lr.GTE},formatExclusiveMinimum:{okStr:">",ok:lr.GT,fail:lr.LTE}},WP={message:({keyword:t,schemaCode:e})=>(0,kt.str)`should be ${Ti[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,kt._)`{comparison: ${Ti[t].okStr}, limit: ${e}}`};pn.formatLimitDefinition={keyword:Object.keys(Ti),type:"string",schemaType:"string",$data:!0,error:WP,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 GP.KeywordCxt(s,a.RULES.all.format.definition,"format");l.$data?d():p();function d(){let _=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),y=e.const("fmt",(0,kt._)`${_}[${l.schemaCode}]`);t.fail$data((0,kt.or)((0,kt._)`typeof ${y} != "object"`,(0,kt._)`${y} instanceof RegExp`,(0,kt._)`typeof ${y}.compare != "function"`,f(y)))}function p(){let _=l.schema,y=a.formats[_];if(!y||y===!0)return;if(typeof y!="object"||y instanceof RegExp||typeof y.compare!="function")throw new Error(`"${o}": format "${_}" does not define "compare" function`);let k=e.scopeValue("formats",{key:_,ref:y,code:i.code.formats?(0,kt._)`${i.code.formats}${(0,kt.getProperty)(_)}`:void 0});t.fail$data(f(k))}function f(_){return(0,kt._)`${_}.compare(${r}, ${n}) ${Ti[o].fail} 0`}},dependencies:["format"]};var JP=t=>(t.addKeyword(pn.formatLimitDefinition),t);pn.default=JP});var Zy=U((So,Xy)=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});var hn=Gy(),YP=Wy(),Ld=re(),Jy=new Ld.Name("fullFormats"),XP=new Ld.Name("fastFormats"),jd=(t,e={keywords:!0})=>{if(Array.isArray(e))return Yy(t,e,hn.fullFormats,Jy),t;let[r,n]=e.mode==="fast"?[hn.fastFormats,XP]:[hn.fullFormats,Jy],o=e.formats||hn.formatNames;return Yy(t,o,r,n),e.keywords&&(0,YP.default)(t),t};jd.get=(t,e="full")=>{let n=(e==="fast"?hn.fastFormats:hn.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Yy(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Ld._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}Xy.exports=So=jd;Object.defineProperty(So,"__esModule",{value:!0});So.default=jd});function ZP(){let t=new Qy.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,eb.default)(t),t}var Qy,eb,xi,tb=j(()=>{Qy=Xd(Pd(),1),eb=Xd(Zy(),1);xi=class{constructor(e){this._ajv=e??ZP()}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 Ri,rb=j(()=>{Jr();Ri=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(p=>p.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,l=a?Array.isArray(a.content)?a.content:[a.content]:[],d=l.some(p=>p.type==="tool_use");if(i){if(s.some(p=>p.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!d)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(d){let p=new Set(l.filter(_=>_.type==="tool_use").map(_=>_.id)),f=new Set(s.filter(_=>_.type==="tool_result").map(_=>_.toolUseId));if(p.size!==f.size||![...p].every(_=>f.has(_)))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},Hn,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},Wr,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 nb(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 ob(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 sb=j(()=>{});var $i,ib=j(()=>{cf();Jr();tb();Nn();rb();sb();$i=class extends Bs{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Fn.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 xi,this.setRequestHandler(Ya,n=>this._oninitialize(n)),this.setNotificationHandler(Xa,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(ol,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Fn.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ri(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=lf(this._capabilities,e)}setRequestHandler(e,r){let o=Xt(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Fr(o);if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(l,d)=>{let p=Yt(Gr,l);if(!p.success){let k=p.error instanceof Error?p.error.message:String(p.error);throw new z(K.InvalidParams,`Invalid tools/call request: ${k}`)}let{params:f}=p.data,_=await Promise.resolve(r(l,d));if(f.task){let k=Yt(Kr,_);if(!k.success){let R=k.error instanceof Error?k.error.message:String(k.error);throw new z(K.InvalidParams,`Invalid task creation result: ${R}`)}return k.data}let y=Yt(As,_);if(!y.success){let k=y.error instanceof Error?y.error.message:String(y.error);throw new z(K.InvalidParams,`Invalid tools/call result: ${k}`)}return y.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){ob(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&nb(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:im.includes(r)?r:Ka,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"},ms)}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(d=>d.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],l=a.some(d=>d.type==="tool_use");if(s){if(o.some(d=>d.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let d=new Set(a.filter(f=>f.type==="tool_use").map(f=>f.id)),p=new Set(o.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(d.size!==p.size||![...d].every(f=>p.has(f)))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},sl,r):this.request({method:"sampling/createMessage",params:e},Hn,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},Wr,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},Wr,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(K.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof z?i:new z(K.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},il,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 Dd(t){return!!t&&typeof t=="object"&&lb in t}function cb(t){return t[lb]?.complete}var lb,ab,db=j(()=>{lb=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(ab||(ab={}))});var ub=j(()=>{});function eA(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"),!QP.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 tA(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 Ud(t){let e=eA(t);return tA(t,e.warnings),e.isValid}var QP,pb=j(()=>{QP=/^[A-Za-z0-9._-]{1,128}$/});var Ei,hb=j(()=>{Ei=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 rA}from"zod";function gb(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function yb(t){return"_def"in t||"_zod"in t||gb(t)}function Md(t){return typeof t!="object"||t===null||yb(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(gb)}function mb(t){if(t){if(Md(t))return yr(t);if(!yb(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function oA(t){let e=Xt(t);return e?Object.entries(e).map(([r,n])=>{let o=om(n),s=sm(n);return{name:r,description:o,required:!s}}):[]}function cr(t){let r=Xt(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Fr(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function fb(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Pi,nA,ko,bb=j(()=>{ib();Nn();Fl();Jr();db();ub();pb();hb();Pi=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 $i(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Ei(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(cr(Ps)),this.server.assertCanSetRequestHandler(cr(Gr)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ps,()=>({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=Br(r.inputSchema);return o?ql(o,{strictUnions:!0,pipeStrategy:"input"}):nA})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Br(r.outputSchema);o&&(n.outputSchema=ql(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Gr,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new z(K.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new z(K.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(K.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new z(K.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===K.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=Br(e.inputSchema)??e.inputSchema,i=await cs(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",l=ds(a);throw new z(K.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(K.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Br(e.outputSchema),s=await cs(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=ds(i);throw new z(K.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,d=a.task,p=d.pollInterval??5e3;for(;d.status!=="completed"&&d.status!=="failed"&&d.status!=="cancelled";){await new Promise(_=>setTimeout(_,p));let f=await n.taskStore.getTask(l);if(!f)throw new z(K.InternalError,`Task ${l} not found during polling`);d=f}return await n.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(cr(Cs)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Cs,async e=>{switch(e.params.ref.type){case"ref/prompt":return Sm(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return km(e),this.handleResourceCompletion(e,e.params.ref);default:throw new z(K.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(K.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new z(K.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return ko;let s=Xt(n.argsSchema)?.[e.params.argument.name];if(!Dd(s))return ko;let i=cb(s);if(!i)return ko;let a=await i(e.params.argument.value,e.params.context);return fb(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 ko;throw new z(K.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return ko;let s=await o(e.params.argument.value,e.params.context);return fb(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(cr(Ts)),this.server.assertCanSetRequestHandler(cr(xs)),this.server.assertCanSetRequestHandler(cr(Rs)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ts,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(xs,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Rs,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new z(K.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(K.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(cr($s)),this.server.assertCanSetRequestHandler(cr(Es)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler($s,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?oA(r.argsSchema):void 0}))})),this.server.setRequestHandler(Es,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new z(K.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new z(K.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Br(n.argsSchema),s=await cs(o,e.params.arguments);if(!s.success){let l="error"in s?s.error:"Unknown error",d=ds(l);throw new z(K.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${d}`)}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:d=>{typeof d.name<"u"&&d.name!==e&&(delete this._registeredResourceTemplates[e],d.name&&(this._registeredResourceTemplates[d.name]=i)),typeof d.title<"u"&&(i.title=d.title),typeof d.template<"u"&&(i.resourceTemplate=d.template),typeof d.metadata<"u"&&(i.metadata=d.metadata),typeof d.callback<"u"&&(i.readCallback=d.callback),typeof d.enabled<"u"&&(i.enabled=d.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(d=>!!n.completeCallback(d))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:yr(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=yr(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 d=l instanceof rA?l._def?.innerType:l;return Dd(d)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,l,d){Ud(e);let p={title:r,description:n,inputSchema:mb(o),outputSchema:mb(s),annotations:i,execution:a,_meta:l,handler:d,enabled:!0,disable:()=>p.update({enabled:!1}),enable:()=>p.update({enabled:!0}),remove:()=>p.update({name:null}),update:f=>{typeof f.name<"u"&&f.name!==e&&(typeof f.name=="string"&&Ud(f.name),delete this._registeredTools[e],f.name&&(this._registeredTools[f.name]=p)),typeof f.title<"u"&&(p.title=f.title),typeof f.description<"u"&&(p.description=f.description),typeof f.paramsSchema<"u"&&(p.inputSchema=yr(f.paramsSchema)),typeof f.outputSchema<"u"&&(p.outputSchema=yr(f.outputSchema)),typeof f.callback<"u"&&(p.handler=f.callback),typeof f.annotations<"u"&&(p.annotations=f.annotations),typeof f._meta<"u"&&(p._meta=f._meta),typeof f.enabled<"u"&&(p.enabled=f.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=p,this.setToolRequestHandlers(),this.sendToolListChanged(),p}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let l=r[0];if(Md(l))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Md(r[0])&&(i=r.shift());else if(typeof l=="object"&&l!==null){if(Object.values(l).some(d=>typeof d=="object"&&d!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,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:d}=r;return this._createRegisteredTool(e,o,s,i,a,l,{taskSupport:"forbidden"},d,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let 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()}},nA={type:"object",properties:{}};ko={completion:{values:[],hasMore:!1}}});function iA(t){return mm.parse(JSON.parse(t))}function wb(t){return JSON.stringify(t)+`
2014
2014
  `}var sA,Ai,vb=j(()=>{Jr();sA=10*1024*1024,Ai=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??sA}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(`
2015
- `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),iA(r)}clear(){this._buffer=void 0}}});import _b from"node:process";var Ci,Sb=j(()=>{vb();Ci=class{constructor(e=_b.stdin,r=_b.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 Ai({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=wb(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var kb,Tb=j(()=>{kb=[]});var Ob={};Yd(Ob,{AUTHORING_MCP_SERVER_NAME:()=>Eb,AUTHORING_MCP_SERVER_VERSION:()=>Pb,AUTHORING_RESOURCES:()=>mA,AUTHORING_TOOLS:()=>pA,AUTHORING_TOOLS_PUBLIC:()=>Ib,buildAuthoringMcpServer:()=>Cb,resolveSamplesDir:()=>Ab,runAuthoringMcpServer:()=>hA});import{promises as aA}from"node:fs";import{isAbsolute as lA,resolve as Ii,sep as cA}from"node:path";import{z as M}from"zod";function $b(){return Rb??=import("../mcp/grounding.js").then(e=>e,()=>null),Rb}function Ab(t,e){if(e===void 0)return Ii(process.cwd(),t??"samples");let r=Ii(e);if(t===void 0)return r;if(lA(t))return null;let n=Ii(r,t);return n===r||n.startsWith(r+cA)?n:null}function Te(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function uA(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 Cb(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let y=await mt(t.baseUrl);if(!y)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:y.baseUrl,token:y.token}}let r=t.grounding??{},n=await $b(),o=null;if(n)try{let y=await e();o={surface:"mcp-authoring",baseUrl:y.baseUrl,token:y.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(y=>({id:y.id,record_type:y.record_type,intent:y.intent}))}catch{l=[]}}let d=o?await uA(o,r):null,p=new Pi({name:Eb,version:Pb},n?{instructions:n.renderAuthoringInstructions({baseUrl:t.displayBaseUrl??o?.baseUrl??t.baseUrl??"this instance",sources:s,recipeIntents:l,promptNames:a.map(y=>y.id),deployedExtensions:d,docsToken:r.docsToken??n.docsPublicToken()})}:void 0);if(n&&o){let y=o;for(let k of a)p.registerPrompt(k.id,{title:k.name,description:k.description},async()=>{let R=await n.getMcpPromptSkill(y,k.id,r);if(!R)throw new Error(`unknown prompt: ${k.id}`);return{description:R.description,messages:[{role:"user",content:{type:"text",text:(R.prompts??[]).join(`
2015
+ `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),iA(r)}clear(){this._buffer=void 0}}});import _b from"node:process";var Ci,Sb=j(()=>{vb();Ci=class{constructor(e=_b.stdin,r=_b.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 Ai({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=wb(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var kb,Tb=j(()=>{kb=[]});var Ob={};Yd(Ob,{AUTHORING_MCP_SERVER_NAME:()=>Eb,AUTHORING_MCP_SERVER_VERSION:()=>Pb,AUTHORING_RESOURCES:()=>hA,AUTHORING_TOOLS:()=>pA,AUTHORING_TOOLS_PUBLIC:()=>Ib,buildAuthoringMcpServer:()=>Cb,resolveSamplesDir:()=>Ab,runAuthoringMcpServer:()=>mA});import{promises as aA}from"node:fs";import{isAbsolute as lA,resolve as Ii,sep as cA}from"node:path";import{z as M}from"zod";function $b(){return Rb??=import("../mcp/grounding.js").then(e=>e,()=>null),Rb}function Ab(t,e){if(e===void 0)return Ii(process.cwd(),t??"samples");let r=Ii(e);if(t===void 0)return r;if(lA(t))return null;let n=Ii(r,t);return n===r||n.startsWith(r+cA)?n:null}function Te(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function uA(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 Cb(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let y=await ht(t.baseUrl);if(!y)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:y.baseUrl,token:y.token}}let r=t.grounding??{},n=await $b(),o=null;if(n)try{let y=await e();o={surface:"mcp-authoring",baseUrl:y.baseUrl,token:y.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(y=>({id:y.id,record_type:y.record_type,intent:y.intent}))}catch{l=[]}}let d=o?await uA(o,r):null,p=new Pi({name:Eb,version:Pb},n?{instructions:n.renderAuthoringInstructions({baseUrl:t.displayBaseUrl??o?.baseUrl??t.baseUrl??"this instance",sources:s,recipeIntents:l,promptNames:a.map(y=>y.id),deployedExtensions:d,docsToken:r.docsToken??n.docsPublicToken()})}:void 0);if(n&&o){let y=o;for(let k of a)p.registerPrompt(k.id,{title:k.name,description:k.description},async()=>{let R=await n.getMcpPromptSkill(y,k.id,r);if(!R)throw new Error(`unknown prompt: ${k.id}`);return{description:R.description,messages:[{role:"user",content:{type:"text",text:(R.prompts??[]).join(`
2016
2016
 
2017
- `)}}]}})}p.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:y,token:k}=await e(),R=await fetch(`${y}/v1/catalog/records`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}});if(!R.ok)throw new Error(`catalog fetch failed: ${R.status}`);return Te(await R.json())}),p.registerTool("record_anatomy",{title:"Record anatomy + display contract",description:"Fetch ONE record type in depth (/v1/catalog/records/:type): anatomy markdown (field meanings, sublists, gotchas, relations), authored recipe display contracts (columns/labels/formats), semantic column metadata and the record's plain-English description. Read this BEFORE building UI over a record \u2014 column names alone routinely mislead (e.g. tran_id is the human-facing document number, entity_id has a display twin entity_name). Also reports `unpopulatedColumns`: columns that EXIST but carry no value in any sampled row on this instance (currency_name is the classic \u2014 currency_id holds the data). Rendering one of those produces a blank column while faithfully following the display contract, so check it before choosing what to show. And reports `lines`: the record's LINE tables with their columns, including line-level custom fields (custcol_*). Check the lines before concluding a link is absent \u2014 a transaction routinely carries a reference on its LINES while the header field is NULL, and reading only the header reports a real link as missing.",inputSchema:{recordType:M.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:M.string().optional().describe('Which connector publishes this recordType, e.g. "netsuite" or "stripe". 29 record types are published by more than one source ("customer" by six) and each is a different shape behind the same name. Omit it and the catalog collapse rule picks one; the answer names its choice in `source`.')}},async({recordType:y,source:k})=>{let{baseUrl:R,token:$}=await e(),P=k?`?source=${encodeURIComponent(k)}`:"",I=await fetch(`${R}/v1/catalog/records/${encodeURIComponent(y)}${P}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(I.status===404)throw new Error(`unknown record type "${y}" \u2014 list them with catalog_get.`);if(!I.ok)throw new Error(`record anatomy fetch failed: ${I.status}`);return Te(await I.json())}),p.registerTool("common_columns",{title:"Columns common to several record types",description:"Given SEVERAL record types, return the columns present on ALL of them (safe to select in one shared query shape) and the columns present on only some, with exactly which types lack each. Use this BEFORE writing a query that spans record types \u2014 transaction tables are NOT uniform (memo, total, created_from_id and even pg_row_id are missing from some), and PostgREST rejects an unknown column with 42703 and fails the ENTIRE request, so one wrong name loses the whole table rather than one field. Record types the caller cannot read come back in unknownRecordTypes \u2014 if that is non-empty the intersection covers fewer types than you asked for.",inputSchema:{recordTypes:M.array(M.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:M.string().optional().describe("Pin every requested type to ONE connector, e.g. \"netsuite\". Without it each name collapses by the catalog rule, so an intersection can silently mix two sources' tables for the same name. The response's `resolvedSources` names what it used.")}},async({recordTypes:y,source:k})=>{let{baseUrl:R,token:$}=await e(),P=new URLSearchParams({types:y.join(",")});k&&P.set("source",k);let I=await fetch(`${R}/v1/catalog/columns?${P}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(I.status===404)throw new Error(`none of those record types resolved: ${y.join(", ")} \u2014 list them with catalog_get.`);if(!I.ok)throw new Error(`common columns fetch failed: ${I.status}`);return Te(await I.json())}),p.registerTool("catalog_census",{title:"Count the customer's customizations",description:'Count the whole customization catalog: every object by kind AND by whether it can be changed (editable / partner_owned / turbobase_managed / unknown), plus which classes were never collected and why. Call this BEFORE search_catalog when the question is "how much is there" / "what is this account made of" / "how much of this is even ours to change". Takes no arguments.',inputSchema:{}},async()=>{let{baseUrl:y,token:k}=await e(),R=await fetch(`${y}/v1/catalog/census`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}});if(!R.ok)throw new Error(`catalog census failed: ${R.status}`);return Te(await R.json())}),p.registerTool("search_catalog",{title:"Search the customization catalog",description:'Survey the customer\'s customization catalog by free text \u2014 scripts, custom records, fields, lists, workflows, roles, saved searches, and installed bundles. Matches ids, names AND the generated plain-English explanations, so ask what you actually want ("which object handles rebates?"), not just an exact id. Returns compact {kind, externalId, name, summary, modifiability} hits plus the TRUE match total, so you can see when the page truncated; pass a hit to explain_object for the full definition + prose. A `partner_owned` object CANNOT be edited by this account however well you understand it \u2014 check that before planning a change. Search this before building over a custom record: its definition and explanation are the spec.',inputSchema:{query:M.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:M.enum(xb).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:M.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:y,kind:k,limit:R})=>{let{baseUrl:$,token:P}=await e(),I=new URLSearchParams({q:y});k&&I.set("kind",k),R!==void 0&&I.set("limit",String(R));let D=await fetch(`${$}/v1/catalog/objects?${I}`,{headers:{Authorization:`Bearer ${P}`,Accept:"application/json"}});if(!D.ok)throw new Error(`catalog object search failed: ${D.status}`);return Te(await D.json())}),p.registerTool("explain_object",{title:"Explain one catalog object",description:"Fetch ONE customization-catalog object in depth: its captured definition (or script source, or a bundle\u2019s membership), human label, the generated plain-English explanation (tldr + markdown) of what it is for, and its OWNERSHIP \u2014 `modifiability` plus a one-line reason saying whether this account can change it at all. Address it by the {kind, externalId} a search_catalog hit returns. For a FIELD it also reports `selectTarget`: where a List/Record field ACTUALLY points, resolved to a mirrored table plus the filter needed to read it correctly. Do not infer a target from the field name \u2014 a carrier-named field can point at `entity` (vendors), and building on the wrong guess resolves nothing while looking like an empty table.",inputSchema:{kind:M.enum(xb),externalId:M.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:y,externalId:k})=>{let{baseUrl:R,token:$}=await e(),P=await fetch(`${R}/v1/catalog/objects/${encodeURIComponent(y)}/${encodeURIComponent(k)}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown object ${y}:${k} \u2014 find it with search_catalog.`);if(!P.ok)throw new Error(`catalog object fetch failed: ${P.status}`);return Te(await P.json())}),p.registerTool("search_documentation",{title:"Search the knowledge base",description:'Search this instance\'s published knowledge base \u2014 internal documentation: processes, policies, playbooks, how-tos. Route questions about how the ORGANISATION works here ("what\'s our receiving process", "how do we handle returns"), and ALWAYS search it before building UI over a custom record \u2014 the KB is the only spec a custom record has. Returns up to `limit` {slug, title, snippet} hits; pass a slug to read_document for the full text. Published release only \u2014 drafts are never returned.',inputSchema:{query:M.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:M.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:y,limit:k})=>{let{baseUrl:R,token:$}=await e(),P=new URLSearchParams({q:y});k!==void 0&&P.set("limit",String(k));let I=await fetch(`${R}/v1/kb/search?${P}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(!I.ok)throw new Error(`kb search failed: ${I.status}`);return Te(await I.json())}),p.registerTool("read_document",{title:"Read a knowledge-base document",description:"Read one published knowledge-base document in full by its slug (from a search_documentation hit). Returns {found, slug, title, body_markdown}. Published release only \u2014 unpublished / admin-only drafts are never returned.",inputSchema:{slug:M.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:y})=>{let{baseUrl:k,token:R}=await e(),$=await fetch(`${k}/v1/kb/document/${encodeURIComponent(y)}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(!$.ok&&$.status!==404)throw new Error(`kb document fetch failed: ${$.status}`);return Te(await $.json())}),p.registerTool("generate_types",{title:"Generate types.ts",description:"Generate the instance's types.ts (record shapes + PostgREST ops). Returns the source.",inputSchema:{recordsOnly:M.boolean().optional()}},async({recordsOnly:y})=>{let{baseUrl:k,token:R}=await e();return{content:[{type:"text",text:await mr({baseUrl:k,token:R,recordsOnly:y})}]}}),p.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:M.string(),event:M.string().optional(),template:M.enum(["require-field","enforce-format","blank"]).optional(),field:M.string().optional(),regex:M.string().optional(),source:M.string().optional(),id:M.string().optional()}},async y=>{let k=Rt("hook",{recordType:y.recordType,event:y.event,template:y.template,field:y.field,regex:y.regex,source:y.source,id:y.id});return Te({path:k.relativePath,content:k.content})}),p.registerTool("scaffold_conduit",{title:"Scaffold a conduit",description:"Generate a conduit file body that bridges a canonical record from one source into another (does not write to disk; returns path + content).",inputSchema:{source:M.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:M.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:M.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:M.string().optional().describe("Target record type (defaults to the trigger record type)."),event:M.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:M.string().optional()}},async y=>{let k=Rt("conduit",{recordType:y.recordType,source:y.source,to:y.to,toRecordType:y.toRecordType,event:y.event,id:y.id});return Te({path:k.relativePath,content:k.content})}),p.registerTool("scaffold_process",{title:"Scaffold a process",description:"Generate a process file body \u2014 an ordered sequence of record writes an app invokes and the platform runs on the server (does not write to disk; returns path + content).",inputSchema:{recordType:M.string().describe('Record type the first step writes, e.g. "purchaseOrder".'),then:M.string().optional().describe('Record type of a second step that waits for the first, e.g. "vendorBill".'),onFailure:M.enum(["stop","rollback"]).optional().describe("What the engine does when a step fails (default stop)."),id:M.string().optional()}},async y=>{let k=Rt("process",{recordType:y.recordType,then:y.then,onFailure:y.onFailure,id:y.id});return Te({path:k.relativePath,content:k.content})}),p.registerTool("author_conduit",{title:"Draft and check a conduit",description:'Ask the instance to WRITE a conduit from a plain-English intent and check it before staging it for review \u2014 the cross-source counterpart to the hook the healing agent drafts. Returns {status, intentId, id?, reason?}: "written" staged a proposal, "rejected_by_validation" says why it could not (including a target system this instance can only read from). Nothing is deployed \u2014 an administrator applies the staged bridge from the Conduits tab. Prefer scaffold_conduit when you intend to write the transform yourself.',inputSchema:{intent:M.string().describe(`What the bridge should do, in the operator's words, e.g. "when a shopify order is paid, raise the matching NetSuite sales order".`),fromSource:M.string().describe('Origin source the record arrives from, e.g. "shopify".'),fromRecordType:M.string().describe('Canonical record type the bridge triggers on, e.g. "order".'),toSource:M.string().describe('Target source the bridge writes into, e.g. "netsuite".'),toRecordType:M.string().describe('Canonical record type written on the target, e.g. "salesOrder".'),intentId:M.string().optional().describe("Correlation id for the audit trail. The instance mints one when omitted."),columns:M.array(M.string()).optional().describe("Narrow the target columns the transform may write. Defaults to the target record's own.")}},async y=>{let{baseUrl:k,token:R}=await e(),$=new q({baseUrl:k,token:R});return Te(await $.authorConduit({intent:y.intent,from:{source:y.fromSource,recordType:y.fromRecordType},to:{source:y.toSource,recordType:y.toRecordType},...y.intentId?{intentId:y.intentId}:{},...y.columns?.length?{columns:y.columns}:{}}))}),p.registerTool("mock_test",{title:"Dry-run an extension against samples",description:"Bundle the given source through the production sandbox and run it against samples/ fixtures.",inputSchema:{source:M.string().describe("The extension TS source."),samplesDir:M.string().optional().describe('Samples directory (default "samples").')}},async({source:y,samplesDir:k})=>{let R=Ab(k,t.samplesRoot);if(R===null)return{content:[{type:"text",text:JSON.stringify({error:"samples_dir_refused",message:dA})}],isError:!0};let $;try{$=await _n(R)}catch(D){if(t.samplesRoot!==void 0)return{content:[{type:"text",text:JSON.stringify({error:"samples_unreadable",message:"the samples directory could not be read"})}],isError:!0};throw D}let P=await Ho(y,$.map(D=>D.fixture)),I=P.filter(D=>!D.pass).length;return Te({total:P.length,passed:P.length-I,results:P})}),p.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:M.string(),recordType:M.string(),event:M.string(),source:M.string().describe('Adapter id or "standalone".'),sourceCode:M.string().describe("The verbatim extension TS."),extensionKind:M.string().optional()}},async y=>{let{baseUrl:k,token:R}=await e(),P=await new q({baseUrl:k,token:R}).deploy({id:y.id,recordType:y.recordType,event:y.event,source:y.source,sourceCode:y.sourceCode,extensionKind:y.extensionKind});return Te(P)}),p.registerTool("tail_logs",{title:"Tail an extension's logs",description:"Read an extension's log ring buffer (GET /v1/extensions/:id/logs).",inputSchema:{id:M.string(),limit:M.number().int().positive().optional()}},async({id:y,limit:k})=>{let{baseUrl:R,token:$}=await e(),P=new q({baseUrl:R,token:$});return Te({id:y,logs:await P.logs(y,k)})}),p.registerTool("apps_list",{title:"List hosted apps",description:"Every hosted app on this instance with its slug, whether it's deployed, and its latest source revision. `sourceRev: null` means the app has no source of record yet (deployed dist only) \u2014 pull will 404 until something is pushed. GET /v1/apps.",inputSchema:{}},async()=>{let{baseUrl:y,token:k}=await e(),R=new q({baseUrl:y,token:k});return Te(await R.appsList())}),p.registerTool("apps_create",{title:"Create a hosted app",description:"Create a bare hosted-app row so source can be pushed and a build shipped to it \u2014 the author-led path that needs no proposal. Creates the registration only; it serves nothing until a build is shipped. POST /v1/apps.",inputSchema:{slug:M.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:M.string().optional().describe("Display name (defaults to the slug)."),description:M.string().optional().describe("Short description.")}},async({slug:y,name:k,description:R})=>{let{baseUrl:$,token:P}=await e(),I=new q({baseUrl:$,token:P});return Te(await I.appsCreate({slug:y,name:k,description:R}))}),p.registerTool("apps_pull",{title:"Pull a hosted app's source",description:"Fetch the app's latest source tree as {path \u2192 contents} READ-ONLY \u2014 write it to disk, refine it, then apps_push it back. Returns 404 when the app has no source revision yet. NEVER deploys. GET /v1/apps/:id/pull.",inputSchema:{app:M.string().describe("App slug or id.")}},async({app:y})=>{let{baseUrl:k,token:R}=await e(),$=new q({baseUrl:k,token:R});return Te(await $.appsPull(y))}),p.registerTool("apps_push",{title:"Push a hosted app's source",description:"Record an edited source tree as the app's NEW source revision, so the instance holds the source of record rather than one laptop. Send the whole tree ({path \u2192 contents}, relative POSIX paths, no node_modules/dist/.git). SOURCE ONLY \u2014 this does not build and does not change what is live; run `turbobase apps deploy <slug>` for that. POST /v1/apps/:id/push.",inputSchema:{app:M.string().describe("App slug or id."),files:M.record(M.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:M.string().optional().describe("Short note stored with the revision.")}},async({app:y,files:k,note:R})=>{let{baseUrl:$,token:P}=await e(),I=new q({baseUrl:$,token:P});return Te(await I.appsPush(y,k,{note:R}))});let f=M.object({name:M.string().describe("Field name (lowercase identifier)."),type:M.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:M.boolean().optional()}),_=M.object({slug:M.string().describe("Table slug; the physical table is cr_<slug>."),displayName:M.string().optional(),fields:M.array(f).describe("At least one field."),rowLevelOwner:M.boolean().optional().describe("Restrict non-admins to rows they created.")});return p.registerTool("tables_list",{title:"List custom tables",description:"The instance's customer-authored tables, their fields, and which apps claim each one. Read the `column` on each field \u2014 that is the actual Postgres column an app SELECTs (cf_sa_<name>), which is not the same string as the field name. GET /v1/tables.",inputSchema:{}},async()=>{let{baseUrl:y,token:k}=await e(),R=new q({baseUrl:y,token:k});return Te(await R.tablesList())}),p.registerTool("tables_plan",{title:"Preview a table declaration",description:"What these table declarations WOULD do, without doing it. Several apps may claim one table and the instance merges their declarations, so this reports the merged shape and \u2014 the reason to call it \u2014 fails with a conflict report when another claimant already declares one of your field names at a different type. Writes NOTHING. POST /v1/tables/plan.",inputSchema:{tables:M.array(_),claimedBy:M.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:y,claimedBy:k})=>{let{baseUrl:R,token:$}=await e(),P=new q({baseUrl:R,token:$});return Te(await P.tablesPlan({tables:y,claimedBy:k}))}),p.registerTool("tables_apply",{title:"Create or evolve custom tables",description:"Record these table declarations and reconcile them into real Postgres tables \u2014 RLS, realtime, and the write path included. Additive: an existing table gains the fields you declare and keeps the ones other claimants declared. Never drops a column, so removing a field from your declaration releases your claim on it rather than deleting data. Prefer declaring tables in the app manifest (public/turbobase.json) so the deploy applies them; use this when authoring outside an app. POST /v1/tables/apply.",inputSchema:{tables:M.array(_),claimedBy:M.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:y,claimedBy:k})=>{let{baseUrl:R,token:$}=await e(),P=new q({baseUrl:R,token:$});return Te(await P.tablesApply({tables:y,claimedBy:k}))}),p.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async y=>{let{baseUrl:k,token:R}=await e(),P=await(await fetch(`${k}/v1/catalog/records`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}})).text();return{contents:[{uri:y.href,mimeType:"application/json",text:P}]}}),p.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async y=>{let{baseUrl:k,token:R}=await e(),$=await mr({baseUrl:k,token:R});return{contents:[{uri:y.href,mimeType:"text/plain",text:$}]}}),p.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async y=>{let k=Ii(process.cwd(),"samples"),R=[];try{R=(await aA.readdir(k)).filter(P=>P.endsWith(".json"))}catch{R=[]}let $=await _n(k);return{contents:[{uri:y.href,mimeType:"application/json",text:JSON.stringify({files:R,samples:$.map(P=>P.fixture)},null,2)}]}}),p.registerResource("recipes","recipes:///",{title:"Intent recipes",description:"Intent recipes (columns / stats / actions per record type + intent), filtered to the instance's installed sources.",mimeType:"application/json"},async y=>{let k=await $b(),R=[];if(k){let{baseUrl:$,token:P}=await e();R=await k.listRecipesForSurface({surface:"mcp-authoring",baseUrl:$,token:P},r)}return{contents:[{uri:y.href,mimeType:"application/json",text:JSON.stringify({recipes:R})}]}}),p}async function hA(t={}){let e=await Cb(t),r=new Ci;await e.connect(r)}var xb,Rb,Eb,Pb,dA,Ib,pA,mA,Nb=j(()=>{bb();Sb();Zi();bn();ht();ca();Jo();Tb();xb=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];Eb="turbobase-authoring",Pb="0.1.0";dA="samplesDir must be a relative path inside the samples directory this server serves; absolute paths and paths that leave it are refused over the network.";Ib=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","search_catalog","catalog_census","explain_object","generate_types","scaffold_hook","scaffold_conduit","scaffold_process","author_conduit","mock_test","deploy","tail_logs","apps_list","apps_create","apps_pull","apps_push","tables_list","tables_plan","tables_apply"],pA=[...Ib,...kb],mA=["catalog:///","types://all","samples:///","recipes:///"]});Zi();bn();ht();ca();import{spawn as Kd}from"node:child_process";import{promises as ae}from"node:fs";import{homedir as fA}from"node:os";import{basename as Db,dirname as zt,join as et,relative as Ni,resolve as se,sep as Hd}from"node:path";import{Command as gA}from"commander";Fo();import{promises as Du}from"node:fs";var qw=/^[a-z][a-z0-9_]+$/;function Iu(t,e){if(typeof t!="string"||!qw.test(t))throw new Error(`${e} ${JSON.stringify(t)} must match /^[a-z][a-z0-9_]+$/ (NS scriptid form). This restriction is what lets reconcile safely splice it as a SQL identifier; refusing to emit DDL.`);return t}var zw="customrecord",Bw="customlist";function Fw(t){return t.startsWith("customrecord_")?t.slice(13):t}function Hw(t){return t.startsWith("customlist_")?t.slice(11):t}function Kw(t){return Iu(t,"custom_record scriptId"),`cr_${Fw(t)}`}function Vw(t){return Iu(t,"custom_list scriptId"),`cl_${Hw(t)}`}function Ou(t){return t.startsWith(zw)?Kw(t):t.startsWith(Bw)?Vw(t):null}var Gw={salesOrder:{table:"order"},invoice:{table:"invoice"},itemFulfillment:{table:"order_fulfillment"},customerPayment:{table:"customer_payment"},cashSale:{table:"cash_sale"},cashRefund:{table:"cash_refund"},opportunity:{table:"opportunity"},estimate:{table:"estimate"},customerDeposit:{table:"customer_deposit"},creditMemo:{table:"credit_memo"},customer:{table:"entity",typeColumn:"entity_type",typeValue:"customer"},vendor:{table:"entity",typeColumn:"entity_type",typeValue:"vendor"},contact:{table:"entity",typeColumn:"entity_type",typeValue:"contact"},employee:{table:"entity",typeColumn:"entity_type",typeValue:"employee"},partner:{table:"entity",typeColumn:"entity_type",typeValue:"partner"},inventoryItem:{table:"item",typeColumn:"item_type",typeValue:"inventoryItem"},serviceSaleItem:{table:"item",typeColumn:"item_type",typeValue:"serviceSaleItem"},nonInventoryResaleItem:{table:"item",typeColumn:"item_type",typeValue:"nonInventoryResaleItem"},kitItem:{table:"item",typeColumn:"item_type",typeValue:"kitItem"},assemblyItem:{table:"item",typeColumn:"item_type",typeValue:"assemblyItem"},lotNumberedInventoryItem:{table:"item",typeColumn:"item_type",typeValue:"lotNumberedInventoryItem"},serializedInventoryItem:{table:"item",typeColumn:"item_type",typeValue:"serializedInventoryItem"},lotNumberedAssemblyItem:{table:"item",typeColumn:"item_type",typeValue:"lotNumberedAssemblyItem"},serializedAssemblyItem:{table:"item",typeColumn:"item_type",typeValue:"serializedAssemblyItem"},nonInventorySaleItem:{table:"item",typeColumn:"item_type",typeValue:"nonInventorySaleItem"},otherChargeSaleItem:{table:"item",typeColumn:"item_type",typeValue:"otherChargeSaleItem"},discountItem:{table:"item",typeColumn:"item_type",typeValue:"discountItem"},location:{table:"location"},department:{table:"department"},classification:{table:"classification"},vendorBill:{table:"vendor_bill"},vendorPayment:{table:"vendor_payment"},purchaseOrder:{table:"purchase_order"},journalEntry:{table:"journal_entry"},timeBill:{table:"time_bill"},expenseReport:{table:"expense_report"},itemReceipt:{table:"item_receipt"},vendorReturnAuthorization:{table:"vendor_return_authorization"},transferOrder:{table:"transfer_order"},check:{table:"check"},customerRefund:{table:"customer_refund"},project:{table:"project"},projectTask:{table:"work_item",typeColumn:"item_type",typeValue:"project_task"},supportCase:{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},caseMessage:{table:"activity",typeColumn:"activity_type",typeValue:"case_message_outgoing",alsoAddresses:["case_message_incoming"]},shippingItem:{table:"shipping_item"},unitsType:{table:"units_type"},returnAuthorization:{table:"return_authorization"},inventoryAdjustment:{table:"inventory_adjustment"},vendorCredit:{table:"vendor_credit"},deposit:{table:"deposit"},account:{table:"account"},channel_message:{table:"activity",typeColumn:"activity_type",typeValue:"message"},social_post:{table:"activity",typeColumn:"activity_type",typeValue:"social_post"},reaction:{table:"reaction"},esignSubmission:{table:"esign_submission"},esignSubmitter:{table:"esign_submitter"},workflow_run:{table:"automation_run"},printer:{table:"printer"},printJob:{table:"print_job"},label:{table:"label"},call:{table:"activity",typeColumn:"activity_type",typeValue:"call"},quote:{table:"estimate"},tag:{table:"label"},request:{table:"request"}};function Nu(t,e){let r=e?Jw[`${e}:${t}`]:void 0;if(r)return r;let n=Gw[t];if(n)return n;let o=Ou(t);return o?{table:o}:void 0}var Ww={accountingPeriod:"accounting_period"};var Jw={...Object.fromEntries(Object.entries(Ww).map(([t,e])=>[`standalone:${t}`,{table:e}])),"google_workspace:doc":{table:"memory_document",typeColumn:"kind",typeValue:"doc"},"google_workspace:email":{table:"memory_document",typeColumn:"kind",typeValue:"email"},"google_workspace:file":{table:"memory_document",typeColumn:"kind",typeValue:"file"},"google_workspace:sheet":{table:"memory_document",typeColumn:"kind",typeValue:"sheet"},"google_workspace:slide":{table:"memory_document",typeColumn:"kind",typeValue:"slide"},"salesforce:account":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"salesforce:case":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"salesforce:lead":{table:"entity",typeColumn:"entity_type",typeValue:"lead"},"salesforce:task":{table:"activity",typeColumn:"activity_type",typeValue:"task"},"salesforce:event":{table:"activity",typeColumn:"activity_type",typeValue:"event"},"intercom:admin":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"intercom:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"hubspot:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"hubspot:owner":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"intercom:conversation":{table:"work_item",typeColumn:"item_type",typeValue:"conversation"},"intercom:ticket":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"github:issue":{table:"work_item",typeColumn:"item_type",typeValue:"issue"},"github:pull_request":{table:"work_item",typeColumn:"item_type",typeValue:"pull_request"},"github:comment":{table:"activity",typeColumn:"activity_type",typeValue:"comment"},"zendesk:organization":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"getsales:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"xero:supplier":{table:"entity",typeColumn:"entity_type",typeValue:"vendor"},"zoho_crm:account":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"zoho_crm:lead":{table:"entity",typeColumn:"entity_type",typeValue:"lead"},"zoho_crm:case":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"slack:user":{table:"entity",typeColumn:"entity_type",typeValue:"contact"},"slack:channel":{table:"channel"},"slack:reaction":{table:"reaction"},"quickbooks:bill":{table:"vendor_bill"},"quickbooks:payment":{table:"customer_payment"},"quickbooks:billPayment":{table:"vendor_payment"},"quickbooks:item":{table:"item"},"zoho_crm:task":{table:"activity",typeColumn:"activity_type",typeValue:"task"},"zoho_crm:event":{table:"activity",typeColumn:"activity_type",typeValue:"event"},"zoho_crm:product":{table:"item",typeColumn:"item_type",typeValue:"inventoryItem"},"xero:bill":{table:"vendor_bill"},"xero:billPayment":{table:"vendor_payment"},"xero:creditNote":{table:"credit_memo"},"xero:item":{table:"item"},"xero:manualJournal":{table:"journal_entry"},"xero:payment":{table:"customer_payment"},"xero:receiveMoney":{table:"deposit"},"xero:spendMoney":{table:"check"},"xero:supplierCreditNote":{table:"vendor_credit"},"azure_blob:file":{table:"source_file"}};function Lu(t,e){let r=Nu(t,e);return r?`${r.table}|${r.typeColumn??"-"}|${r.typeValue??"-"}`:void 0}function ju(t,e,r){if(e===t)return"same-type-merge";let n=r?.fromSource,o=r?.toSource;if(n&&o&&n!==o){let s=Lu(t,n),i=Lu(e,o);if(s!==void 0&&s===i)return"same-type-merge"}return"different-type-mint"}var Uu=4;function da(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=Ir(t,"id"),r=Ir(t,"on"),n=Ir(t,"source"),o=Ir(t,"recordType"),s=[];for(let l of t.matchAll(/\bto\s*:\s*\{([^}]*)\}/g)){let d=Ir(l[1]??"","source"),p=Ir(l[1]??"","recordType");d&&p&&s.push({source:d,recordType:p})}let i=s[0],a=/cycleBudget\s*:\s*(\d+)/.exec(t);if(!e||!n||!o||!i)throw new Error("could not parse id/from.{source,recordType}/to.{source,recordType} \u2014 is it a reference-shape defineConduit({...})?");return{id:e,on:r,fromSource:n,fromRecordType:o,toSource:i.source,toRecordType:i.recordType,targets:s,cycleBudget:a?Number(a[1]):Uu}}function Ir(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function Yw(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 Mu(t,e,r="fixture",n={}){let o=e.name??r,s=[],i;try{i=da(t)}catch(d){return{fixtureName:o,conduit:Zw(),guards:s,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],targets:[],logs:[],error:d instanceof Error?d.message:String(d)}}let a=Yw(e),l=Object.entries(e.atlasLinks??{}).map(([d,p])=>({key:d,resolved:p}));try{let d=await Bo(t,{resolveDir:n.resolveDir}),f=!!(await vn(d,a,{member:"when",timeoutMs:zo})).whenResult;s.push({name:"from.when",status:f?"passed":"failed",detail:f?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let _=e.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${_} vs cycleBudget=${i.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),s.push({name:"opposite-direction-loop",status:"skipped-offline",detail:"reads committed conduit_event rows for the reverse leg \u2014 requires live sandbox state (skipped in fixture mode)"}),s.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!f)return{fixtureName:o,conduit:i,guards:s,whenPassed:f,atlasResolutions:l,wouldWriteBindings:[],targets:[],logs:[]};let y=[],k=[],R=[];for(let P=0;P<i.targets.length;P+=1){let I=i.targets[P],D=await vn(d,{...a,materialized:R.map(Ft=>({...Ft}))},{member:"transform",stepIndex:P,timeoutMs:zo});y.push(...D.effects.logs);let Y=D.effects.result;if(!Y||typeof Y!="object")throw new Error(`conduit ${i.id} transform${i.targets.length>1?` (target ${P+1})`:""} returned no result (expected { patch, createdFrom? })`);let F=Y,Oe=ju(i.fromRecordType,I.recordType,{fromSource:i.fromSource,toSource:I.source}),{wouldWriteBindings:Ce,masterAction:Bt}=Xw(i,I,Oe,e);k.push({to:I,transformResult:F,applyBranch:Oe,wouldWriteBindings:Ce,masterAction:Bt}),R.push({source:I.source,recordType:I.recordType,masterTable:`<${I.recordType} master, dry-run>`,masterRowId:`<dry-run target ${P+1}>`,externalId:null})}let $=k[0];return{fixtureName:o,conduit:i,guards:s,whenPassed:f,atlasResolutions:l,transformResult:$.transformResult,applyBranch:$.applyBranch,wouldWriteBindings:$.wouldWriteBindings,masterAction:$.masterAction,targets:k,logs:y}}catch(d){return{fixtureName:o,conduit:i,guards:s,whenPassed:!1,atlasResolutions:l,wouldWriteBindings:[],targets:[],logs:[],error:d instanceof Error?d.message:String(d)}}}function Xw(t,e,r,n){return r==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${n.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:n.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:e.source,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${e.recordType} master (source_system='${e.source}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:e.source,externalId:null,role:"origin",why:"this conduit CREATED the new master, so the target is its origin; external_id null until writeback mints it"}]}}function Zw(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",targets:[],cycleBudget:Uu}}async function qu(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 zu(t){let e=await Du.readFile(t,"utf8");return JSON.parse(e)}function Bu(t){return Du.readFile(t,"utf8")}function Fu(t,e){let r=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;let n=t.targets.length>1;if(!e){if(!t.whenPassed)return`replay ${t.fixtureName} [${r.id}]: WHEN-FAILED (conduit short-circuited)`;if(n){let a=t.targets.reduce((l,d)=>l+d.wouldWriteBindings.length,0);return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.targets.length} targets in sequence (${a} binding(s) would be written)`}return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`}let o=[];o.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),o.push(`conduit: ${r.id}`);let s=(r.targets.length>0?r.targets:[{source:r.toSource,recordType:r.toRecordType}]).map(a=>`${a.source}.${a.recordType}`).join(" \u2192 ");o.push(`route: ${r.fromSource}.${r.fromRecordType} \u2192 ${s}${r.on?` on=${r.on}`:""}`),o.push(""),o.push("guards (dispatch order):");for(let a of t.guards){let l=a.status==="passed"?"\u2713":a.status==="failed"?"\u2717":"\u2298";o.push(` ${l} ${a.name} [${a.status}] \u2014 ${a.detail}`)}if(o.push(""),o.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)o.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let a of t.atlasResolutions)o.push(` ${a.key} \u2192 ${a.resolved===null?"null (no Atlas link \u2014 noted)":a.resolved}`);if(!t.whenPassed)return o.push(""),o.push("transform: SKIPPED (from.when gate did not fire)."),o.join(`
2017
+ `)}}]}})}p.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:y,token:k}=await e(),R=await fetch(`${y}/v1/catalog/records`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}});if(!R.ok)throw new Error(`catalog fetch failed: ${R.status}`);return Te(await R.json())}),p.registerTool("record_anatomy",{title:"Record anatomy + display contract",description:"Fetch ONE record type in depth (/v1/catalog/records/:type): anatomy markdown (field meanings, sublists, gotchas, relations), authored recipe display contracts (columns/labels/formats), semantic column metadata and the record's plain-English description. Read this BEFORE building UI over a record \u2014 column names alone routinely mislead (e.g. tran_id is the human-facing document number, entity_id has a display twin entity_name). Also reports `unpopulatedColumns`: columns that EXIST but carry no value in any sampled row on this instance (currency_name is the classic \u2014 currency_id holds the data). Rendering one of those produces a blank column while faithfully following the display contract, so check it before choosing what to show. And reports `lines`: the record's LINE tables with their columns, including line-level custom fields (custcol_*). Check the lines before concluding a link is absent \u2014 a transaction routinely carries a reference on its LINES while the header field is NULL, and reading only the header reports a real link as missing.",inputSchema:{recordType:M.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:M.string().optional().describe('Which connector publishes this recordType, e.g. "netsuite" or "stripe". 29 record types are published by more than one source ("customer" by six) and each is a different shape behind the same name. Omit it and the catalog collapse rule picks one; the answer names its choice in `source`.')}},async({recordType:y,source:k})=>{let{baseUrl:R,token:$}=await e(),P=k?`?source=${encodeURIComponent(k)}`:"",I=await fetch(`${R}/v1/catalog/records/${encodeURIComponent(y)}${P}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(I.status===404)throw new Error(`unknown record type "${y}" \u2014 list them with catalog_get.`);if(!I.ok)throw new Error(`record anatomy fetch failed: ${I.status}`);return Te(await I.json())}),p.registerTool("common_columns",{title:"Columns common to several record types",description:"Given SEVERAL record types, return the columns present on ALL of them (safe to select in one shared query shape) and the columns present on only some, with exactly which types lack each. Use this BEFORE writing a query that spans record types \u2014 transaction tables are NOT uniform (memo, total, created_from_id and even pg_row_id are missing from some), and PostgREST rejects an unknown column with 42703 and fails the ENTIRE request, so one wrong name loses the whole table rather than one field. Record types the caller cannot read come back in unknownRecordTypes \u2014 if that is non-empty the intersection covers fewer types than you asked for.",inputSchema:{recordTypes:M.array(M.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:M.string().optional().describe("Pin every requested type to ONE connector, e.g. \"netsuite\". Without it each name collapses by the catalog rule, so an intersection can silently mix two sources' tables for the same name. The response's `resolvedSources` names what it used.")}},async({recordTypes:y,source:k})=>{let{baseUrl:R,token:$}=await e(),P=new URLSearchParams({types:y.join(",")});k&&P.set("source",k);let I=await fetch(`${R}/v1/catalog/columns?${P}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(I.status===404)throw new Error(`none of those record types resolved: ${y.join(", ")} \u2014 list them with catalog_get.`);if(!I.ok)throw new Error(`common columns fetch failed: ${I.status}`);return Te(await I.json())}),p.registerTool("catalog_census",{title:"Count the customer's customizations",description:'Count the whole customization catalog: every object by kind AND by whether it can be changed (editable / partner_owned / turbobase_managed / unknown), plus which classes were never collected and why. Call this BEFORE search_catalog when the question is "how much is there" / "what is this account made of" / "how much of this is even ours to change". Takes no arguments.',inputSchema:{}},async()=>{let{baseUrl:y,token:k}=await e(),R=await fetch(`${y}/v1/catalog/census`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}});if(!R.ok)throw new Error(`catalog census failed: ${R.status}`);return Te(await R.json())}),p.registerTool("search_catalog",{title:"Search the customization catalog",description:'Survey the customer\'s customization catalog by free text \u2014 scripts, custom records, fields, lists, workflows, roles, saved searches, and installed bundles. Matches ids, names AND the generated plain-English explanations, so ask what you actually want ("which object handles rebates?"), not just an exact id. Returns compact {kind, externalId, name, summary, modifiability} hits plus the TRUE match total, so you can see when the page truncated; pass a hit to explain_object for the full definition + prose. A `partner_owned` object CANNOT be edited by this account however well you understand it \u2014 check that before planning a change. Search this before building over a custom record: its definition and explanation are the spec.',inputSchema:{query:M.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:M.enum(xb).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:M.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:y,kind:k,limit:R})=>{let{baseUrl:$,token:P}=await e(),I=new URLSearchParams({q:y});k&&I.set("kind",k),R!==void 0&&I.set("limit",String(R));let D=await fetch(`${$}/v1/catalog/objects?${I}`,{headers:{Authorization:`Bearer ${P}`,Accept:"application/json"}});if(!D.ok)throw new Error(`catalog object search failed: ${D.status}`);return Te(await D.json())}),p.registerTool("explain_object",{title:"Explain one catalog object",description:"Fetch ONE customization-catalog object in depth: its captured definition (or script source, or a bundle\u2019s membership), human label, the generated plain-English explanation (tldr + markdown) of what it is for, and its OWNERSHIP \u2014 `modifiability` plus a one-line reason saying whether this account can change it at all. Address it by the {kind, externalId} a search_catalog hit returns. For a FIELD it also reports `selectTarget`: where a List/Record field ACTUALLY points, resolved to a mirrored table plus the filter needed to read it correctly. Do not infer a target from the field name \u2014 a carrier-named field can point at `entity` (vendors), and building on the wrong guess resolves nothing while looking like an empty table.",inputSchema:{kind:M.enum(xb),externalId:M.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:y,externalId:k})=>{let{baseUrl:R,token:$}=await e(),P=await fetch(`${R}/v1/catalog/objects/${encodeURIComponent(y)}/${encodeURIComponent(k)}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown object ${y}:${k} \u2014 find it with search_catalog.`);if(!P.ok)throw new Error(`catalog object fetch failed: ${P.status}`);return Te(await P.json())}),p.registerTool("search_documentation",{title:"Search the knowledge base",description:'Search this instance\'s published knowledge base \u2014 internal documentation: processes, policies, playbooks, how-tos. Route questions about how the ORGANISATION works here ("what\'s our receiving process", "how do we handle returns"), and ALWAYS search it before building UI over a custom record \u2014 the KB is the only spec a custom record has. Returns up to `limit` {slug, title, snippet} hits; pass a slug to read_document for the full text. Published release only \u2014 drafts are never returned.',inputSchema:{query:M.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:M.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:y,limit:k})=>{let{baseUrl:R,token:$}=await e(),P=new URLSearchParams({q:y});k!==void 0&&P.set("limit",String(k));let I=await fetch(`${R}/v1/kb/search?${P}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(!I.ok)throw new Error(`kb search failed: ${I.status}`);return Te(await I.json())}),p.registerTool("read_document",{title:"Read a knowledge-base document",description:"Read one published knowledge-base document in full by its slug (from a search_documentation hit). Returns {found, slug, title, body_markdown}. Published release only \u2014 unpublished / admin-only drafts are never returned.",inputSchema:{slug:M.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:y})=>{let{baseUrl:k,token:R}=await e(),$=await fetch(`${k}/v1/kb/document/${encodeURIComponent(y)}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(!$.ok&&$.status!==404)throw new Error(`kb document fetch failed: ${$.status}`);return Te(await $.json())}),p.registerTool("generate_types",{title:"Generate types.ts",description:"Generate the instance's types.ts (record shapes + PostgREST ops). Returns the source.",inputSchema:{recordsOnly:M.boolean().optional()}},async({recordsOnly:y})=>{let{baseUrl:k,token:R}=await e();return{content:[{type:"text",text:await hr({baseUrl:k,token:R,recordsOnly:y})}]}}),p.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:M.string(),event:M.string().optional(),template:M.enum(["require-field","enforce-format","blank"]).optional(),field:M.string().optional(),regex:M.string().optional(),source:M.string().optional(),id:M.string().optional()}},async y=>{let k=Rt("hook",{recordType:y.recordType,event:y.event,template:y.template,field:y.field,regex:y.regex,source:y.source,id:y.id});return Te({path:k.relativePath,content:k.content})}),p.registerTool("scaffold_conduit",{title:"Scaffold a conduit",description:"Generate a conduit file body that bridges a canonical record from one source into another (does not write to disk; returns path + content).",inputSchema:{source:M.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:M.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:M.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:M.string().optional().describe("Target record type (defaults to the trigger record type)."),event:M.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:M.string().optional()}},async y=>{let k=Rt("conduit",{recordType:y.recordType,source:y.source,to:y.to,toRecordType:y.toRecordType,event:y.event,id:y.id});return Te({path:k.relativePath,content:k.content})}),p.registerTool("scaffold_process",{title:"Scaffold a process",description:"Generate a process file body \u2014 an ordered sequence of record writes an app invokes and the platform runs on the server (does not write to disk; returns path + content).",inputSchema:{recordType:M.string().describe('Record type the first step writes, e.g. "purchaseOrder".'),then:M.string().optional().describe('Record type of a second step that waits for the first, e.g. "vendorBill".'),onFailure:M.enum(["stop","rollback"]).optional().describe("What the engine does when a step fails (default stop)."),id:M.string().optional()}},async y=>{let k=Rt("process",{recordType:y.recordType,then:y.then,onFailure:y.onFailure,id:y.id});return Te({path:k.relativePath,content:k.content})}),p.registerTool("author_conduit",{title:"Draft and check a conduit",description:'Ask the instance to WRITE a conduit from a plain-English intent and check it before staging it for review \u2014 the cross-source counterpart to the hook the healing agent drafts. Returns {status, intentId, id?, reason?}: "written" staged a proposal, "rejected_by_validation" says why it could not (including a target system this instance can only read from). Nothing is deployed \u2014 an administrator applies the staged bridge from the Conduits tab. Prefer scaffold_conduit when you intend to write the transform yourself.',inputSchema:{intent:M.string().describe(`What the bridge should do, in the operator's words, e.g. "when a shopify order is paid, raise the matching NetSuite sales order".`),fromSource:M.string().describe('Origin source the record arrives from, e.g. "shopify".'),fromRecordType:M.string().describe('Canonical record type the bridge triggers on, e.g. "order".'),toSource:M.string().describe('Target source the bridge writes into, e.g. "netsuite".'),toRecordType:M.string().describe('Canonical record type written on the target, e.g. "salesOrder".'),intentId:M.string().optional().describe("Correlation id for the audit trail. The instance mints one when omitted."),columns:M.array(M.string()).optional().describe("Narrow the target columns the transform may write. Defaults to the target record's own.")}},async y=>{let{baseUrl:k,token:R}=await e(),$=new q({baseUrl:k,token:R});return Te(await $.authorConduit({intent:y.intent,from:{source:y.fromSource,recordType:y.fromRecordType},to:{source:y.toSource,recordType:y.toRecordType},...y.intentId?{intentId:y.intentId}:{},...y.columns?.length?{columns:y.columns}:{}}))}),p.registerTool("mock_test",{title:"Dry-run an extension against samples",description:"Bundle the given source through the production sandbox and run it against samples/ fixtures.",inputSchema:{source:M.string().describe("The extension TS source."),samplesDir:M.string().optional().describe('Samples directory (default "samples").')}},async({source:y,samplesDir:k})=>{let R=Ab(k,t.samplesRoot);if(R===null)return{content:[{type:"text",text:JSON.stringify({error:"samples_dir_refused",message:dA})}],isError:!0};let $;try{$=await _n(R)}catch(D){if(t.samplesRoot!==void 0)return{content:[{type:"text",text:JSON.stringify({error:"samples_unreadable",message:"the samples directory could not be read"})}],isError:!0};throw D}let P=await Ho(y,$.map(D=>D.fixture)),I=P.filter(D=>!D.pass).length;return Te({total:P.length,passed:P.length-I,results:P})}),p.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:M.string(),recordType:M.string(),event:M.string(),source:M.string().describe('Adapter id or "standalone".'),sourceCode:M.string().describe("The verbatim extension TS."),extensionKind:M.string().optional()}},async y=>{let{baseUrl:k,token:R}=await e(),P=await new q({baseUrl:k,token:R}).deploy({id:y.id,recordType:y.recordType,event:y.event,source:y.source,sourceCode:y.sourceCode,extensionKind:y.extensionKind});return Te(P)}),p.registerTool("tail_logs",{title:"Tail an extension's logs",description:"Read an extension's log ring buffer (GET /v1/extensions/:id/logs).",inputSchema:{id:M.string(),limit:M.number().int().positive().optional()}},async({id:y,limit:k})=>{let{baseUrl:R,token:$}=await e(),P=new q({baseUrl:R,token:$});return Te({id:y,logs:await P.logs(y,k)})}),p.registerTool("apps_list",{title:"List hosted apps",description:"Every hosted app on this instance with its slug, whether it's deployed, and its latest source revision. `sourceRev: null` means the app has no source of record yet (deployed dist only) \u2014 pull will 404 until something is pushed. GET /v1/apps.",inputSchema:{}},async()=>{let{baseUrl:y,token:k}=await e(),R=new q({baseUrl:y,token:k});return Te(await R.appsList())}),p.registerTool("apps_create",{title:"Create a hosted app",description:"Create a bare hosted-app row so source can be pushed and a build shipped to it \u2014 the author-led path that needs no proposal. Creates the registration only; it serves nothing until a build is shipped. POST /v1/apps.",inputSchema:{slug:M.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:M.string().optional().describe("Display name (defaults to the slug)."),description:M.string().optional().describe("Short description.")}},async({slug:y,name:k,description:R})=>{let{baseUrl:$,token:P}=await e(),I=new q({baseUrl:$,token:P});return Te(await I.appsCreate({slug:y,name:k,description:R}))}),p.registerTool("apps_pull",{title:"Pull a hosted app's source",description:"Fetch the app's latest source tree as {path \u2192 contents} READ-ONLY \u2014 write it to disk, refine it, then apps_push it back. Returns 404 when the app has no source revision yet. NEVER deploys. GET /v1/apps/:id/pull.",inputSchema:{app:M.string().describe("App slug or id.")}},async({app:y})=>{let{baseUrl:k,token:R}=await e(),$=new q({baseUrl:k,token:R});return Te(await $.appsPull(y))}),p.registerTool("apps_push",{title:"Push a hosted app's source",description:"Record an edited source tree as the app's NEW source revision, so the instance holds the source of record rather than one laptop. Send the whole tree ({path \u2192 contents}, relative POSIX paths, no node_modules/dist/.git). SOURCE ONLY \u2014 this does not build and does not change what is live; run `turbobase apps deploy <slug>` for that. POST /v1/apps/:id/push.",inputSchema:{app:M.string().describe("App slug or id."),files:M.record(M.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:M.string().optional().describe("Short note stored with the revision.")}},async({app:y,files:k,note:R})=>{let{baseUrl:$,token:P}=await e(),I=new q({baseUrl:$,token:P});return Te(await I.appsPush(y,k,{note:R}))});let f=M.object({name:M.string().describe("Field name (lowercase identifier)."),type:M.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:M.boolean().optional()}),_=M.object({slug:M.string().describe("Table slug; the physical table is cr_<slug>."),displayName:M.string().optional(),fields:M.array(f).describe("At least one field."),rowLevelOwner:M.boolean().optional().describe("Restrict non-admins to rows they created.")});return p.registerTool("tables_list",{title:"List custom tables",description:"The instance's customer-authored tables, their fields, and which apps claim each one. Read the `column` on each field \u2014 that is the actual Postgres column an app SELECTs (cf_sa_<name>), which is not the same string as the field name. GET /v1/tables.",inputSchema:{}},async()=>{let{baseUrl:y,token:k}=await e(),R=new q({baseUrl:y,token:k});return Te(await R.tablesList())}),p.registerTool("tables_plan",{title:"Preview a table declaration",description:"What these table declarations WOULD do, without doing it. Several apps may claim one table and the instance merges their declarations, so this reports the merged shape and \u2014 the reason to call it \u2014 fails with a conflict report when another claimant already declares one of your field names at a different type. Writes NOTHING. POST /v1/tables/plan.",inputSchema:{tables:M.array(_),claimedBy:M.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:y,claimedBy:k})=>{let{baseUrl:R,token:$}=await e(),P=new q({baseUrl:R,token:$});return Te(await P.tablesPlan({tables:y,claimedBy:k}))}),p.registerTool("tables_apply",{title:"Create or evolve custom tables",description:"Record these table declarations and reconcile them into real Postgres tables \u2014 RLS, realtime, and the write path included. Additive: an existing table gains the fields you declare and keeps the ones other claimants declared. Never drops a column, so removing a field from your declaration releases your claim on it rather than deleting data. Prefer declaring tables in the app manifest (public/turbobase.json) so the deploy applies them; use this when authoring outside an app. POST /v1/tables/apply.",inputSchema:{tables:M.array(_),claimedBy:M.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:y,claimedBy:k})=>{let{baseUrl:R,token:$}=await e(),P=new q({baseUrl:R,token:$});return Te(await P.tablesApply({tables:y,claimedBy:k}))}),p.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async y=>{let{baseUrl:k,token:R}=await e(),P=await(await fetch(`${k}/v1/catalog/records`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}})).text();return{contents:[{uri:y.href,mimeType:"application/json",text:P}]}}),p.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async y=>{let{baseUrl:k,token:R}=await e(),$=await hr({baseUrl:k,token:R});return{contents:[{uri:y.href,mimeType:"text/plain",text:$}]}}),p.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async y=>{let k=Ii(process.cwd(),"samples"),R=[];try{R=(await aA.readdir(k)).filter(P=>P.endsWith(".json"))}catch{R=[]}let $=await _n(k);return{contents:[{uri:y.href,mimeType:"application/json",text:JSON.stringify({files:R,samples:$.map(P=>P.fixture)},null,2)}]}}),p.registerResource("recipes","recipes:///",{title:"Intent recipes",description:"Intent recipes (columns / stats / actions per record type + intent), filtered to the instance's installed sources.",mimeType:"application/json"},async y=>{let k=await $b(),R=[];if(k){let{baseUrl:$,token:P}=await e();R=await k.listRecipesForSurface({surface:"mcp-authoring",baseUrl:$,token:P},r)}return{contents:[{uri:y.href,mimeType:"application/json",text:JSON.stringify({recipes:R})}]}}),p}async function mA(t={}){let e=await Cb(t),r=new Ci;await e.connect(r)}var xb,Rb,Eb,Pb,dA,Ib,pA,hA,Nb=j(()=>{bb();Sb();Zi();bn();mt();ca();Jo();Tb();xb=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];Eb="turbobase-authoring",Pb="0.1.0";dA="samplesDir must be a relative path inside the samples directory this server serves; absolute paths and paths that leave it are refused over the network.";Ib=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","search_catalog","catalog_census","explain_object","generate_types","scaffold_hook","scaffold_conduit","scaffold_process","author_conduit","mock_test","deploy","tail_logs","apps_list","apps_create","apps_pull","apps_push","tables_list","tables_plan","tables_apply"],pA=[...Ib,...kb],hA=["catalog:///","types://all","samples:///","recipes:///"]});Zi();bn();mt();ca();import{spawn as Kd}from"node:child_process";import{promises as ae}from"node:fs";import{homedir as fA}from"node:os";import{basename as Db,dirname as zt,join as et,relative as Ni,resolve as se,sep as Hd}from"node:path";import{Command as gA}from"commander";Fo();import{promises as Du}from"node:fs";var qw=/^[a-z][a-z0-9_]+$/;function Iu(t,e){if(typeof t!="string"||!qw.test(t))throw new Error(`${e} ${JSON.stringify(t)} must match /^[a-z][a-z0-9_]+$/ (NS scriptid form). This restriction is what lets reconcile safely splice it as a SQL identifier; refusing to emit DDL.`);return t}var zw="customrecord",Bw="customlist";function Fw(t){return t.startsWith("customrecord_")?t.slice(13):t}function Hw(t){return t.startsWith("customlist_")?t.slice(11):t}function Kw(t){return Iu(t,"custom_record scriptId"),`cr_${Fw(t)}`}function Vw(t){return Iu(t,"custom_list scriptId"),`cl_${Hw(t)}`}function Ou(t){return t.startsWith(zw)?Kw(t):t.startsWith(Bw)?Vw(t):null}var Gw={salesOrder:{table:"order"},invoice:{table:"invoice"},itemFulfillment:{table:"order_fulfillment"},customerPayment:{table:"customer_payment"},cashSale:{table:"cash_sale"},cashRefund:{table:"cash_refund"},opportunity:{table:"opportunity"},estimate:{table:"estimate"},customerDeposit:{table:"customer_deposit"},creditMemo:{table:"credit_memo"},customer:{table:"entity",typeColumn:"entity_type",typeValue:"customer"},vendor:{table:"entity",typeColumn:"entity_type",typeValue:"vendor"},contact:{table:"entity",typeColumn:"entity_type",typeValue:"contact"},employee:{table:"entity",typeColumn:"entity_type",typeValue:"employee"},partner:{table:"entity",typeColumn:"entity_type",typeValue:"partner"},inventoryItem:{table:"item",typeColumn:"item_type",typeValue:"inventoryItem"},serviceSaleItem:{table:"item",typeColumn:"item_type",typeValue:"serviceSaleItem"},nonInventoryResaleItem:{table:"item",typeColumn:"item_type",typeValue:"nonInventoryResaleItem"},kitItem:{table:"item",typeColumn:"item_type",typeValue:"kitItem"},assemblyItem:{table:"item",typeColumn:"item_type",typeValue:"assemblyItem"},lotNumberedInventoryItem:{table:"item",typeColumn:"item_type",typeValue:"lotNumberedInventoryItem"},serializedInventoryItem:{table:"item",typeColumn:"item_type",typeValue:"serializedInventoryItem"},lotNumberedAssemblyItem:{table:"item",typeColumn:"item_type",typeValue:"lotNumberedAssemblyItem"},serializedAssemblyItem:{table:"item",typeColumn:"item_type",typeValue:"serializedAssemblyItem"},nonInventorySaleItem:{table:"item",typeColumn:"item_type",typeValue:"nonInventorySaleItem"},otherChargeSaleItem:{table:"item",typeColumn:"item_type",typeValue:"otherChargeSaleItem"},discountItem:{table:"item",typeColumn:"item_type",typeValue:"discountItem"},location:{table:"location"},department:{table:"department"},classification:{table:"classification"},vendorBill:{table:"vendor_bill"},vendorPayment:{table:"vendor_payment"},purchaseOrder:{table:"purchase_order"},journalEntry:{table:"journal_entry"},timeBill:{table:"time_bill"},expenseReport:{table:"expense_report"},itemReceipt:{table:"item_receipt"},vendorReturnAuthorization:{table:"vendor_return_authorization"},transferOrder:{table:"transfer_order"},check:{table:"check"},customerRefund:{table:"customer_refund"},project:{table:"project"},projectTask:{table:"work_item",typeColumn:"item_type",typeValue:"project_task"},supportCase:{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},caseMessage:{table:"activity",typeColumn:"activity_type",typeValue:"case_message_outgoing",alsoAddresses:["case_message_incoming"]},shippingItem:{table:"shipping_item"},unitsType:{table:"units_type"},returnAuthorization:{table:"return_authorization"},inventoryAdjustment:{table:"inventory_adjustment"},vendorCredit:{table:"vendor_credit"},deposit:{table:"deposit"},account:{table:"account"},channel_message:{table:"activity",typeColumn:"activity_type",typeValue:"message"},social_post:{table:"activity",typeColumn:"activity_type",typeValue:"social_post"},reaction:{table:"reaction"},esignSubmission:{table:"esign_submission"},esignSubmitter:{table:"esign_submitter"},workflow_run:{table:"automation_run"},printer:{table:"printer"},printJob:{table:"print_job"},label:{table:"label"},call:{table:"activity",typeColumn:"activity_type",typeValue:"call"},quote:{table:"estimate"},tag:{table:"label"},request:{table:"request"}};function Nu(t,e){let r=e?Jw[`${e}:${t}`]:void 0;if(r)return r;let n=Gw[t];if(n)return n;let o=Ou(t);return o?{table:o}:void 0}var Ww={accountingPeriod:"accounting_period",printer:"printer"};var Jw={...Object.fromEntries(Object.entries(Ww).map(([t,e])=>[`standalone:${t}`,{table:e}])),"google_workspace:doc":{table:"memory_document",typeColumn:"kind",typeValue:"doc"},"google_workspace:email":{table:"memory_document",typeColumn:"kind",typeValue:"email"},"google_workspace:file":{table:"memory_document",typeColumn:"kind",typeValue:"file"},"google_workspace:sheet":{table:"memory_document",typeColumn:"kind",typeValue:"sheet"},"google_workspace:slide":{table:"memory_document",typeColumn:"kind",typeValue:"slide"},"salesforce:account":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"salesforce:case":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"salesforce:lead":{table:"entity",typeColumn:"entity_type",typeValue:"lead"},"salesforce:task":{table:"activity",typeColumn:"activity_type",typeValue:"task"},"salesforce:event":{table:"activity",typeColumn:"activity_type",typeValue:"event"},"intercom:admin":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"intercom:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"hubspot:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"hubspot:owner":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"intercom:conversation":{table:"work_item",typeColumn:"item_type",typeValue:"conversation"},"intercom:ticket":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"github:issue":{table:"work_item",typeColumn:"item_type",typeValue:"issue"},"github:pull_request":{table:"work_item",typeColumn:"item_type",typeValue:"pull_request"},"github:comment":{table:"activity",typeColumn:"activity_type",typeValue:"comment"},"zendesk:organization":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"getsales:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"xero:supplier":{table:"entity",typeColumn:"entity_type",typeValue:"vendor"},"zoho_crm:account":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"zoho_crm:lead":{table:"entity",typeColumn:"entity_type",typeValue:"lead"},"zoho_crm:case":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"slack:user":{table:"entity",typeColumn:"entity_type",typeValue:"contact"},"slack:channel":{table:"channel"},"slack:reaction":{table:"reaction"},"quickbooks:bill":{table:"vendor_bill"},"quickbooks:payment":{table:"customer_payment"},"quickbooks:billPayment":{table:"vendor_payment"},"quickbooks:item":{table:"item"},"zoho_crm:task":{table:"activity",typeColumn:"activity_type",typeValue:"task"},"zoho_crm:event":{table:"activity",typeColumn:"activity_type",typeValue:"event"},"zoho_crm:product":{table:"item",typeColumn:"item_type",typeValue:"inventoryItem"},"xero:bill":{table:"vendor_bill"},"xero:billPayment":{table:"vendor_payment"},"xero:creditNote":{table:"credit_memo"},"xero:item":{table:"item"},"xero:manualJournal":{table:"journal_entry"},"xero:payment":{table:"customer_payment"},"xero:receiveMoney":{table:"deposit"},"xero:spendMoney":{table:"check"},"xero:supplierCreditNote":{table:"vendor_credit"},"azure_blob:file":{table:"source_file"}};function Lu(t,e){let r=Nu(t,e);return r?`${r.table}|${r.typeColumn??"-"}|${r.typeValue??"-"}`:void 0}function ju(t,e,r){if(e===t)return"same-type-merge";let n=r?.fromSource,o=r?.toSource;if(n&&o&&n!==o){let s=Lu(t,n),i=Lu(e,o);if(s!==void 0&&s===i)return"same-type-merge"}return"different-type-mint"}var Uu=4;function da(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=Ir(t,"id"),r=Ir(t,"on"),n=Ir(t,"source"),o=Ir(t,"recordType"),s=[];for(let l of t.matchAll(/\bto\s*:\s*\{([^}]*)\}/g)){let d=Ir(l[1]??"","source"),p=Ir(l[1]??"","recordType");d&&p&&s.push({source:d,recordType:p})}let i=s[0],a=/cycleBudget\s*:\s*(\d+)/.exec(t);if(!e||!n||!o||!i)throw new Error("could not parse id/from.{source,recordType}/to.{source,recordType} \u2014 is it a reference-shape defineConduit({...})?");return{id:e,on:r,fromSource:n,fromRecordType:o,toSource:i.source,toRecordType:i.recordType,targets:s,cycleBudget:a?Number(a[1]):Uu}}function Ir(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function Yw(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 Mu(t,e,r="fixture",n={}){let o=e.name??r,s=[],i;try{i=da(t)}catch(d){return{fixtureName:o,conduit:Zw(),guards:s,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],targets:[],logs:[],error:d instanceof Error?d.message:String(d)}}let a=Yw(e),l=Object.entries(e.atlasLinks??{}).map(([d,p])=>({key:d,resolved:p}));try{let d=await Bo(t,{resolveDir:n.resolveDir}),f=!!(await vn(d,a,{member:"when",timeoutMs:zo})).whenResult;s.push({name:"from.when",status:f?"passed":"failed",detail:f?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let _=e.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${_} vs cycleBudget=${i.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),s.push({name:"opposite-direction-loop",status:"skipped-offline",detail:"reads committed conduit_event rows for the reverse leg \u2014 requires live sandbox state (skipped in fixture mode)"}),s.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!f)return{fixtureName:o,conduit:i,guards:s,whenPassed:f,atlasResolutions:l,wouldWriteBindings:[],targets:[],logs:[]};let y=[],k=[],R=[];for(let P=0;P<i.targets.length;P+=1){let I=i.targets[P],D=await vn(d,{...a,materialized:R.map(Ft=>({...Ft}))},{member:"transform",stepIndex:P,timeoutMs:zo});y.push(...D.effects.logs);let Y=D.effects.result;if(!Y||typeof Y!="object")throw new Error(`conduit ${i.id} transform${i.targets.length>1?` (target ${P+1})`:""} returned no result (expected { patch, createdFrom? })`);let F=Y,Oe=ju(i.fromRecordType,I.recordType,{fromSource:i.fromSource,toSource:I.source}),{wouldWriteBindings:Ce,masterAction:Bt}=Xw(i,I,Oe,e);k.push({to:I,transformResult:F,applyBranch:Oe,wouldWriteBindings:Ce,masterAction:Bt}),R.push({source:I.source,recordType:I.recordType,masterTable:`<${I.recordType} master, dry-run>`,masterRowId:`<dry-run target ${P+1}>`,externalId:null})}let $=k[0];return{fixtureName:o,conduit:i,guards:s,whenPassed:f,atlasResolutions:l,transformResult:$.transformResult,applyBranch:$.applyBranch,wouldWriteBindings:$.wouldWriteBindings,masterAction:$.masterAction,targets:k,logs:y}}catch(d){return{fixtureName:o,conduit:i,guards:s,whenPassed:!1,atlasResolutions:l,wouldWriteBindings:[],targets:[],logs:[],error:d instanceof Error?d.message:String(d)}}}function Xw(t,e,r,n){return r==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${n.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:n.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:e.source,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${e.recordType} master (source_system='${e.source}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:e.source,externalId:null,role:"origin",why:"this conduit CREATED the new master, so the target is its origin; external_id null until writeback mints it"}]}}function Zw(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",targets:[],cycleBudget:Uu}}async function qu(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 zu(t){let e=await Du.readFile(t,"utf8");return JSON.parse(e)}function Bu(t){return Du.readFile(t,"utf8")}function Fu(t,e){let r=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;let n=t.targets.length>1;if(!e){if(!t.whenPassed)return`replay ${t.fixtureName} [${r.id}]: WHEN-FAILED (conduit short-circuited)`;if(n){let a=t.targets.reduce((l,d)=>l+d.wouldWriteBindings.length,0);return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.targets.length} targets in sequence (${a} binding(s) would be written)`}return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`}let o=[];o.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),o.push(`conduit: ${r.id}`);let s=(r.targets.length>0?r.targets:[{source:r.toSource,recordType:r.toRecordType}]).map(a=>`${a.source}.${a.recordType}`).join(" \u2192 ");o.push(`route: ${r.fromSource}.${r.fromRecordType} \u2192 ${s}${r.on?` on=${r.on}`:""}`),o.push(""),o.push("guards (dispatch order):");for(let a of t.guards){let l=a.status==="passed"?"\u2713":a.status==="failed"?"\u2717":"\u2298";o.push(` ${l} ${a.name} [${a.status}] \u2014 ${a.detail}`)}if(o.push(""),o.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)o.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let a of t.atlasResolutions)o.push(` ${a.key} \u2192 ${a.resolved===null?"null (no Atlas link \u2014 noted)":a.resolved}`);if(!t.whenPassed)return o.push(""),o.push("transform: SKIPPED (from.when gate did not fire)."),o.join(`
2018
2018
  `);let i=t.targets.length>0?t.targets:[{to:{source:r.toSource,recordType:r.toRecordType},transformResult:t.transformResult??{patch:{}},applyBranch:t.applyBranch??"different-type-mint",wouldWriteBindings:t.wouldWriteBindings,masterAction:t.masterAction??""}];if(i.forEach((a,l)=>{let d=n?` (target ${l+1}/${i.length}: ${a.to.source}.${a.to.recordType})`:"";o.push(""),o.push(`transform${d} \u2192 patch:`),o.push(Qw(JSON.stringify(a.transformResult.patch??{},null,2)," ")),a.transformResult.createdFrom&&o.push(` createdFrom: ${JSON.stringify(a.transformResult.createdFrom)}`),o.push(""),o.push(`apply-branch${d}: ${a.applyBranch}`),o.push(` ${a.masterAction}`),o.push(""),o.push(`bindings that WOULD be written (txn_source_link)${d}:`);for(let p of a.wouldWriteBindings)o.push(` ${p.source} role=${p.role} external_id=${p.externalId??"null"} \u2014 ${p.why}`)}),t.logs.length>0){o.push(""),o.push("conduit logs:");for(let a of t.logs)o.push(` [${a.level}] ${a.message}${a.meta?` ${JSON.stringify(a.meta)}`:""}`)}return o.join(`
2019
2019
  `)}function Qw(t,e){return t.split(`
2020
2020
  `).map(r=>e+r).join(`
2021
- `)}var ev="2026-01-01",Hu="2026-01-01T00:00:00.000Z";function tv(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"?ev:r.startsWith("timestamp")?Hu: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:Hu}:{}:r==="uuid"?"00000000-0000-0000-0000-000000000000":r==="array"||r.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function rv(t){let e={};for(let r of t.columns)e[r.name]=tv(r.pgType,r.name);return e}function nv(t,e={}){let r=e.event??"before_save";return{name:`${t.recordType} ${r} (generated)`,context:{recordType:t.recordType,event:r,source:t.source,payload:rv(t)},expect:e.expect??"pass"}}function Ku(t,e={}){return t.map(r=>({recordType:r.recordType,fixture:nv(r,e)}))}import{promises as Vu}from"node:fs";import{join as Gu,relative as ov,sep as sv}from"node:path";var iv=67324752,av=33639248,lv=101010256,cv=(()=>{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 dv(t){let e=4294967295;for(let r=0;r<t.length;r++)e=cv[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}async function uv(t){let e=[];async function r(n){let o=await Vu.readdir(n,{withFileTypes:!0});for(let s of o){let i=Gu(n,s.name);s.isDirectory()?await r(i):s.isFile()&&e.push(ov(t,i).split(sv).join("/"))}}return await r(t),e.sort(),e}async function Wu(t){let e=await uv(t),r=[],n=[],o=0;for(let a of e){let l=Buffer.from(a,"utf8"),d=await Vu.readFile(Gu(t,a)),p=dv(d),f=Buffer.alloc(30+l.length);f.writeUInt32LE(iv,0),f.writeUInt16LE(20,4),f.writeUInt16LE(0,6),f.writeUInt16LE(0,8),f.writeUInt32LE(p,14),f.writeUInt32LE(d.length,18),f.writeUInt32LE(d.length,22),f.writeUInt16LE(l.length,26),l.copy(f,30),r.push(f,d);let _=Buffer.alloc(46+l.length);_.writeUInt32LE(av,0),_.writeUInt16LE(20,4),_.writeUInt16LE(20,6),_.writeUInt16LE(0,10),_.writeUInt32LE(p,16),_.writeUInt32LE(d.length,20),_.writeUInt32LE(d.length,24),_.writeUInt16LE(l.length,28),_.writeUInt32LE(o,42),l.copy(_,46),n.push(_),o+=f.length+d.length}let s=Buffer.concat(n),i=Buffer.alloc(22);return i.writeUInt32LE(lv,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}}oa();function pv(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":/\bdefineProcess\s*[<(]/.test(t)?"process":"hook"}function Ko(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function mv(t){let e=hv(t,"from"),n=Ju(t,"to").map(o=>({source:Ko(o,"source"),recordType:Ko(o,"recordType")}));return{fromSource:e?Ko(e,"source"):void 0,fromRecordType:e?Ko(e,"recordType"):void 0,toSource:n[0]?.source,toRecordType:n[0]?.recordType,targets:n}}function hv(t,e){return Ju(t,e)[0]??null}function Ju(t,e){let r=[],n=new RegExp(`\\b${e}\\s*:\\s*\\{`,"g"),o;for(;(o=n.exec(t))!==null;){let s=0,i=o.index+o[0].length-1;for(let a=i;a<t.length;a+=1){let l=t[a];if(l==="{")s+=1;else if(l==="}"&&(s-=1,s===0)){r.push(t.slice(i+1,a)),n.lastIndex=a+1;break}}}return r}function fv(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 gv(t,e){let r=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return r?Number(r[1]):void 0}function yv(t){return/\bcreatedFrom\b/.test(t)}function Yu(t){let e=pv(t),r=[];if(e==="hook")return{kind:e,warnings:r};let{fromSource:n,fromRecordType:o,toRecordType:s,targets:i}=mv(t);for(let p of i)if(n&&p.source&&n===p.source){r.push({rule:"same-source-conduit",message:`from.source and to.source are both '${n}' \u2014 a conduit that doesn't cross sources isn't a conduit.`,fix:`Make 'to.source' a DIFFERENT source than 'from.source', or rewrite this as a hook (\`turbobase ext new hook --record ${o??"<type>"}\`) \u2014 a same-source transform belongs on the write path, not the cross-source bridge.`});break}let a=fv(t);if(a!==null){let p=/\bexternalId\b/.test(a),f=/\bfromSource\b/.test(a);!p&&!f&&r.push({rule:"weak-idempotency-key",message:"idempotencyKey omits both ctx.externalId and ctx.fromSource \u2014 two distinct re-fires (different records, or the same record from different sources) collapse onto one conduit_event ledger row and one of them is silently dropped as a duplicate.",fix:"Include `ctx.externalId` (and, for multi-source triggers, `ctx.fromSource`) in the key, e.g. `idempotencyKey: (ctx) => `${ctx.fromSource}:${ctx.externalId}``."})}let l=i.find(p=>p.recordType&&o&&p.recordType!==o)?.recordType??(o!==s?s:void 0);o&&l&&!yv(t)&&r.push({rule:"missing-created-from",message:`this conduit bridges '${o}' \u2192 '${l}' (different record types) but its transform never returns 'createdFrom' \u2014 the created ${l} 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 d=gv(t,"cycleBudget");return d!==void 0&&(d<1?r.push({rule:"cycle-budget-too-low",message:`cycleBudget=${d} 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)."}):d>20&&r.push({rule:"cycle-budget-too-high",message:`cycleBudget=${d} 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 Xu(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(`
2021
+ `)}var ev="2026-01-01",Hu="2026-01-01T00:00:00.000Z";function tv(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"?ev:r.startsWith("timestamp")?Hu: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:Hu}:{}:r==="uuid"?"00000000-0000-0000-0000-000000000000":r==="array"||r.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function rv(t){let e={};for(let r of t.columns)e[r.name]=tv(r.pgType,r.name);return e}function nv(t,e={}){let r=e.event??"before_save";return{name:`${t.recordType} ${r} (generated)`,context:{recordType:t.recordType,event:r,source:t.source,payload:rv(t)},expect:e.expect??"pass"}}function Ku(t,e={}){return t.map(r=>({recordType:r.recordType,fixture:nv(r,e)}))}import{promises as Vu}from"node:fs";import{join as Gu,relative as ov,sep as sv}from"node:path";var iv=67324752,av=33639248,lv=101010256,cv=(()=>{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 dv(t){let e=4294967295;for(let r=0;r<t.length;r++)e=cv[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}async function uv(t){let e=[];async function r(n){let o=await Vu.readdir(n,{withFileTypes:!0});for(let s of o){let i=Gu(n,s.name);s.isDirectory()?await r(i):s.isFile()&&e.push(ov(t,i).split(sv).join("/"))}}return await r(t),e.sort(),e}async function Wu(t){let e=await uv(t),r=[],n=[],o=0;for(let a of e){let l=Buffer.from(a,"utf8"),d=await Vu.readFile(Gu(t,a)),p=dv(d),f=Buffer.alloc(30+l.length);f.writeUInt32LE(iv,0),f.writeUInt16LE(20,4),f.writeUInt16LE(0,6),f.writeUInt16LE(0,8),f.writeUInt32LE(p,14),f.writeUInt32LE(d.length,18),f.writeUInt32LE(d.length,22),f.writeUInt16LE(l.length,26),l.copy(f,30),r.push(f,d);let _=Buffer.alloc(46+l.length);_.writeUInt32LE(av,0),_.writeUInt16LE(20,4),_.writeUInt16LE(20,6),_.writeUInt16LE(0,10),_.writeUInt32LE(p,16),_.writeUInt32LE(d.length,20),_.writeUInt32LE(d.length,24),_.writeUInt16LE(l.length,28),_.writeUInt32LE(o,42),l.copy(_,46),n.push(_),o+=f.length+d.length}let s=Buffer.concat(n),i=Buffer.alloc(22);return i.writeUInt32LE(lv,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}}oa();function pv(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":/\bdefineProcess\s*[<(]/.test(t)?"process":"hook"}function Ko(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function hv(t){let e=mv(t,"from"),n=Ju(t,"to").map(o=>({source:Ko(o,"source"),recordType:Ko(o,"recordType")}));return{fromSource:e?Ko(e,"source"):void 0,fromRecordType:e?Ko(e,"recordType"):void 0,toSource:n[0]?.source,toRecordType:n[0]?.recordType,targets:n}}function mv(t,e){return Ju(t,e)[0]??null}function Ju(t,e){let r=[],n=new RegExp(`\\b${e}\\s*:\\s*\\{`,"g"),o;for(;(o=n.exec(t))!==null;){let s=0,i=o.index+o[0].length-1;for(let a=i;a<t.length;a+=1){let l=t[a];if(l==="{")s+=1;else if(l==="}"&&(s-=1,s===0)){r.push(t.slice(i+1,a)),n.lastIndex=a+1;break}}}return r}function fv(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 gv(t,e){let r=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return r?Number(r[1]):void 0}function yv(t){return/\bcreatedFrom\b/.test(t)}function Yu(t){let e=pv(t),r=[];if(e==="hook")return{kind:e,warnings:r};let{fromSource:n,fromRecordType:o,toRecordType:s,targets:i}=hv(t);for(let p of i)if(n&&p.source&&n===p.source){r.push({rule:"same-source-conduit",message:`from.source and to.source are both '${n}' \u2014 a conduit that doesn't cross sources isn't a conduit.`,fix:`Make 'to.source' a DIFFERENT source than 'from.source', or rewrite this as a hook (\`turbobase ext new hook --record ${o??"<type>"}\`) \u2014 a same-source transform belongs on the write path, not the cross-source bridge.`});break}let a=fv(t);if(a!==null){let p=/\bexternalId\b/.test(a),f=/\bfromSource\b/.test(a);!p&&!f&&r.push({rule:"weak-idempotency-key",message:"idempotencyKey omits both ctx.externalId and ctx.fromSource \u2014 two distinct re-fires (different records, or the same record from different sources) collapse onto one conduit_event ledger row and one of them is silently dropped as a duplicate.",fix:"Include `ctx.externalId` (and, for multi-source triggers, `ctx.fromSource`) in the key, e.g. `idempotencyKey: (ctx) => `${ctx.fromSource}:${ctx.externalId}``."})}let l=i.find(p=>p.recordType&&o&&p.recordType!==o)?.recordType??(o!==s?s:void 0);o&&l&&!yv(t)&&r.push({rule:"missing-created-from",message:`this conduit bridges '${o}' \u2192 '${l}' (different record types) but its transform never returns 'createdFrom' \u2014 the created ${l} 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 d=gv(t,"cycleBudget");return d!==void 0&&(d<1?r.push({rule:"cycle-budget-too-low",message:`cycleBudget=${d} 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)."}):d>20&&r.push({rule:"cycle-budget-too-high",message:`cycleBudget=${d} 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 Xu(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(`
2022
2022
  `);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(`
2023
2023
  lint: ${n(`${e.warnings.length} warning(s).`)}`),i.join(`
2024
2024
  `)}function Zu(t){return t.cases.filter(e=>e.status==="failed").length}function kn(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function bv(t){let e=Zu(t),r=[];r.push('<?xml version="1.0" encoding="UTF-8"?>'),r.push(`<testsuite name="${kn(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let n of t.cases){let o=` <testcase name="${kn(n.name)}"`;if(n.status==="passed"){r.push(`${o} />`);continue}r.push(`${o}>`);let s=n.detail??"failed",i=n.type?` type="${kn(n.type)}"`:"";r.push(` <failure${i} message="${kn(s)}">${kn(s)}</failure>`),r.push(" </testcase>")}return r.push("</testsuite>"),`${r.join(`
2025
2025
  `)}
2026
2026
  `}function wv(t){let e={suite:t.name,tests:t.cases.length,failures:Zu(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
2027
- `}function Vo(t,e){return e==="junit"?bv(t):wv(t)}var Ge={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"},Ee={hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",clearLine:"\x1B[2K",clearToEnd:"\x1B[0J",col0:"\r",cursorUp:t=>`\x1B[${t}A`},Or=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],nt={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},Qu=/\x1b\[[0-9;]*m/g;function Nt(t){return t.replace(Qu,"").length}function ua(t,e){return e<=0?1:Math.max(1,Math.ceil(Nt(t)/e))}function vv(){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 pa=vv();function Ie(){return pa}function ma(t){pa=t}function Ne(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function ot(t,e){return pa?`${t}${e}${Ge.reset}`:e}var m={bold:t=>ot(Ge.bold,t),dim:t=>ot(Ge.dim,t),red:t=>ot(Ge.red,t),green:t=>ot(Ge.green,t),yellow:t=>ot(Ge.yellow,t),blue:t=>ot(Ge.blue,t),magenta:t=>ot(Ge.magenta,t),cyan:t=>ot(Ge.cyan,t),grey:t=>ot(Ge.grey,t)};var ve={success:t=>`${m.green("\u2713")} ${t}`,error:t=>`${m.red("\u2716")} ${t}`,warn:t=>`${m.yellow("\u26A0")} ${t}`,info:t=>`${m.dim("\xB7")} ${t}`,step:t=>`${m.cyan("\u25B8")} ${t}`},Vt={add:t=>m.green(`+ ${t}`),change:t=>m.yellow(`~ ${t}`),destroy:t=>m.red(`- ${t}`)},_v=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),Sv=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),kv=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function Nr(t){let e=t.toLowerCase();return _v.has(e)?m.green(t):Sv.has(e)?m.red(t):kv.has(e)?m.yellow(t):t}function Gt(t,e=[]){let r=Math.max(Nt(t),...e.map(Nt),0),n=r+2,o=m.cyan(nt.v),s=a=>` ${a}${" ".repeat(r-Nt(a))} `,i=[m.cyan(`${nt.tl}${nt.h.repeat(n)}${nt.tr}`),`${o}${m.bold(s(t))}${o}`];if(e.length){i.push(`${m.cyan(nt.ml)}${m.dim(nt.h.repeat(n))}${m.cyan(nt.mr)}`);for(let a of e)i.push(`${o}${s(a)}${o}`)}return i.push(m.cyan(`${nt.bl}${nt.h.repeat(n)}${nt.br}`)),i.join(`
2028
- `)}function ft(t,e={}){let r=e.indent??" ",n=e.gap??" ",o=e.head?[e.head,...t]:t,s=Math.max(0,...o.map(d=>d.length)),i=[];for(let d=0;d<s;d+=1)i[d]=Math.max(0,...o.map(p=>Nt(p[d]??"")));let a=d=>{let p=d.map((f,_)=>{let y=f??"";return _===d.length-1?y:y+" ".repeat(Math.max(0,i[_]-Nt(y)))});return r+p.join(n)},l=[];e.head&&(l.push(a(e.head.map(d=>m.bold(d)))),l.push(a(e.head.map((d,p)=>m.dim("\u2500".repeat(i[p]??Nt(d)))))));for(let d of t)l.push(a(d));return l.join(`
2029
- `)}function ha(t="the CLI for your Turbobase instance"){let e=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D"," \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2557 "," \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u255A\u2550\u2550\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D "," \u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"];return`${Ie()?e.map(n=>ot(Ge.cyan,n)).join(`
2027
+ `}function Vo(t,e){return e==="junit"?bv(t):wv(t)}var Ge={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"},Ee={hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",clearLine:"\x1B[2K",clearToEnd:"\x1B[0J",col0:"\r",cursorUp:t=>`\x1B[${t}A`},Or=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],nt={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},Qu=/\x1b\[[0-9;]*m/g;function Nt(t){return t.replace(Qu,"").length}function ua(t,e){return e<=0?1:Math.max(1,Math.ceil(Nt(t)/e))}function vv(){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 pa=vv();function Ie(){return pa}function ha(t){pa=t}function Ne(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function ot(t,e){return pa?`${t}${e}${Ge.reset}`:e}var h={bold:t=>ot(Ge.bold,t),dim:t=>ot(Ge.dim,t),red:t=>ot(Ge.red,t),green:t=>ot(Ge.green,t),yellow:t=>ot(Ge.yellow,t),blue:t=>ot(Ge.blue,t),magenta:t=>ot(Ge.magenta,t),cyan:t=>ot(Ge.cyan,t),grey:t=>ot(Ge.grey,t)};var ve={success:t=>`${h.green("\u2713")} ${t}`,error:t=>`${h.red("\u2716")} ${t}`,warn:t=>`${h.yellow("\u26A0")} ${t}`,info:t=>`${h.dim("\xB7")} ${t}`,step:t=>`${h.cyan("\u25B8")} ${t}`},Vt={add:t=>h.green(`+ ${t}`),change:t=>h.yellow(`~ ${t}`),destroy:t=>h.red(`- ${t}`)},_v=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),Sv=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),kv=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function Nr(t){let e=t.toLowerCase();return _v.has(e)?h.green(t):Sv.has(e)?h.red(t):kv.has(e)?h.yellow(t):t}function Gt(t,e=[]){let r=Math.max(Nt(t),...e.map(Nt),0),n=r+2,o=h.cyan(nt.v),s=a=>` ${a}${" ".repeat(r-Nt(a))} `,i=[h.cyan(`${nt.tl}${nt.h.repeat(n)}${nt.tr}`),`${o}${h.bold(s(t))}${o}`];if(e.length){i.push(`${h.cyan(nt.ml)}${h.dim(nt.h.repeat(n))}${h.cyan(nt.mr)}`);for(let a of e)i.push(`${o}${s(a)}${o}`)}return i.push(h.cyan(`${nt.bl}${nt.h.repeat(n)}${nt.br}`)),i.join(`
2028
+ `)}function ft(t,e={}){let r=e.indent??" ",n=e.gap??" ",o=e.head?[e.head,...t]:t,s=Math.max(0,...o.map(d=>d.length)),i=[];for(let d=0;d<s;d+=1)i[d]=Math.max(0,...o.map(p=>Nt(p[d]??"")));let a=d=>{let p=d.map((f,_)=>{let y=f??"";return _===d.length-1?y:y+" ".repeat(Math.max(0,i[_]-Nt(y)))});return r+p.join(n)},l=[];e.head&&(l.push(a(e.head.map(d=>h.bold(d)))),l.push(a(e.head.map((d,p)=>h.dim("\u2500".repeat(i[p]??Nt(d)))))));for(let d of t)l.push(a(d));return l.join(`
2029
+ `)}function ma(t="the CLI for your Turbobase instance"){let e=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D"," \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2557 "," \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u255A\u2550\u2550\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D "," \u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"];return`${Ie()?e.map(n=>ot(Ge.cyan,n)).join(`
2030
2030
  `):e.join(`
2031
2031
  `)}
2032
- ${m.dim(` ${t}`)}`}var st=t=>{process.stderr.write(t)};function Go(){return Ie()&&process.stderr.isTTY===!0}function ep(t,e=15){let r=Math.max(0,Math.min(100,t??0)),n=Math.round(r/100*e);return`${"\u2588".repeat(n)}${m.dim("\u2591".repeat(e-n))}`}async function J(t,e){let r=Go(),n=0,o;r&&(st(Ee.hideCursor),o=setInterval(()=>{st(`${Ee.col0}${Ee.clearLine}${m.magenta(Or[n++%Or.length])} ${t}`)},80));let s=()=>{o&&clearInterval(o),r&&st(`${Ee.col0}${Ee.clearLine}${Ee.showCursor}`)};try{let i=await e();return s(),r&&st(`${ve.success(t)}
2032
+ ${h.dim(` ${t}`)}`}var st=t=>{process.stderr.write(t)};function Go(){return Ie()&&process.stderr.isTTY===!0}function ep(t,e=15){let r=Math.max(0,Math.min(100,t??0)),n=Math.round(r/100*e);return`${"\u2588".repeat(n)}${h.dim("\u2591".repeat(e-n))}`}async function J(t,e){let r=Go(),n=0,o;r&&(st(Ee.hideCursor),o=setInterval(()=>{st(`${Ee.col0}${Ee.clearLine}${h.magenta(Or[n++%Or.length])} ${t}`)},80));let s=()=>{o&&clearInterval(o),r&&st(`${Ee.col0}${Ee.clearLine}${Ee.showCursor}`)};try{let i=await e();return s(),r&&st(`${ve.success(t)}
2033
2033
  `),i}catch(i){throw s(),r&&st(`${ve.error(t)}
2034
- `),i}}function fa(t){let e=0,r={stage:"queued"},n=!1,o=()=>{let l=m.magenta(Or[e%Or.length]),d=m.cyan(r.stage),p=r.runStatus?` ${m.dim(`(${r.runStatus})`)}`:"",f=`${String(Math.round(r.percent??0)).padStart(3)}%`;return`${l} ${t} ${m.dim("\u25B8")} ${d}${p} ${ep(r.percent)} ${f}`},s=()=>{st(`${Ee.col0}${Ee.clearLine}${o()}`),n=!0},i=()=>{n&&st(`${Ee.col0}${Ee.clearLine}`),n=!1};st(Ee.hideCursor);let a=setInterval(()=>{e+=1,s()},80);return{log(l){i(),st(`${l}
2035
- `),s()},status(l){r=l,s()},done(l){clearInterval(a),i(),st(Ee.showCursor);let d=l.stage!=="failed",p=`${t} ${m.dim("\u25B8")} ${Tv(l.stage)}${l.runStatus?` (${l.runStatus})`:""}`;st(`${d?ve.success(p):ve.error(p)}
2036
- `)},stop(){clearInterval(a),i(),st(Ee.showCursor)}}}function Tv(t){return t==="completed"?m.green(t):t==="failed"?m.red(t):m.cyan(t)}function Le(t,e,r={}){return new Promise((n,o)=>{let s=e.findIndex(R=>!R.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=R=>{process.stderr.write(R)},l=process.stdin,d=l.isRaw;l.setRawMode?.(!0),l.resume(),a(`${m.bold(m.cyan("?"))} ${m.bold(t)}
2037
- `),a(`${m.dim(" (\u2191/\u2193 to move, enter to select, ctrl+c to abort)")}
2038
- `),a(Ee.hideCursor);let p=0,f=()=>{let R=process.stderr.columns??process.stdout.columns??80;p>0&&(a(Ee.cursorUp(p)),a(Ee.clearToEnd));let $=0;for(let P=0;P<e.length;P+=1){let I=e[P],D=P===i,Y=D?m.cyan("\u25B6"):" ",F=I.disabled?m.grey(I.label):D?m.bold(m.cyan(I.label)):I.label,Oe=I.description?` ${m.dim(I.description)}`:"",Ce=` ${Y} ${F}${Oe}`;a(`\r${Ce}
2034
+ `),i}}function fa(t){let e=0,r={stage:"queued"},n=!1,o=()=>{let l=h.magenta(Or[e%Or.length]),d=h.cyan(r.stage),p=r.runStatus?` ${h.dim(`(${r.runStatus})`)}`:"",f=`${String(Math.round(r.percent??0)).padStart(3)}%`;return`${l} ${t} ${h.dim("\u25B8")} ${d}${p} ${ep(r.percent)} ${f}`},s=()=>{st(`${Ee.col0}${Ee.clearLine}${o()}`),n=!0},i=()=>{n&&st(`${Ee.col0}${Ee.clearLine}`),n=!1};st(Ee.hideCursor);let a=setInterval(()=>{e+=1,s()},80);return{log(l){i(),st(`${l}
2035
+ `),s()},status(l){r=l,s()},done(l){clearInterval(a),i(),st(Ee.showCursor);let d=l.stage!=="failed",p=`${t} ${h.dim("\u25B8")} ${Tv(l.stage)}${l.runStatus?` (${l.runStatus})`:""}`;st(`${d?ve.success(p):ve.error(p)}
2036
+ `)},stop(){clearInterval(a),i(),st(Ee.showCursor)}}}function Tv(t){return t==="completed"?h.green(t):t==="failed"?h.red(t):h.cyan(t)}function Le(t,e,r={}){return new Promise((n,o)=>{let s=e.findIndex(R=>!R.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=R=>{process.stderr.write(R)},l=process.stdin,d=l.isRaw;l.setRawMode?.(!0),l.resume(),a(`${h.bold(h.cyan("?"))} ${h.bold(t)}
2037
+ `),a(`${h.dim(" (\u2191/\u2193 to move, enter to select, ctrl+c to abort)")}
2038
+ `),a(Ee.hideCursor);let p=0,f=()=>{let R=process.stderr.columns??process.stdout.columns??80;p>0&&(a(Ee.cursorUp(p)),a(Ee.clearToEnd));let $=0;for(let P=0;P<e.length;P+=1){let I=e[P],D=P===i,Y=D?h.cyan("\u25B6"):" ",F=I.disabled?h.grey(I.label):D?h.bold(h.cyan(I.label)):I.label,Oe=I.description?` ${h.dim(I.description)}`:"",Ce=` ${Y} ${F}${Oe}`;a(`\r${Ce}
2039
2039
  `),$+=ua(Ce,R)}p=$},_=()=>{l.removeListener("data",k),l.setRawMode?.(d??!1),l.pause(),a(Ee.showCursor)},y=R=>{let $=i;for(let P=0;P<e.length;P+=1)if($=($+R+e.length)%e.length,!e[$].disabled){i=$;return}},k=R=>{let $=R.toString("utf8");if($===""||$==="q"){_(),a(`
2040
2040
  `),o(new Error("aborted"));return}if($==="\r"||$===`
2041
2041
  `){let I=e[i];if(I.disabled)return;_(),n(I.value);return}if($==="\x1B[A"||$==="k"){y(-1),f();return}if($==="\x1B[B"||$==="j"){y(1),f();return}let P=Number($);Number.isFinite(P)&&P>=1&&P<=e.length&&!e[P-1].disabled&&(i=P-1,f())};l.on("data",k),f()})}function Wo(t,e){return`${Nr(t)}${" ".repeat(Math.max(0,e-t.length))}`}var rp=t=>new Promise(e=>setTimeout(e,t));function tp(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}] ${Wo(t.state,9)} ${t.conduitId} \u2192 ${e}${n} hop=${t.hop}${o}${r}`}async function np(t,e,r={}){let n=r.sink??(p=>{process.stdout.write(`${p}
2042
2042
  `)}),o=r.sleep??rp,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 p of[...i].reverse())n(tp(p)),a+=1,p.updatedAt>l&&(l=p.updatedAt);if(!r.follow)return a;let d=r.maxPolls??Number.POSITIVE_INFINITY;for(let p=0;p<d;p+=1){await o(s);let f=await t.conduitEvents(e,{since:l||void 0,limit:200});for(let _ of[...f].reverse())n(tp(_)),a+=1,_.updatedAt>l&&(l=_.updatedAt)}return a}function xv(t){let e=t.externalId??"\u2014",r=t.createdByConduit?` via=${t.createdByConduit}`:"",n=t.lastError?` last_error="${t.lastError}"`:"";return`${t.id} ${Wo(t.writeStatus,9)} ${t.sourceSystem}/${e} role=${t.role} master=${t.masterTable}/${t.masterRowId}${r}${n}`}async function op(t,e={}){let r=e.sink??(o=>{process.stdout.write(`${o}
2043
2043
  `)});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(xv(o));return r(`
2044
2044
  binding: ${n.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:n.length}}function Rv(t){let e=Object.entries(t.detail??{}).map(([i,a])=>`${i}=${typeof a=="string"?JSON.stringify(a):String(a)}`).join(" "),r=[t.sourceSystem,t.recordType,t.subjectId].filter(Boolean).join("/"),n=t.occurrences>1?` x${t.occurrences}`:"",o=t.redaction?.length?` redacted=[${t.redaction.join(",")}]`:"",s=t.correlationId?` corr=${t.correlationId}`:"";return`[${t.ts}] ${Wo(t.severity,5)} ${Wo(t.outcome,8)} ${t.code}${n}${r?` ${r}`:""}${s}${e?` ${e}`:""}${o}`}async function sp(t,e={}){let r=e.sink??(P=>{process.stdout.write(`${P}
2045
- `)}),n=e.sleep??rp,o=e.intervalMs??2e3,{follow:s,maxPolls:i,json:a,sink:l,sleep:d,intervalMs:p,...f}=e,_=P=>{r(a?JSON.stringify(P):Rv(P))},y=await t.platformEvents({...f,limit:f.limit??100});if(y.length===0&&!s)return r("logs: no events matched."),0;let k=0,R="";for(let P of[...y].reverse())_(P),k+=1,P.ts>R&&(R=P.ts);if(!s)return k;let $=i??Number.POSITIVE_INFINITY;for(let P=0;P<$;P+=1){await n(o);let I=await t.platformEvents({...f,...R?{after:R,since:void 0}:{},limit:200});for(let D of[...I].reverse())_(D),k+=1,D.ts>R&&(R=D.ts)}return k}Jo();Fo();function ap(t,e={}){return t.learningIngestError?{level:"warn",message:`warning: learning ingest was not queued (${t.learningIngestError}). The version is live, but the findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT read. Re-deploy to retry.`}:t.learningIngestTaskId?t.learningSourceRev===null?{level:"warn",message:"warning: this app has no pushed source, so the ingest has nothing to read. The findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT ingested \u2014 deploy uploads the built bundle, `apps push` records the markdown. Run `turbobase apps push <app> .`, then deploy again."}:typeof t.learningSourceRev=="number"?e.localDocsModifiedAt&&t.learningSourceAt&&e.localDocsModifiedAt.getTime()>Date.parse(t.learningSourceAt)?{level:"warn",message:`warning: learning ingest queued (task ${t.learningIngestTaskId}), but it reads source rev ${t.learningSourceRev} and your standing markdown has changed since that push. Those findings will NOT be ingested. Run \`turbobase apps push <app> .\`, then deploy again.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}) \u2014 reading source rev ${t.learningSourceRev}.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}).`}:null}var dp=9,Tn=" ".repeat(2+dp);function Lr(t,e=r=>r){return e(t)+" ".repeat(Math.max(1,dp-t.length))}function Cv(t,e,r){return t===1?e:r}function up(t){return t?m.dim(` (${t} holder${t===1?"":"s"} re-stamped)`):""}function pp(t){return t.length>0?`[${t.join(", ")}]`:"unrestricted"}function Iv(t){if(!t)return[];let e=[],r=t.addedGrants??[],n=t.removedGrants??[];if(r.length>0||n.length>0){let s=[...r.map(i=>`+${i}`),...n.map(i=>`\u2212${i}`)];e.push(`content ${s.join(" ")}`)}let o=t.setRestrictions??{};for(let s of Object.keys(o).sort())e.push(`${s} \u2192 ${pp(o[s]??[])}`);return e}function lp(t){let e=[],r=t.scopeChanges?.adoptedGrants??[];r.length>0&&e.push({stream:"out",text:m.dim(`${Tn}adopted (already on the role \u2014 the admin's, never retired by this app): ${r.join(", ")}`)});let n=t.scopeChanges?.adoptedRestrictions??{};for(let s of Object.keys(n).sort())e.push({stream:"out",text:m.dim(`${Tn}adopted ${s} ${pp(n[s]??[])} (already on the role \u2014 the admin's, never cleared or widened by this app)`)});let o=[...t.keptRemovedCapabilities??[],...t.scopeChanges?.keptRemovedGrants??[]];o.length>0&&e.push({stream:"out",text:m.dim(`${Tn}kept (admin removed): ${o.join(", ")}`)});for(let s of t.scopeChanges?.keptAdminRestrictions??[])e.push({stream:"out",text:m.dim(`${Tn}kept admin value for ${s}`)});for(let s of t.warnings??[])e.push({stream:"out",text:m.yellow(`${Tn}! ${s}`)});return e}function mp(t){return(t.warnings?.length??0)>0||(t.keptRemovedCapabilities?.length??0)>0||(t.scopeChanges?.keptRemovedGrants?.length??0)>0||(t.scopeChanges?.keptAdminRestrictions?.length??0)>0}function cp(t){return mp(t)||(t.scopeChanges?.adoptedGrants?.length??0)>0||Object.keys(t.scopeChanges?.adoptedRestrictions??{}).length>0}function Ov(t,e,r){let n=r==="applied",o=Iv(t.scopeChanges),s=n?up(t.holdersRestamped):"",i=l=>{let d=[...l,...o];return d.length>0?` ${m.dim(d.join(" "))}`:""};if(t.action==="error")return[{stream:"err",text:` ${Lr("ERROR",m.bold)}${e} \u2014 ${t.message??"cannot be created"}`},...lp(t)];let a;if(t.action==="create"){let l=t.addCapabilities?.length??0;a=` ${Lr(n?"created":"create")}${e}${i([`${l} ${Cv(l,"capability","capabilities")}`])}${s}`}else if(t.action==="add_capabilities"){let l=(t.addCapabilities??[]).map(d=>`+${d}`).join(", ");a=` ${Lr(n?"updated":"add")}${e}${i([l])}${s}`}else t.action==="update_scopes"?a=` ${Lr(n?"updated":"update")}${e}${o.length>0?i([]):` ${m.dim("scopes changed")}`}${s}`:t.action==="noop"?a=` ${Lr("ok",m.dim)}${e} ${m.dim("already up to date")}`:a=` ${Lr(n?"changed":"change")}${e}${i([])} ${m.dim("(upgrade the CLI to see details)")}${s}`;return[{stream:"out",text:a},...lp(t)]}function Nv(t,e){let r=[];for(let n of t){if(!n.removedGrants||n.removedGrants.length===0)continue;let o=n.removedGrants.map(i=>`\u2212${i}`).join(" "),s=e==="applied"?"retired":"retire";r.push({stream:"out",text:` ${s} grants on ${n.name}: ${m.dim(o)}${e==="applied"?up(n.holdersRestamped):""}`})}return r}function hp(t){let{mode:e}=t,r=t.verdicts??[],n=e==="plan"?r:r.filter(d=>d.action!=="noop"||cp(d)),o=Nv(t.retired??[],e);if(n.length===0&&o.length===0)return[];let s=[{stream:"out",text:""},{stream:"out",text:m.bold(e==="preview"?"roles (preview \u2014 not applied)":"roles")}],i=n.length>0?Math.max(...n.map(d=>d.name.length)):0;for(let d of n)s.push(...Ov(d,d.name.padEnd(i),e));s.push(...o);let a=n.some(d=>Lv.has(d.action)),l=n.every(d=>d.action==="noop");if(a){let d=e==="plan"?" roles are created at deploy \u2014 a declared role has no holders until an admin assigns it in Admin \u2192 Users.":e==="preview"?" nothing was created \u2014 promoting this preview applies them.":" assign these in Admin \u2192 Users \u2014 a declared role has no holders until you do.";s.push({stream:"out",text:m.dim(d)})}else if(o.length===0&&l&&n.some(d=>cp(d))){let d=e==="applied"?"no role changed":e==="preview"?"no role would change on promote":"no role would change",p=n.some(f=>mp(f))?"each note above recurs on every deploy until the manifest or the role is changed.":"the adopted values were already on the roles.";s.push({stream:"out",text:m.dim(` ${d} \u2014 ${p}`)})}return s}var Lv=new Set(["create","add_capabilities","update_scopes"]);function ga(t){let{app:e,roles:r}=t;if(r===null)return[];let n=(o,s)=>[{stream:"out",text:""},{stream:"out",text:m.yellow(`! ${o}`)},{stream:"out",text:m.dim(` ${s}`)}];if(r.length===0){let o='"roles": [] retires the content values this app added to roles on an earlier deploy.';return e===null?n(o,"pass --app <slug> so the plan can name them."):Array.isArray(t.retired)?t.retired.some(s=>(s.removedGrants?.length??0)>0)?[]:[{stream:"out",text:""},{stream:"out",text:m.dim(' "roles": [] \u2014 no content value this app added is on a role, so a deploy retires nothing.')}]:n(o,"this instance's plan does not list them \u2014 read the roles section the deploy prints.")}return e===null&&r.some(o=>o.scopes!==void 0&&o.scopes!==null)?n("a declared role carries scopes, but no app was named \u2014 pass --app <slug> (or --as app:<slug>).","without it this plan cannot tell this app's earlier declarations from another app's: a scope another deploy declared on the same role is not planned (the deploy decides it, and may refuse), and content values the deploy would retire are not listed."):[]}function fp(t){let e=t.roles;return Array.isArray(e)?{verdicts:e,retired:t.rolesRetired??[]}:e&&typeof e=="object"?{verdicts:e.verdicts??[],retired:e.retired??t.rolesRetired??[]}:{verdicts:[],retired:t.rolesRetired??[]}}var ya=".github/workflows/turbobase-release-deploy.yml",jv=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2045
+ `)}),n=e.sleep??rp,o=e.intervalMs??2e3,{follow:s,maxPolls:i,json:a,sink:l,sleep:d,intervalMs:p,...f}=e,_=P=>{r(a?JSON.stringify(P):Rv(P))},y=await t.platformEvents({...f,limit:f.limit??100});if(y.length===0&&!s)return r("logs: no events matched."),0;let k=0,R="";for(let P of[...y].reverse())_(P),k+=1,P.ts>R&&(R=P.ts);if(!s)return k;let $=i??Number.POSITIVE_INFINITY;for(let P=0;P<$;P+=1){await n(o);let I=await t.platformEvents({...f,...R?{after:R,since:void 0}:{},limit:200});for(let D of[...I].reverse())_(D),k+=1,D.ts>R&&(R=D.ts)}return k}Jo();Fo();function ap(t,e={}){return t.learningIngestError?{level:"warn",message:`warning: learning ingest was not queued (${t.learningIngestError}). The version is live, but the findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT read. Re-deploy to retry.`}:t.learningIngestTaskId?t.learningSourceRev===null?{level:"warn",message:"warning: this app has no pushed source, so the ingest has nothing to read. The findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT ingested \u2014 deploy uploads the built bundle, `apps push` records the markdown. Run `turbobase apps push <app> .`, then deploy again."}:typeof t.learningSourceRev=="number"?e.localDocsModifiedAt&&t.learningSourceAt&&e.localDocsModifiedAt.getTime()>Date.parse(t.learningSourceAt)?{level:"warn",message:`warning: learning ingest queued (task ${t.learningIngestTaskId}), but it reads source rev ${t.learningSourceRev} and your standing markdown has changed since that push. Those findings will NOT be ingested. Run \`turbobase apps push <app> .\`, then deploy again.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}) \u2014 reading source rev ${t.learningSourceRev}.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}).`}:null}var dp=9,Tn=" ".repeat(2+dp);function Lr(t,e=r=>r){return e(t)+" ".repeat(Math.max(1,dp-t.length))}function Cv(t,e,r){return t===1?e:r}function up(t){return t?h.dim(` (${t} holder${t===1?"":"s"} re-stamped)`):""}function pp(t){return t.length>0?`[${t.join(", ")}]`:"unrestricted"}function Iv(t){if(!t)return[];let e=[],r=t.addedGrants??[],n=t.removedGrants??[];if(r.length>0||n.length>0){let s=[...r.map(i=>`+${i}`),...n.map(i=>`\u2212${i}`)];e.push(`content ${s.join(" ")}`)}let o=t.setRestrictions??{};for(let s of Object.keys(o).sort())e.push(`${s} \u2192 ${pp(o[s]??[])}`);return e}function lp(t){let e=[],r=t.scopeChanges?.adoptedGrants??[];r.length>0&&e.push({stream:"out",text:h.dim(`${Tn}adopted (already on the role \u2014 the admin's, never retired by this app): ${r.join(", ")}`)});let n=t.scopeChanges?.adoptedRestrictions??{};for(let s of Object.keys(n).sort())e.push({stream:"out",text:h.dim(`${Tn}adopted ${s} ${pp(n[s]??[])} (already on the role \u2014 the admin's, never cleared or widened by this app)`)});let o=[...t.keptRemovedCapabilities??[],...t.scopeChanges?.keptRemovedGrants??[]];o.length>0&&e.push({stream:"out",text:h.dim(`${Tn}kept (admin removed): ${o.join(", ")}`)});for(let s of t.scopeChanges?.keptAdminRestrictions??[])e.push({stream:"out",text:h.dim(`${Tn}kept admin value for ${s}`)});for(let s of t.warnings??[])e.push({stream:"out",text:h.yellow(`${Tn}! ${s}`)});return e}function hp(t){return(t.warnings?.length??0)>0||(t.keptRemovedCapabilities?.length??0)>0||(t.scopeChanges?.keptRemovedGrants?.length??0)>0||(t.scopeChanges?.keptAdminRestrictions?.length??0)>0}function cp(t){return hp(t)||(t.scopeChanges?.adoptedGrants?.length??0)>0||Object.keys(t.scopeChanges?.adoptedRestrictions??{}).length>0}function Ov(t,e,r){let n=r==="applied",o=Iv(t.scopeChanges),s=n?up(t.holdersRestamped):"",i=l=>{let d=[...l,...o];return d.length>0?` ${h.dim(d.join(" "))}`:""};if(t.action==="error")return[{stream:"err",text:` ${Lr("ERROR",h.bold)}${e} \u2014 ${t.message??"cannot be created"}`},...lp(t)];let a;if(t.action==="create"){let l=t.addCapabilities?.length??0;a=` ${Lr(n?"created":"create")}${e}${i([`${l} ${Cv(l,"capability","capabilities")}`])}${s}`}else if(t.action==="add_capabilities"){let l=(t.addCapabilities??[]).map(d=>`+${d}`).join(", ");a=` ${Lr(n?"updated":"add")}${e}${i([l])}${s}`}else t.action==="update_scopes"?a=` ${Lr(n?"updated":"update")}${e}${o.length>0?i([]):` ${h.dim("scopes changed")}`}${s}`:t.action==="noop"?a=` ${Lr("ok",h.dim)}${e} ${h.dim("already up to date")}`:a=` ${Lr(n?"changed":"change")}${e}${i([])} ${h.dim("(upgrade the CLI to see details)")}${s}`;return[{stream:"out",text:a},...lp(t)]}function Nv(t,e){let r=[];for(let n of t){if(!n.removedGrants||n.removedGrants.length===0)continue;let o=n.removedGrants.map(i=>`\u2212${i}`).join(" "),s=e==="applied"?"retired":"retire";r.push({stream:"out",text:` ${s} grants on ${n.name}: ${h.dim(o)}${e==="applied"?up(n.holdersRestamped):""}`})}return r}function mp(t){let{mode:e}=t,r=t.verdicts??[],n=e==="plan"?r:r.filter(d=>d.action!=="noop"||cp(d)),o=Nv(t.retired??[],e);if(n.length===0&&o.length===0)return[];let s=[{stream:"out",text:""},{stream:"out",text:h.bold(e==="preview"?"roles (preview \u2014 not applied)":"roles")}],i=n.length>0?Math.max(...n.map(d=>d.name.length)):0;for(let d of n)s.push(...Ov(d,d.name.padEnd(i),e));s.push(...o);let a=n.some(d=>Lv.has(d.action)),l=n.every(d=>d.action==="noop");if(a){let d=e==="plan"?" roles are created at deploy \u2014 a declared role has no holders until an admin assigns it in Admin \u2192 Users.":e==="preview"?" nothing was created \u2014 promoting this preview applies them.":" assign these in Admin \u2192 Users \u2014 a declared role has no holders until you do.";s.push({stream:"out",text:h.dim(d)})}else if(o.length===0&&l&&n.some(d=>cp(d))){let d=e==="applied"?"no role changed":e==="preview"?"no role would change on promote":"no role would change",p=n.some(f=>hp(f))?"each note above recurs on every deploy until the manifest or the role is changed.":"the adopted values were already on the roles.";s.push({stream:"out",text:h.dim(` ${d} \u2014 ${p}`)})}return s}var Lv=new Set(["create","add_capabilities","update_scopes"]);function ga(t){let{app:e,roles:r}=t;if(r===null)return[];let n=(o,s)=>[{stream:"out",text:""},{stream:"out",text:h.yellow(`! ${o}`)},{stream:"out",text:h.dim(` ${s}`)}];if(r.length===0){let o='"roles": [] retires the content values this app added to roles on an earlier deploy.';return e===null?n(o,"pass --app <slug> so the plan can name them."):Array.isArray(t.retired)?t.retired.some(s=>(s.removedGrants?.length??0)>0)?[]:[{stream:"out",text:""},{stream:"out",text:h.dim(' "roles": [] \u2014 no content value this app added is on a role, so a deploy retires nothing.')}]:n(o,"this instance's plan does not list them \u2014 read the roles section the deploy prints.")}return e===null&&r.some(o=>o.scopes!==void 0&&o.scopes!==null)?n("a declared role carries scopes, but no app was named \u2014 pass --app <slug> (or --as app:<slug>).","without it this plan cannot tell this app's earlier declarations from another app's: a scope another deploy declared on the same role is not planned (the deploy decides it, and may refuse), and content values the deploy would retire are not listed."):[]}function fp(t){let e=t.roles;return Array.isArray(e)?{verdicts:e,retired:t.rolesRetired??[]}:e&&typeof e=="object"?{verdicts:e.verdicts??[],retired:e.retired??t.rolesRetired??[]}:{verdicts:[],retired:t.rolesRetired??[]}}var ya=".github/workflows/turbobase-release-deploy.yml",jv=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2046
2046
  # Turbobase release deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR repo)
2047
2047
  #
2048
2048
  # Epic #775 "GitHub is just a link": Turbobase hosts nothing and clones nothing.
@@ -2696,14 +2696,24 @@ and nothing factored into a shared module.
2696
2696
  Every read below runs under a real person's identity and their row-level
2697
2697
  permissions, never under a token's own.
2698
2698
 
2699
- Three ways to actually read rows:
2699
+ Four ways to actually read rows:
2700
2700
 
2701
2701
  - **In the app** \u2014 the browser session does it. \`src/lib/turbobase.ts\` is already
2702
2702
  wired for this; \`select()\` through it and RLS applies to the signed-in user.
2703
2703
  - **From your editor** \u2014 connect the **data MCP** as yourself, which signs you in
2704
2704
  once over OAuth and then exposes \`list_records\` / \`get_record\` / \`search_fields\`
2705
2705
  as tools. The connect URL is on your instance under Settings \u203A Integrations.
2706
- - **From a script or an unattended agent** \u2014 present a PAT carrying the
2706
+ - **From a script that is not an AI client** \u2014 a label printer, a warehouse
2707
+ script, an overnight integration \u2014 present a PAT carrying the
2708
+ **\`rest:read\`** permission as a bearer at **\`POST /v1/batch\`**, sending
2709
+ PostgREST query strings and getting their rows back. The request runs as the
2710
+ administrator who minted the token, under that person's row-level permissions.
2711
+ **\`rest:write\`** beside it reaches \`POST /v1/data/<recordType>\`, the upload
2712
+ route and \`DELETE /v1/data/<recordType>\` \u2014 the same write boundary this app
2713
+ goes through, so your hooks, guardrails and \`expectedSyncVersion\` all apply.
2714
+ \`/rest/v1\` still takes a browser session only, which is why a script reads
2715
+ through the batch endpoint.
2716
+ - **From an unattended AI client** \u2014 present a PAT carrying the
2707
2717
  **\`mcp:data\`** permission as a bearer at that same data-MCP endpoint. Reads run
2708
2718
  as the administrator who minted it, under that person's row-level permissions.
2709
2719
  It is never granted by default \u2014 an administrator ticks it deliberately when
@@ -2714,6 +2724,10 @@ Three ways to actually read rows:
2714
2724
  write setting on. Ask for one when there is nobody to complete a sign-in, or
2715
2725
  when a session expiring mid-job would strand the work.
2716
2726
 
2727
+ Neither pair implies the other: a token connected to the data MCP is not thereby
2728
+ allowed on the web interface, and each read permission is refused the matching
2729
+ write on its own.
2730
+
2717
2731
  **\`permission denied for table <x>\` usually means NOT SIGNED IN.** With no
2718
2732
  session, PostgREST answers as the anonymous role and every table denies \u2014 it
2719
2733
  reads like an RLS problem and is not one. Check the session before the grants.
@@ -2818,7 +2832,7 @@ a test. \`turbobase apps deploy\` reads both files and queues what it finds for
2818
2832
  review, so what you write reaches the knowledge base and the product team instead
2819
2833
  of evaporating at the end of the session. Keep the section headings exactly as
2820
2834
  they are \u2014 the ingest finds entries by heading, not by filename.
2821
- `}var jr="customer",hr="email",Vv="^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$",Gv=`// EXAMPLE \u2014 a business rule that holds for EVERY writer, not just this app.
2835
+ `}var jr="customer",mr="email",Vv="^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$",Gv=`// EXAMPLE \u2014 a business rule that holds for EVERY writer, not just this app.
2822
2836
  //
2823
2837
  // It runs inside \`POST /v1/data\`, which is the only way an app can write at all:
2824
2838
  // the \`authenticated\` role holds no INSERT/UPDATE/DELETE on the mirror, so a
@@ -2837,8 +2851,8 @@ they are \u2014 the ingest finds entries by heading, not by filename.
2837
2851
  // Pure and credentials-free: no secrets, no network, no Node builtins, one
2838
2852
  // concern per file, nothing factored into a shared module (the sandbox fences
2839
2853
  // every import except the SDK).
2840
- `;function Wv(){let t=Rt("hook",{recordType:jr,event:"before_save",template:"enforce-format",field:hr,regex:Vv,id:`app:${jr}:${hr}-format`,description:`Reject a ${jr} write whose ${hr} is not an address.`}),e=(r,n,o)=>JSON.stringify({name:o,context:{recordType:jr,event:"before_save",payload:r},expect:n},null,2)+`
2841
- `;return[{path:t.relativePath,content:`${Gv}${t.content}`},{path:`samples/${jr}.${hr}-ok.json`,content:e({company_name:"Acme Supply",[hr]:"ada@example.com"},"pass","a well-formed address passes")},{path:`samples/${jr}.${hr}-malformed.json`,content:e({company_name:"Acme Supply",[hr]:"ada-at-example"},"reject","a malformed address is rejected")}]}var Jv="---\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",Yv=`---
2854
+ `;function Wv(){let t=Rt("hook",{recordType:jr,event:"before_save",template:"enforce-format",field:mr,regex:Vv,id:`app:${jr}:${mr}-format`,description:`Reject a ${jr} write whose ${mr} is not an address.`}),e=(r,n,o)=>JSON.stringify({name:o,context:{recordType:jr,event:"before_save",payload:r},expect:n},null,2)+`
2855
+ `;return[{path:t.relativePath,content:`${Gv}${t.content}`},{path:`samples/${jr}.${mr}-ok.json`,content:e({company_name:"Acme Supply",[mr]:"ada@example.com"},"pass","a well-formed address passes")},{path:`samples/${jr}.${mr}-malformed.json`,content:e({company_name:"Acme Supply",[mr]:"ada-at-example"},"reject","a malformed address is rejected")}]}var Jv="---\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",Yv=`---
2842
2856
  name: ship-app
2843
2857
  description: Push the app's source to the instance and deploy it live. Use once the app has been previewed and works.
2844
2858
  ---
@@ -3779,11 +3793,11 @@ control, with a visible focus ring? A green \`npm run build\` proves none of the
3779
3793
  .mcp.json
3780
3794
 
3781
3795
  .DS_Store
3782
- `;function ba(t={}){let e=zv.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:c_(r)},{path:"INSTANCE-LEARNINGS.md",content:Qv(o)},{path:"TURBOBASE-FEEDBACK.md",content:e_(o)},{path:".claude/settings.json",content:o_},{path:`.claude/output-styles/${r_}.md`,content:n_},{path:".claude/skills/generate-types/SKILL.md",content:Bv(n)},{path:".claude/skills/record-learning/SKILL.md",content:Zv(o)},{path:".claude/skills/business-rule-to-hook/SKILL.md",content:Xv},{path:".claude/hooks/session-start-refresh-types.sh",content:t_(n,o),executable:!0},{path:".claude/hooks/check-rule-placement.sh",content:s_,executable:!0},{path:".claude/hooks/check-rule-placement.mjs",content:i_}];return r?[{path:"CLAUDE.md",content:Kv(t.appSlug)},...s,{path:".claude/skills/preview-app/SKILL.md",content:Jv},{path:".claude/skills/ship-app/SKILL.md",content:Yv},{path:".claude/skills/app-design/SKILL.md",content:l_},{path:".claude/skills/roles-and-permissions/SKILL.md",content:a_},...Wv(),{path:"conduits/.gitkeep",content:Yo},{path:"turbobase/sync.json",content:bp},{path:"turbobase/schedules.json",content:wp},...yp()]:[{path:"CLAUDE.md",content:qv},...s,{path:".claude/skills/mock-test/SKILL.md",content:Fv},{path:".claude/skills/deploy/SKILL.md",content:Hv},{path:"hooks/.gitkeep",content:Yo},{path:"conduits/.gitkeep",content:Yo},{path:"samples/.gitkeep",content:Yo},{path:"turbobase/sync.json",content:bp},{path:"turbobase/schedules.json",content:wp}]}import{promises as va}from"node:fs";import{dirname as d_,join as gt,resolve as Rp}from"node:path";function kp(t){return{version:1,...t?{tenant:t}:{},hooks:[],conduits:[],sync:{fields:[],tables:[]},guardrails:{validationHooks:[],fieldRules:[],conduits:[]},schedules:[]}}var xn="bundle.json",Xo="turbobase";function Tp(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 wa(a)}function wa(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(Sp)),tables:[...t.sync.tables].sort(e(r=>r.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(Sp)),conduits:[...t.guardrails.conduits].sort(e(r=>r.conduitId))},schedules:[...t.schedules].sort(e(r=>r.name))}}function Sp(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function xp(t,e){let r=(e??"").trim();if(!r)return{ok:!1,reason:"target instance slug is unknown \u2014 cannot confirm a promote"};let n=(t??"").trim();return n?n!==r?{ok:!1,reason:`--confirm "${n}" does not match the target instance "${r}" \u2014 refusing to apply`}:{ok:!0}:{ok:!1,reason:`--confirm <slug> is required for promote (expected "${r}")`}}var Qo="hooks",es="conduits",$p="processes",Wt="turbobase/sync.json",Jt="turbobase/schedules.json";function _a(t){let e=d=>{let p=new RegExp(`${d}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return p?p[2]:void 0},r=/\bdefineConduit\s*[<(]/.test(t),n=/\bdefineProcess\s*[<(]/.test(t),o=/\bdefineHook\s*[<(]/.test(t);if(!r&&!o&&!n)return null;let s=e("id"),i=e("recordType");if(n){let d=e("source")??"standalone";return s?{id:s,recordType:"*",event:"invoke",source:d,extensionKind:"process"}:null}if(r){let d=e("on"),p=e("source");return!s||!i||!d||!p?null:{id:s,recordType:i,event:d,source:p,extensionKind:"conduit"}}let a=e("event"),l=e("source")??"standalone";return!s||!i||!a?null:{id:s,recordType:i,event:a,source:l,extensionKind:"hook"}}function Sa(t){return/\bdefineProcess\s*[<(]/.test(t)?"could not read a quoted id \u2014 is it a defineProcess({...}) file? A process binds to no single record type; its steps carry their own.":/\bdefineConduit\s*[<(]/.test(t)?"could not read id / on / from.source / from.recordType \u2014 is it a defineConduit({...}) file?":"could not read id / recordType / event \u2014 is it a defineHook({...}) file?"}async function Rn(t){let e;try{e=await va.readdir(t,{withFileTypes:!0})}catch{return[]}let r=[];for(let n of e){if(n.isDirectory()){if(n.name.startsWith(".")||n.name==="node_modules")continue;for(let o of await Rn(gt(t,n.name)))r.push(`${n.name}/${o}`);continue}n.name.endsWith(".ts")&&(n.name.endsWith(".test.ts")||n.name.endsWith(".d.ts")||r.push(n.name))}return r.sort()}async function Zo(t,e){let r;try{r=await va.readFile(t,"utf8")}catch{return}try{return JSON.parse(r)}catch(n){throw new Error(`${e} is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}}function u_(t){return{sourceSystem:String(t.sourceSystem??""),recordType:String(t.recordType??""),fieldName:String(t.fieldName??""),owningSide:t.owningSide==="pg"?"pg":"source",caseSensitive:!!t.caseSensitive}}function p_(t){return{sourceRecordType:String(t.sourceRecordType??""),kind:String(t.kind??""),sourceSystem:String(t.sourceSystem??"")}}function m_(t){let e={name:String(t.name??""),scheduleKind:String(t.scheduleKind??"cron"),scheduleExpr:String(t.scheduleExpr??""),scheduleTz:String(t.scheduleTz??"UTC"),body:t.body??{}};return typeof t.status=="string"&&(e.status=t.status),e}async function Ep(t=process.cwd()){let e=Rp(t),[r,n,o]=await Promise.all([Rn(gt(e,Qo)),Rn(gt(e,es)),Rn(gt(e,$p))]);if(r.length>0||n.length>0||o.length>0)return!0;let[s,i]=await Promise.all([Zo(gt(e,Wt),Wt).catch(()=>{}),Zo(gt(e,Jt),Jt).catch(()=>{})]);return s!==void 0||i!==void 0}async function Pp(t=process.cwd(),e={}){let r=Rp(t),n=kp(e.tenant),o=[],s=[];for(let l of[Qo,es,$p])for(let d of await Rn(gt(r,l))){let p=`${l}/${d}`,f=await va.readFile(gt(r,l,d),"utf8"),_=e.inline?await e.inline(f,d_(gt(r,l,d))):f,y=_a(_);if(!y){/\bdefine(Hook|Conduit|Process)\s*[<(]/.test(_)&&s.push({file:p,reason:Sa(_)});continue}let k={id:y.id,kind:y.extensionKind,recordType:y.recordType,event:y.event,source:y.source,sourceCode:_};y.extensionKind==="conduit"?n.conduits.push(k):n.hooks.push(k),o.push(p)}let i=await Zo(gt(r,Wt),Wt);if(i!==void 0){if(typeof i!="object"||i===null||Array.isArray(i))throw new Error(`${Wt} must be a JSON object with "fields" and/or "tables".`);let l=i;for(let d of Array.isArray(l.fields)?l.fields:[])n.sync.fields.push(u_(d));for(let d of Array.isArray(l.tables)?l.tables:[])n.sync.tables.push(p_(d));o.push(Wt)}let a=await Zo(gt(r,Jt),Jt);if(a!==void 0){let l=Array.isArray(a)?a:Array.isArray(a.schedules)?a.schedules:null;if(l===null)throw new Error(`${Jt} must be a JSON array, or an object with a "schedules" array.`);for(let d of l)n.schedules.push(m_(d));o.push(Jt)}return n.guardrails.fieldRules=[...n.sync.fields],n.guardrails.validationHooks=n.hooks.filter(l=>l.event==="before_save").map(l=>l.id).sort(),{manifest:wa(n),contributed:o,unparsed:s}}import{promises as xa}from"node:fs";import{resolve as w_}from"node:path";var h_="For app developers \u2014 adopt these";function Ap(t){let e=/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?$/.exec(t.trim());return e?{core:[Number(e[1]),Number(e[2]??0),Number(e[3]??0)],prerelease:e[4]??""}:null}function Cp(t,e){let r=Ap(t),n=Ap(e);if(!r&&!n)return 0;if(!r)return-1;if(!n)return 1;for(let o=0;o<3;o++){let s=(r.core[o]??0)-(n.core[o]??0);if(s!==0)return s}return r.prerelease===n.prerelease?0:r.prerelease?n.prerelease?r.prerelease<n.prerelease?-1:1:-1:1}function f_(t){return t.replace(/[‐-―]/g,"-").toLowerCase().replace(/\s+/g," ").trim()}var UI=f_(h_);bn();ht();var g_=t=>new Promise(e=>setTimeout(e,t));function Ip(t){return t.stage==="completed"||t.stage==="failed"}function y_(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function b_(t,e,r){let n=t.outputTail??"";if(n&&n!==e){let s=(n.startsWith(e)?n.slice(e.length):n).replace(/\n+$/,"");if(s)for(let i of s.split(`
3796
+ `;function ba(t={}){let e=zv.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:c_(r)},{path:"INSTANCE-LEARNINGS.md",content:Qv(o)},{path:"TURBOBASE-FEEDBACK.md",content:e_(o)},{path:".claude/settings.json",content:o_},{path:`.claude/output-styles/${r_}.md`,content:n_},{path:".claude/skills/generate-types/SKILL.md",content:Bv(n)},{path:".claude/skills/record-learning/SKILL.md",content:Zv(o)},{path:".claude/skills/business-rule-to-hook/SKILL.md",content:Xv},{path:".claude/hooks/session-start-refresh-types.sh",content:t_(n,o),executable:!0},{path:".claude/hooks/check-rule-placement.sh",content:s_,executable:!0},{path:".claude/hooks/check-rule-placement.mjs",content:i_}];return r?[{path:"CLAUDE.md",content:Kv(t.appSlug)},...s,{path:".claude/skills/preview-app/SKILL.md",content:Jv},{path:".claude/skills/ship-app/SKILL.md",content:Yv},{path:".claude/skills/app-design/SKILL.md",content:l_},{path:".claude/skills/roles-and-permissions/SKILL.md",content:a_},...Wv(),{path:"conduits/.gitkeep",content:Yo},{path:"turbobase/sync.json",content:bp},{path:"turbobase/schedules.json",content:wp},...yp()]:[{path:"CLAUDE.md",content:qv},...s,{path:".claude/skills/mock-test/SKILL.md",content:Fv},{path:".claude/skills/deploy/SKILL.md",content:Hv},{path:"hooks/.gitkeep",content:Yo},{path:"conduits/.gitkeep",content:Yo},{path:"samples/.gitkeep",content:Yo},{path:"turbobase/sync.json",content:bp},{path:"turbobase/schedules.json",content:wp}]}import{promises as va}from"node:fs";import{dirname as d_,join as gt,resolve as Rp}from"node:path";function kp(t){return{version:1,...t?{tenant:t}:{},hooks:[],conduits:[],sync:{fields:[],tables:[]},guardrails:{validationHooks:[],fieldRules:[],conduits:[]},schedules:[]}}var xn="bundle.json",Xo="turbobase";function Tp(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 wa(a)}function wa(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(Sp)),tables:[...t.sync.tables].sort(e(r=>r.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(Sp)),conduits:[...t.guardrails.conduits].sort(e(r=>r.conduitId))},schedules:[...t.schedules].sort(e(r=>r.name))}}function Sp(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function xp(t,e){let r=(e??"").trim();if(!r)return{ok:!1,reason:"target instance slug is unknown \u2014 cannot confirm a promote"};let n=(t??"").trim();return n?n!==r?{ok:!1,reason:`--confirm "${n}" does not match the target instance "${r}" \u2014 refusing to apply`}:{ok:!0}:{ok:!1,reason:`--confirm <slug> is required for promote (expected "${r}")`}}var Qo="hooks",es="conduits",$p="processes",Wt="turbobase/sync.json",Jt="turbobase/schedules.json";function _a(t){let e=d=>{let p=new RegExp(`${d}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return p?p[2]:void 0},r=/\bdefineConduit\s*[<(]/.test(t),n=/\bdefineProcess\s*[<(]/.test(t),o=/\bdefineHook\s*[<(]/.test(t);if(!r&&!o&&!n)return null;let s=e("id"),i=e("recordType");if(n){let d=e("source")??"standalone";return s?{id:s,recordType:"*",event:"invoke",source:d,extensionKind:"process"}:null}if(r){let d=e("on"),p=e("source");return!s||!i||!d||!p?null:{id:s,recordType:i,event:d,source:p,extensionKind:"conduit"}}let a=e("event"),l=e("source")??"standalone";return!s||!i||!a?null:{id:s,recordType:i,event:a,source:l,extensionKind:"hook"}}function Sa(t){return/\bdefineProcess\s*[<(]/.test(t)?"could not read a quoted id \u2014 is it a defineProcess({...}) file? A process binds to no single record type; its steps carry their own.":/\bdefineConduit\s*[<(]/.test(t)?"could not read id / on / from.source / from.recordType \u2014 is it a defineConduit({...}) file?":"could not read id / recordType / event \u2014 is it a defineHook({...}) file?"}async function Rn(t){let e;try{e=await va.readdir(t,{withFileTypes:!0})}catch{return[]}let r=[];for(let n of e){if(n.isDirectory()){if(n.name.startsWith(".")||n.name==="node_modules")continue;for(let o of await Rn(gt(t,n.name)))r.push(`${n.name}/${o}`);continue}n.name.endsWith(".ts")&&(n.name.endsWith(".test.ts")||n.name.endsWith(".d.ts")||r.push(n.name))}return r.sort()}async function Zo(t,e){let r;try{r=await va.readFile(t,"utf8")}catch{return}try{return JSON.parse(r)}catch(n){throw new Error(`${e} is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}}function u_(t){return{sourceSystem:String(t.sourceSystem??""),recordType:String(t.recordType??""),fieldName:String(t.fieldName??""),owningSide:t.owningSide==="pg"?"pg":"source",caseSensitive:!!t.caseSensitive}}function p_(t){return{sourceRecordType:String(t.sourceRecordType??""),kind:String(t.kind??""),sourceSystem:String(t.sourceSystem??"")}}function h_(t){let e={name:String(t.name??""),scheduleKind:String(t.scheduleKind??"cron"),scheduleExpr:String(t.scheduleExpr??""),scheduleTz:String(t.scheduleTz??"UTC"),body:t.body??{}};return typeof t.status=="string"&&(e.status=t.status),e}async function Ep(t=process.cwd()){let e=Rp(t),[r,n,o]=await Promise.all([Rn(gt(e,Qo)),Rn(gt(e,es)),Rn(gt(e,$p))]);if(r.length>0||n.length>0||o.length>0)return!0;let[s,i]=await Promise.all([Zo(gt(e,Wt),Wt).catch(()=>{}),Zo(gt(e,Jt),Jt).catch(()=>{})]);return s!==void 0||i!==void 0}async function Pp(t=process.cwd(),e={}){let r=Rp(t),n=kp(e.tenant),o=[],s=[];for(let l of[Qo,es,$p])for(let d of await Rn(gt(r,l))){let p=`${l}/${d}`,f=await va.readFile(gt(r,l,d),"utf8"),_=e.inline?await e.inline(f,d_(gt(r,l,d))):f,y=_a(_);if(!y){/\bdefine(Hook|Conduit|Process)\s*[<(]/.test(_)&&s.push({file:p,reason:Sa(_)});continue}let k={id:y.id,kind:y.extensionKind,recordType:y.recordType,event:y.event,source:y.source,sourceCode:_};y.extensionKind==="conduit"?n.conduits.push(k):n.hooks.push(k),o.push(p)}let i=await Zo(gt(r,Wt),Wt);if(i!==void 0){if(typeof i!="object"||i===null||Array.isArray(i))throw new Error(`${Wt} must be a JSON object with "fields" and/or "tables".`);let l=i;for(let d of Array.isArray(l.fields)?l.fields:[])n.sync.fields.push(u_(d));for(let d of Array.isArray(l.tables)?l.tables:[])n.sync.tables.push(p_(d));o.push(Wt)}let a=await Zo(gt(r,Jt),Jt);if(a!==void 0){let l=Array.isArray(a)?a:Array.isArray(a.schedules)?a.schedules:null;if(l===null)throw new Error(`${Jt} must be a JSON array, or an object with a "schedules" array.`);for(let d of l)n.schedules.push(h_(d));o.push(Jt)}return n.guardrails.fieldRules=[...n.sync.fields],n.guardrails.validationHooks=n.hooks.filter(l=>l.event==="before_save").map(l=>l.id).sort(),{manifest:wa(n),contributed:o,unparsed:s}}import{promises as xa}from"node:fs";import{resolve as w_}from"node:path";var m_="For app developers \u2014 adopt these";function Ap(t){let e=/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?$/.exec(t.trim());return e?{core:[Number(e[1]),Number(e[2]??0),Number(e[3]??0)],prerelease:e[4]??""}:null}function Cp(t,e){let r=Ap(t),n=Ap(e);if(!r&&!n)return 0;if(!r)return-1;if(!n)return 1;for(let o=0;o<3;o++){let s=(r.core[o]??0)-(n.core[o]??0);if(s!==0)return s}return r.prerelease===n.prerelease?0:r.prerelease?n.prerelease?r.prerelease<n.prerelease?-1:1:-1:1}function f_(t){return t.replace(/[‐-―]/g,"-").toLowerCase().replace(/\s+/g," ").trim()}var UI=f_(m_);bn();mt();var g_=t=>new Promise(e=>setTimeout(e,t));function Ip(t){return t.stage==="completed"||t.stage==="failed"}function y_(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function b_(t,e,r){let n=t.outputTail??"";if(n&&n!==e){let s=(n.startsWith(e)?n.slice(e.length):n).replace(/\n+$/,"");if(s)for(let i of s.split(`
3783
3797
  `))r(i)}return n}async function ka(t,e={}){let r=e.sink??(_=>{process.stdout.write(`${_}
3784
3798
  `)}),n=e.sleep??g_,o=e.intervalMs??2e3,s=e.maxPolls??Number.POSITIVE_INFINITY,i=e.onStage??(_=>r(y_(_))),a=e.onPoll,l="",d="",p=_=>{a?.(_),_.stage!==d&&i(_),l=b_(_,l,r),d=_.stage},f=await t();if(p(f),Ip(f))return f;for(let _=0;_<s;_+=1)if(await n(o),f=await t(),p(f),Ip(f))return f;return f}var b=t=>{process.stdout.write(`${t}
3785
3799
  `)},L=t=>{process.stderr.write(`${t}
3786
- `)};function w(t){L(m.red(`turbobase: ${t}`)),process.exit(1)}var $n=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function Op(t,e){let r=e.json===!0||typeof e.reporter=="string";(t.color===!1||r)&&ma(!1)}async function H(t){let e=await mt(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let r=await Ot();if(t){let n=r.length?` Stored instances: ${r.map(o=>o.baseUrl).join(", ")}.`:"";w(`not signed in to ${rt(t)}.${n} Run \`turbobase auth login --base-url ${rt(t)} --token tb_pat_\u2026\`.`)}if(r.length===0&&w("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Ne())try{let n=await Le("Multiple instances stored \u2014 pick the active one:",r.map(s=>({value:s.baseUrl,label:s.baseUrl,description:`updated ${s.updatedAt}`})));await jo(n);let o=await mt();if(o)return{baseUrl:o.baseUrl,token:o.token}}catch{}w(`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 V(t,e,r){if(!(t instanceof Q)||t.status!==403)return;t.body?.error==="approval_required"&&w(`${r} denied (403): an approval-gated deploy needs a recorded approval \u2014 pass --approved-by <email>.`),w(`${r} forbidden (403) \u2014 the stored PAT lacks the '${e}' scope. Re-run \`turbobase auth login\` with a token that has it.`)}async function Ta(t,e,r){let n=r?Number(r):void 0;if(Go()){let s=fa(e),i;try{i=await ka(t,{intervalMs:n,sink:a=>s.log(a),onStage:()=>{},onPoll:a=>s.status({stage:a.stage,percent:a.percent??void 0,runStatus:a.runStatus??void 0})})}catch(a){s.stop(),w(`${e} --follow failed: ${a instanceof Error?a.message:String(a)}`)}s.done({stage:i.stage,percent:i.percent??void 0,runStatus:i.runStatus??void 0}),i.stage==="failed"&&process.exit(1);return}let o;try{o=await ka(t,{sink:b,intervalMs:n})}catch(s){w(`${e} --follow failed: ${s instanceof Error?s.message:String(s)}`)}o.stage==="failed"&&w(`${e} failed${o.runStatus?` (${o.runStatus})`:""}.`),b(`${e} ${o.stage}.`)}var v_=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function __(t){try{let e=await xa.readFile(t,"utf8");return v_.exec(e)?.[1]??null}catch{return null}}var S_=/GENERATED by `turbobase project adopt`/,Lp=/^##[ \t]+v?(\d+(?:\.\d+){0,2}(?:-[0-9A-Za-z.-]+)?)[ \t]*$/,k_=/^[ \t]*[-*][ \t]+\[([ xX])\][ \t]+(.*)$/;function Np(t){let e=[],r=null;for(let n of t.split(`
3800
+ `)};function w(t){L(h.red(`turbobase: ${t}`)),process.exit(1)}var $n=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function Op(t,e){let r=e.json===!0||typeof e.reporter=="string";(t.color===!1||r)&&ha(!1)}async function H(t){let e=await ht(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let r=await Ot();if(t){let n=r.length?` Stored instances: ${r.map(o=>o.baseUrl).join(", ")}.`:"";w(`not signed in to ${rt(t)}.${n} Run \`turbobase auth login --base-url ${rt(t)} --token tb_pat_\u2026\`.`)}if(r.length===0&&w("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Ne())try{let n=await Le("Multiple instances stored \u2014 pick the active one:",r.map(s=>({value:s.baseUrl,label:s.baseUrl,description:`updated ${s.updatedAt}`})));await jo(n);let o=await ht();if(o)return{baseUrl:o.baseUrl,token:o.token}}catch{}w(`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 V(t,e,r){if(!(t instanceof Q)||t.status!==403)return;t.body?.error==="approval_required"&&w(`${r} denied (403): an approval-gated deploy needs a recorded approval \u2014 pass --approved-by <email>.`),w(`${r} forbidden (403) \u2014 the stored PAT lacks the '${e}' scope. Re-run \`turbobase auth login\` with a token that has it.`)}async function Ta(t,e,r){let n=r?Number(r):void 0;if(Go()){let s=fa(e),i;try{i=await ka(t,{intervalMs:n,sink:a=>s.log(a),onStage:()=>{},onPoll:a=>s.status({stage:a.stage,percent:a.percent??void 0,runStatus:a.runStatus??void 0})})}catch(a){s.stop(),w(`${e} --follow failed: ${a instanceof Error?a.message:String(a)}`)}s.done({stage:i.stage,percent:i.percent??void 0,runStatus:i.runStatus??void 0}),i.stage==="failed"&&process.exit(1);return}let o;try{o=await ka(t,{sink:b,intervalMs:n})}catch(s){w(`${e} --follow failed: ${s instanceof Error?s.message:String(s)}`)}o.stage==="failed"&&w(`${e} failed${o.runStatus?` (${o.runStatus})`:""}.`),b(`${e} ${o.stage}.`)}var v_=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function __(t){try{let e=await xa.readFile(t,"utf8");return v_.exec(e)?.[1]??null}catch{return null}}var S_=/GENERATED by `turbobase project adopt`/,Lp=/^##[ \t]+v?(\d+(?:\.\d+){0,2}(?:-[0-9A-Za-z.-]+)?)[ \t]*$/,k_=/^[ \t]*[-*][ \t]+\[([ xX])\][ \t]+(.*)$/;function Np(t){let e=[],r=null;for(let n of t.split(`
3787
3801
  `)){let o=Lp.exec(n);if(o){r={version:o[1],items:[]},e.push(r);continue}if(/^#{1,6}[ \t]/.test(n)){r=null;continue}if(!r)continue;let s=k_.exec(n);if(s){let a=s[2].trim();r.items.push({key:a.replace(/\s+/g," "),done:s[1]!==" ",text:a,extra:[]});continue}let i=r.items[r.items.length-1];i&&n.trim()!==""&&i.extra.push(n)}return e}function T_(t){let e=t.items.map(r=>[`- [${r.done?"x":" "}] ${r.text}`,...r.extra].join(`
3788
3802
  `)).join(`
3789
3803
  `);return`## v${t.version}
@@ -3798,67 +3812,67 @@ ${o.map(T_).join(`
3798
3812
  `)}
3799
3813
  `,carried:s}}function jp(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 H(e.baseUrl),o=w_(process.cwd(),e.out),s=e.since?.trim()||await __(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||w(`adopt fetch failed: GET /v1/catalog/adopt-notes \u2192 ${l.status}`);let d=await l.json();if(!d.available){b(`${r} ships no release notes to adopt from (nothing written).`);return}let p=d.releases.reduce(($,P)=>$+P.items.length,0);if(p===0){b(`up to date${s?` since v${s.replace(/^v/,"")}`:""}${d.currentVersion?` (instance is on v${d.currentVersion})`:""} \u2014 ${o} left untouched.`);return}let f=d.currentVersion??d.releases[0]?.version??"",_=`<!-- GENERATED by \`turbobase project adopt\` against ${r} \u2014 adopted-through=${f}. Re-run to refresh; delete this file once every line is done. -->
3800
3814
 
3801
- `,y=await xa.readFile(o,"utf8").catch(()=>null),k=d.markdown,R=0;if(y!==null&&y.trim()!==""){let $=x_(y,d.markdown);$||w(`${o} was not written by \`turbobase project adopt\` (no generated header, no \`## v<version>\` section) \u2014 refusing to overwrite it. Move it aside, or write elsewhere with \`-o <file>\`.`),k=$.markdown,R=$.carried}await xa.writeFile(o,_+k,"utf8"),b(`wrote ${o} \u2014 ${p} item(s) across ${d.releases.length} release(s)${s?` since v${s.replace(/^v/,"")}`:""}${R>0?`, keeping ${R} unticked item(s) already in the file`:""}.`)})}ht();var En=["suggested_kb_edit","kb_correction"];var R_=[{heading:"Suggested KB edits",section:"suggested_kb_edit",ranked:!1},{heading:"Knowledge-base corrections",section:"kb_correction",ranked:!1},{heading:"What would have helped most, in order",section:"platform_feedback",ranked:!0},{heading:"Platform asks",section:"platform_feedback",ranked:!1},{heading:"Requested rollups",section:"platform_feedback",ranked:!1},{heading:"Agent rules",section:"agent_rule",ranked:!1}];function $_(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var XI=new Map(R_.map(t=>[$_(t.heading),t]));var ZI=new RegExp(["^the (situation|context|background|problem|ask|point|gist|upshot|part\\b)","^the (one|two|three|four|five|six|seven|eight|nine|ten|\\d{1,2}) \\w+s?\\b","^(on|about) \\w+ing\\b","^(concrete|specific|possible|suggested) \\w+","^what (we|i|you)(\\b|'d| would| could| should)","^(background|summary|context|recommendations?|next steps|takeaways?|conclusion|in short|tl;?dr)\\b","^why (this|that|it) matters\\b"].join("|"),"i");function E_(t){return t.diff??!!t.dryRun}var P_={update_page:"append to the existing page",new_page:"create a NEW page"},Lt=(t,e)=>` ${m.dim(t.padEnd(11))}${e}`,Mp=t=>t.ownerEmail??t.ownerId;function Dr(t){return!t.needsPageRef&&!t.blockedBy}var ts=t=>m.green(t?` + ${t}`:" +"),A_=t=>m.red(t?` - ${t}`:" -"),fr=t=>m.dim(` ${t}`),C_=` ${m.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,Ra=80;function I_(t){let e=[C_];t.target?(e.push(fr(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(A_(`visibility: ${t.target.visibility}`)),e.push(ts("visibility: admin"))):e.push(fr(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(fr("title, slug, evidence: untouched")),e.push(fr("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(fr("turbobase.document \xB7 new")),e.push(ts(`title: ${t.pageTitle}`)),e.push(ts("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(fr('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(fr('appended under "## From app developers":'));let r=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
3802
- `);for(let n of r.slice(0,Ra))e.push(ts(n?` ${n}`:""));return r.length>Ra&&e.push(m.yellow(` \u2026 ${r.length-Ra} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function O_(t,e={}){let r=[];return t.forEach((n,o)=>{let{target:s,entries:i}=n;if(r.push(`${String(o+1).padStart(2)}. ${m.bold(n.pageTitle)}`),r.push(Lt("page",s?`${s.title} (${s.slug}) [${s.visibility}]`:m.dim("new \u2014 no existing page matches"))),r.push(Lt("action",Dr(n)?P_[n.action]:m.red("SKIP \u2014 nothing is written"))),n.needsPageRef){let a=[...new Set(i.map(l=>l.kb_page_ref?.trim()).filter(l=>!!l))];r.push(Lt("unresolved",m.red((a.length>0?`no page matches ${a.map(l=>`"${l}"`).join(", ")}`:"the correction names no page at all")+" \u2014 a correction needs a page to correct, so this group is SKIPPED and its findings stay pending. Fix the ref (or write the page) and re-run.")))}if(r.push(Lt("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?` ${m.dim(`\xB7 ${a.verdict}`)}`:"",d=a.kb_page_ref?` ${m.dim(`(${a.kb_page_ref})`)}`:"";r.push(` ${m.dim("\xB7")} ${a.title.trim()}${d}${l}`)}),r.push(Lt("confidence",n.withdraws?m.red("WITHDRAWN from readers (text untouched)"):m.dim("untouched"))),n.supersedes&&r.push(Lt("supersedes",m.yellow("a finding here AMENDS an earlier claim \u2014 its block is appended and marked, and nothing already on the page is reordered or removed"))),n.blockedBy&&r.push(Lt("blocked",m.red(`unpublished work on this page belongs to ${Mp(n.blockedBy)} \u2014 this page will be SKIPPED`))),n.alsoMatched.length>0&&r.push(Lt("ambiguous",m.yellow(`${n.alsoMatched.length} other page(s) match this ref: ${n.alsoMatched.map(a=>a.slug).join(", ")}`))),(n.similarTo?.length??0)>0){let a=(n.similarTo??[]).map(l=>{let d=t.findIndex(f=>f.key===l),p=d>=0?t[d]:void 0;return p?`#${d+1} "${p.pageTitle}"`:l});r.push(Lt("similar",m.yellow(`this new page looks related to ${a.join(", ")} \u2014 nothing was merged. If they are one page, push one now and re-run: the rest will resolve onto it.`)))}e.diff&&Dr(n)&&r.push(...I_(n)),r.push("")}),r}function N_(t){let e=d=>t.filter(d).length,r=t.reduce((d,p)=>d+p.entries.length,0),n=e(d=>d.withdraws),o=e(d=>d.blockedBy!=null),s=e(d=>d.needsPageRef),i=[`${r} finding${r===1?"":"s"}`,`${e(Dr)} page(s)`,`${e(d=>d.action==="update_page"&&Dr(d))} appended`,`${e(d=>d.action==="new_page"&&Dr(d))} created (unpublished)`,...s>0?[m.red(`${s} SKIPPED \u2014 correction with no page to correct`)]:[]],a=n>0?m.red(`${n} page(s) WITHDRAWN from readers`):m.dim("no page withdrawn"),l=o>0?` \xB7 ${m.red(`${o} page(s) BLOCKED by another editor`)}`:"";return`${i.join(" \xB7 ")} \xB7 ${a}${l}`}function L_(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(`${m.yellow("skipped")} ${i} \u2014 unpublished work belongs to ${o.blockedBy?Mp(o.blockedBy):"another editor"}; its findings stay pending`);continue}if(o.skipped==="unresolved_page_ref"){let l=[...new Set((s?.entries??[]).map(d=>d.kb_page_ref?.trim()).filter(d=>!!d))];n.push(`${m.yellow("skipped")} ${i} \u2014 `+(l.length>0?`no page matches ${l.map(d=>`"${d}"`).join(", ")}`:"the correction names no page")+"; nothing was written and its findings stay pending");continue}if(o.skipped){n.push(`${m.yellow("skipped")} ${i} \u2014 ${o.skipped.replace(/_/g," ")}`);continue}let a=o.created?m.green("created "):m.green("appended");n.push(`${a} ${i} \u2014 ${o.appliedEntryIds.length} finding(s) \u2192 page ${m.bold(o.documentId??"?")}`+(o.created?m.dim(" (unpublished)"):"")),o.confidence==="downgraded"?n.push(` ${m.red("withdrawn from readers:")} ${i}`):o.confidence==="already_withdrawn"?n.push(` ${m.dim("page was already unpublished \u2014 left as is")}`):o.confidence==="missing"&&n.push(` ${m.yellow("page vanished between plan and push \u2014 nothing withdrawn")}`)}return n}function Dp(t){if(t instanceof Q){let e=t.body;t.status===403&&e?.reason==="admin_required"&&w("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&&w("this instance does not serve /v1/learnings \u2014 it predates the app-developer learning loop. Ask for an instance upgrade.")}V(t,"extensions:deploy","learnings push-kb")}async function Pn(t,e){let r;try{r=await J("re-reading pushed markdown",()=>t.learningsIngest(e))}catch(o){return o instanceof Q&&o.status===404?L(m.dim("this instance ingests on deploy only \u2014 planning against the queue as it stands. If a recent edit is missing, run `turbobase apps push` then `apps deploy`.")):xu(o)?L(m.yellow(Up(o))):L(m.yellow(`could not re-read the pushed markdown: ${Up(o)} \u2014 planning anyway.`)),null}if(r.filesScanned===0)return L(m.yellow("no markdown found in this app\u2019s pushed source \u2014 nothing can be ingested. Run `turbobase apps push` (a deploy uploads the built bundle, not your .md files).")),r;let n=[`${r.filesScanned} file(s) scanned`];return r.docsIngested>0&&n.push(`${r.docsIngested} changed`),r.docsUnchanged>0&&n.push(`${r.docsUnchanged} unchanged`),n.push(`${r.entriesAdded} new finding(s)`),r.entriesDuplicate>0&&n.push(`${r.entriesDuplicate} already known`),r.parseSkipped>0&&n.push(m.yellow(`${r.parseSkipped} unparseable`)),L(m.dim(n.join(" \xB7 "))),r}function Up(t){return t instanceof Error?t.message:String(t)}async function qp(t,e=r=>new q(r)){t.section&&!En.includes(t.section.trim())&&w(`unknown --section "${t.section}" \u2014 expected one of ${En.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&w("--limit must be a positive integer.");let r=await H(t.baseUrl),n=e(r),o={...t.app?{app:t.app}:{},...t.section?{section:t.section.trim()}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{}},s=await Pn(n,t.app),i;try{i=await J("reading the pending queue",()=>n.learningsPending(o))}catch(d){Dp(d),w(`could not read the pending queue: ${d instanceof Error?d.message:String(d)}`)}if(i.items.length===0){if(i.pendingTotal===0&&s&&s.entriesDuplicate>0){L(`nothing pending \u2014 all ${s.entriesDuplicate} finding(s) in your markdown were already dealt with. Materially reword one to file it again, or see \`--reapply\` on \`skills push\` to re-emit a rule without changing its text.`);return}L(i.pendingTotal===0?"nothing pending \u2014 no ingested findings are waiting on a knowledge-base decision.":`nothing matched \u2014 ${i.pendingTotal} pending finding(s) exist but not under these filters.`);return}if(b(O_(i.items,{diff:E_(t)}).join(`
3803
- `)),b(N_(i.items)),t.dryRun){L(m.dim("dry run \u2014 nothing was written."));return}let a=i.items.filter(Dr);if(a.length===0){L(m.yellow(`nothing to write \u2014 all ${i.items.length} group(s) are skipped (see the plan above): a correction with no page to correct, or a page whose unpublished work belongs to another editor. Fix the refs (or wait for the draft) and re-run; the findings stay pending.`));return}let l=a.reduce((d,p)=>d+p.entries.length,0);if(!t.yes){if(!Ne()){L(m.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 Le(`Push ${l} finding(s) into the knowledge base as ${a.length} page(s)?`,[{value:"yes",label:"Yes \u2014 push to the knowledge base",description:"pages land unpublished; corrections withdraw the pages listed above"},{value:"no",label:"No \u2014 leave the queue untouched"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){L("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{let d=await J("writing pages",()=>n.learningsPushKb(i.planToken,o));b(L_(d.applied,i.items).join(`
3804
- `))}catch(d){if(d instanceof Q&&d.status===409){L(m.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),L(`re-run \`${$n} kb push\` to review the current plan.`),process.exitCode=2;return}Dp(d),L(m.red(`turbobase: ${d instanceof Error?d.message:String(d)}`)),process.exitCode=2}}ht();var Ur=t=>new q(t);async function Mr(t,e){let r=await H(t.baseUrl);return e(r)}async function rs(t,e,r,n){return n.yes?!0:Ne()?await Le(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(L("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(L(m.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function j_(t){return t.visibility!=="published"?m.dim("draft"):t.in_current_release?m.green("live"):m.yellow("unreleased")}function zp(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function D_(t){if(t.items.length===0)return["no pages in this knowledge base."];let e=Math.max(4,...t.items.map(s=>s.slug.length)),r=[];for(let s of t.items)r.push(`${zp(m.bold(s.slug),e)} ${zp(j_(s),10)} ${m.dim(s.path)}`);r.push("");let n=t.items.filter(s=>s.visibility==="published"&&s.in_current_release).length,o=t.items.filter(s=>s.visibility!=="published").length;return r.push(`${t.items.length} page(s) \xB7 ${n} readable \xB7 ${o} draft`+(t.currentVersion==null?"":` \xB7 release v${t.currentVersion}`)),r}async function Bp(t,e=Ur){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&w(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await Mr(t,e),o;try{o=await J("reading the knowledge base",()=>n.docsList(r))}catch(s){V(s,"docs:publish","read the knowledge base"),w(`could not read the knowledge base: ${s instanceof Error?s.message:String(s)}`)}b(D_(o).join(`
3805
- `))}async function Fp(t,e,r=Ur){let n=[...new Set(t.map(l=>l.trim()).filter(Boolean))];n.length===0&&w("name at least one page slug. `turbobase kb list` shows them.");let o=await Mr(e,r);if(!await rs(`Publish ${n.length} page(s)?`,"Yes \u2014 publish them","every member can read them, and retrieval can ground answers on them, from now on",e))return;let i;try{i=await J("publishing",()=>o.docsPublish(n))}catch(l){V(l,"docs:publish","publish a page"),w(`publish failed: ${l instanceof Error?l.message:String(l)}`)}let a=i.published.map(l=>l.slug);b(m.green(`published ${a.length} page(s) \u2014 readable now.`)),i.missing.length>0&&(L(m.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1),L(m.dim(`undo with: turbobase kb unpublish ${a.join(" ")}`))}async function Hp(t,e,r=Ur){let n=[...new Set(t.map(l=>l.trim()).filter(Boolean))];n.length===0&&w("name at least one page slug. `turbobase kb list` shows them.");let o=await Mr(e,r);if(!await rs(`Hide ${n.length} page(s) from readers?`,"Yes \u2014 unpublish them","they drop out of the reader snapshot immediately; the text and its history are kept",e))return;let i;try{i=await J("unpublishing",()=>o.docsUnpublish(n))}catch(l){V(l,"docs:publish","unpublish a page"),w(`unpublish failed: ${l instanceof Error?l.message:String(l)}`)}let a=i.unpublished.map(l=>l.slug);b(m.green(`unpublished ${a.length} page(s) \u2014 retracted now.`)),L(m.dim(`re-publish with: turbobase kb publish ${a.join(" ")}`)),i.missing.length>0&&(L(m.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1)}async function Kp(t,e=Ur){let r=await Mr(t,e),n;try{n=await J("reading the releases",()=>r.docsVersions())}catch(o){V(o,"docs:publish","read the knowledge-base releases"),w(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){b("no releases yet \u2014 nothing has been published.");return}for(let o of n.items){let s=o.is_current?m.green("current"):m.dim(" ");b(`v${String(o.version_no).padEnd(4)} ${s} ${o.published_at} ${o.node_count} page(s)${o.published_by?` ${m.dim(o.published_by)}`:""}`),o.release_note&&b(` ${m.dim(o.release_note)}`)}}async function Vp(t,e,r=Ur){let n=Number(t);(!Number.isInteger(n)||n<1)&&w(`version must be a release number (got '${t}'). \`turbobase kb versions\` lists them.`);let o=await Mr(e,r);if(await rs(`Roll the knowledge base back to release v${n}?`,"Yes \u2014 roll it back","every reader sees that release\u2019s content until something is published again",e))try{let i=await J("rolling back",()=>o.docsRollback(n));b(m.green(`rolled back \u2014 release v${i.version.version_no} is current.`))}catch(i){V(i,"docs:publish","roll the knowledge base back"),w(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function Gp(t,e,r=Ur){let n=(t??"").trim();n||w("name the page slug to delete. `turbobase kb list` shows them.");let o=await Mr(e,r);if(await rs(`Delete "${n}"?`,"Yes \u2014 delete it","it drops out of the tree and every reader release; its subtree goes with it, and it stays restorable from the editor\u2019s trash",e))try{let i=await J("deleting",()=>o.docsDelete(n));b(m.green(`deleted ${i.deleted} \u2014 restorable from the knowledge-base trash.`))}catch(i){V(i,"docs:publish","delete a page"),w(`delete failed: ${i instanceof Error?i.message:String(i)}`)}}ht();function U_(t){return t.diff??!!t.dryRun}function M_(t,e){let r=[];return t.forEach((n,o)=>{let s=n.action==="new_rule"?m.green("new rule"):m.yellow("amend rule"),i=n.targetPublished?` ${m.yellow("[currently live]")}`:"";r.push(`${o+1}. ${s} ${m.bold(n.slug)}${i}`),r.push(` ${n.name}`),n.description&&r.push(` ${m.dim(n.description)}`);for(let a of n.entries)r.push(` ${m.dim("\xB7")} ${m.dim(a.app_slug)} ${a.title}`);if(e.diff){r.push("");for(let a of n.bodyMarkdown.split(`
3806
- `))r.push(` ${m.dim("|")} ${a}`)}r.push("")}),r}function q_(t){let e=t.reduce((o,s)=>o+s.entries.length,0),r=t.filter(o=>o.targetPublished).length,n=[`${e} finding(s) \u2192 ${t.length} rule(s)`];return r>0&&n.push(m.yellow(`${r} amend a rule that is currently live`)),n.join(" \xB7 ")}async function Wp(t,e=r=>new q(r)){t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&w("--limit must be a positive integer.");let r=await H(t.baseUrl),n=e(r),o={...t.app?{app:t.app}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{},...t.reapply?{reapply:!0}:{}},s=await Pn(n,t.app),i;try{i=await J("reading the pending rules",()=>n.rulesPending(o))}catch(l){V(l,"extensions:deploy","read the pending rules"),w(`could not read the pending queue: ${l instanceof Error?l.message:String(l)}`)}if(i.items.length===0){if(i.pendingTotal===0&&!t.reapply&&s&&s.entriesDuplicate>0){L(`nothing pending \u2014 all ${s.entriesDuplicate} finding(s) in your markdown were already applied. A regroup or a cosmetic edit is the same finding by design; re-run with --reapply to re-emit them (picking up a changed \`###\` grouping), or materially reword a rule to file it as a new one.`);return}L(i.pendingTotal===0?"nothing pending \u2014 no findings are waiting under `## Agent rules`.":`nothing matched \u2014 ${i.pendingTotal} pending rule finding(s) exist but not under these filters.`);return}if(b(M_(i.items,{diff:U_(t)}).join(`
3807
- `)),b(q_(i.items)),t.dryRun){L(m.dim("dry run \u2014 nothing was written."));return}let a=i.items.reduce((l,d)=>l+d.entries.length,0);if(!t.yes){if(!Ne()){L(m.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 Le(`Push ${a} finding(s) as ${i.items.length} draft rule(s)?`,[{value:"yes",label:"Yes \u2014 write them as draft rules",description:"they land as DRAFTS; an admin publishes them before anything is injected"},{value:"no",label:"No \u2014 leave the queue untouched"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){L("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{await J("writing the rules",()=>n.rulesPush(i.planToken,o))}catch(l){l instanceof Q&&l.status===409&&w("the pending queue changed while you were reading the plan \u2014 nothing was written. Re-run to see the new plan."),w(`push failed: ${l instanceof Error?l.message:String(l)}`)}b(m.green(`wrote ${i.items.length} draft rule(s).`)),L(m.dim("They are DRAFT \u2014 nothing is injected yet. An admin reviews and publishes them under Settings \u203A Skills."))}import{readdir as V_,readFile as G_,stat as W_}from"node:fs/promises";import{join as Xp,resolve as J_}from"node:path";var jt=class extends Error{constructor(e){super(e),this.name="SkillParseError"}},z_=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;function Jp(t){let e=t.replace(/^/,""),r=z_.exec(e);if(!r)throw new jt("SKILL.md must begin with a `---` YAML frontmatter block");let[,n,o]=r,s=B_(n??""),i=s.name,a=s.description;if(!i)throw new jt("SKILL.md frontmatter is missing required `name`");if(!a)throw new jt("SKILL.md frontmatter is missing required `description`");let l=new Set(["name","description","license","version"]),d=Object.entries(s).filter(([f])=>!l.has(f));return{frontmatter:{name:i,description:a,...s.license?{license:s.license}:{},...s.version?{version:s.version}:{},...d.length?{extra:Object.fromEntries(d)}:{}},body:(o??"").trim()}}function B_(t){let e={},r=t.split(/\r?\n/),n=0;for(;n<r.length;){let o=r[n]??"";if(!o.trim()||o.trim().startsWith("#")){n+=1;continue}if(/^\s/.test(o))throw new jt(`SKILL.md frontmatter: indented line not allowed in this parser: "${o.trim()}"`);let s=o.indexOf(":");if(s===-1)throw new jt(`SKILL.md frontmatter: expected "key: value", got "${o.trim()}"`);let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(a=H_(a),a===">"||a==="|"){let l=[];for(n+=1;n<r.length;){let d=r[n]??"";if(d.length===0||/^\s/.test(d))l.push(d.replace(/^\s{0,2}/,"")),n+=1;else break}e[i]=(a===">"?l.join(" "):l.join(`
3808
- `)).trim();continue}e[i]=F_(a),n+=1}return e}function F_(t){return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function H_(t){let e=!1,r=!1;for(let n=0;n<t.length;n+=1){let o=t[n];if(o==="'"&&!r)e=!e;else if(o==='"'&&!e)r=!r;else if(o==="#"&&!e&&!r)return t.slice(0,n).trim()}return t}var K_=/^[a-z0-9][a-z0-9-]{1,58}[a-z0-9]$/;function Yp(t){let e=[];t.length===0&&e.push("no skill files: expected <dir>/<slug>/SKILL.md"),t.length>50&&e.push(`${t.length} skill files; at most 50 per push`);let r=new Set;for(let n of t){let o=n.slug||"(unnamed)";K_.test(n.slug??"")||e.push(`${o}: the directory name must be lowercase letters, digits and hyphens (3\u201360 characters)`),r.has(n.slug)&&e.push(`${o}: two files share this slug`),r.add(n.slug),n.name?.trim()?n.name.length>200&&e.push(`${o}: \`name\` is over 200 characters`):e.push(`${o}: frontmatter \`name\` is empty`),n.description?.trim()?n.description.length>1024&&e.push(`${o}: \`description\` is over 1024 characters`):e.push(`${o}: frontmatter \`description\` is empty \u2014 it is what an MCP client reads to choose the skill`),n.body?.trim()?Buffer.byteLength(n.body,"utf8")>65536&&e.push(`${o}: the body is over ${65536/1024} KB`):e.push(`${o}: the body after the frontmatter is empty`)}return e}ht();async function Y_(t){let e=J_(t),r;try{r=(await V_(e)).sort()}catch{w(`--from ${t}: no such directory.`)}let n=[];for(let o of r){let s=Xp(e,o,"SKILL.md");if(await W_(s).then(a=>a.isFile()).catch(()=>!1))try{let a=Jp(await G_(s,"utf8"));n.push({slug:o,name:a.frontmatter.name.trim(),description:a.frontmatter.description.trim(),body:a.body})}catch(a){throw a instanceof jt&&w(`${Xp(t,o,"SKILL.md")}: ${a.message}`),a}}return n}var ns={new:"new skill",update:"update skill",unchanged:"unchanged",refused:"REFUSED"},X_={slug_taken:"a skill with this slug exists and was not written by this app \u2014 rename the directory",owned_by_another_app:"another app owns a skill with this slug \u2014 rename the directory"};function Z_(t){let e=[];for(let r of t.items){let n=r.action==="refused"?m.red(ns.refused):r.action==="unchanged"?m.dim(ns.unchanged):r.action==="new"?m.green(ns.new):m.yellow(ns.update),o=r.targetPublished?` ${m.yellow("[currently live]")}`:"";e.push(`${n} ${m.bold(r.slug)}${o} \u2014 ${r.name}`),r.reason&&e.push(` ${m.red(X_[r.reason]??r.reason)}`)}for(let r of t.orphans)e.push(`${m.yellow("orphan")} ${m.bold(r)} \u2014 this app wrote it and no file names it now; left as it is (\`skills unpublish\` / \`skills delete\` to remove it)`);return e}async function Zp(t,e=r=>new q(r)){t.app||w("--from needs --app <slug>: the skills are the app\u2019s own, and the app owns what it writes.");let r=await Y_(t.from),n=Yp(r);n.length>0&&w(`nothing was sent:
3815
+ `,y=await xa.readFile(o,"utf8").catch(()=>null),k=d.markdown,R=0;if(y!==null&&y.trim()!==""){let $=x_(y,d.markdown);$||w(`${o} was not written by \`turbobase project adopt\` (no generated header, no \`## v<version>\` section) \u2014 refusing to overwrite it. Move it aside, or write elsewhere with \`-o <file>\`.`),k=$.markdown,R=$.carried}await xa.writeFile(o,_+k,"utf8"),b(`wrote ${o} \u2014 ${p} item(s) across ${d.releases.length} release(s)${s?` since v${s.replace(/^v/,"")}`:""}${R>0?`, keeping ${R} unticked item(s) already in the file`:""}.`)})}mt();var En=["suggested_kb_edit","kb_correction"];var R_=[{heading:"Suggested KB edits",section:"suggested_kb_edit",ranked:!1},{heading:"Knowledge-base corrections",section:"kb_correction",ranked:!1},{heading:"What would have helped most, in order",section:"platform_feedback",ranked:!0},{heading:"Platform asks",section:"platform_feedback",ranked:!1},{heading:"Requested rollups",section:"platform_feedback",ranked:!1},{heading:"Agent rules",section:"agent_rule",ranked:!1}];function $_(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var XI=new Map(R_.map(t=>[$_(t.heading),t]));var ZI=new RegExp(["^the (situation|context|background|problem|ask|point|gist|upshot|part\\b)","^the (one|two|three|four|five|six|seven|eight|nine|ten|\\d{1,2}) \\w+s?\\b","^(on|about) \\w+ing\\b","^(concrete|specific|possible|suggested) \\w+","^what (we|i|you)(\\b|'d| would| could| should)","^(background|summary|context|recommendations?|next steps|takeaways?|conclusion|in short|tl;?dr)\\b","^why (this|that|it) matters\\b"].join("|"),"i");function E_(t){return t.diff??!!t.dryRun}var P_={update_page:"append to the existing page",new_page:"create a NEW page"},Lt=(t,e)=>` ${h.dim(t.padEnd(11))}${e}`,Mp=t=>t.ownerEmail??t.ownerId;function Dr(t){return!t.needsPageRef&&!t.blockedBy}var ts=t=>h.green(t?` + ${t}`:" +"),A_=t=>h.red(t?` - ${t}`:" -"),fr=t=>h.dim(` ${t}`),C_=` ${h.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,Ra=80;function I_(t){let e=[C_];t.target?(e.push(fr(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(A_(`visibility: ${t.target.visibility}`)),e.push(ts("visibility: admin"))):e.push(fr(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(fr("title, slug, evidence: untouched")),e.push(fr("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(fr("turbobase.document \xB7 new")),e.push(ts(`title: ${t.pageTitle}`)),e.push(ts("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(fr('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(fr('appended under "## From app developers":'));let r=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
3816
+ `);for(let n of r.slice(0,Ra))e.push(ts(n?` ${n}`:""));return r.length>Ra&&e.push(h.yellow(` \u2026 ${r.length-Ra} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function O_(t,e={}){let r=[];return t.forEach((n,o)=>{let{target:s,entries:i}=n;if(r.push(`${String(o+1).padStart(2)}. ${h.bold(n.pageTitle)}`),r.push(Lt("page",s?`${s.title} (${s.slug}) [${s.visibility}]`:h.dim("new \u2014 no existing page matches"))),r.push(Lt("action",Dr(n)?P_[n.action]:h.red("SKIP \u2014 nothing is written"))),n.needsPageRef){let a=[...new Set(i.map(l=>l.kb_page_ref?.trim()).filter(l=>!!l))];r.push(Lt("unresolved",h.red((a.length>0?`no page matches ${a.map(l=>`"${l}"`).join(", ")}`:"the correction names no page at all")+" \u2014 a correction needs a page to correct, so this group is SKIPPED and its findings stay pending. Fix the ref (or write the page) and re-run.")))}if(r.push(Lt("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?` ${h.dim(`\xB7 ${a.verdict}`)}`:"",d=a.kb_page_ref?` ${h.dim(`(${a.kb_page_ref})`)}`:"";r.push(` ${h.dim("\xB7")} ${a.title.trim()}${d}${l}`)}),r.push(Lt("confidence",n.withdraws?h.red("WITHDRAWN from readers (text untouched)"):h.dim("untouched"))),n.supersedes&&r.push(Lt("supersedes",h.yellow("a finding here AMENDS an earlier claim \u2014 its block is appended and marked, and nothing already on the page is reordered or removed"))),n.blockedBy&&r.push(Lt("blocked",h.red(`unpublished work on this page belongs to ${Mp(n.blockedBy)} \u2014 this page will be SKIPPED`))),n.alsoMatched.length>0&&r.push(Lt("ambiguous",h.yellow(`${n.alsoMatched.length} other page(s) match this ref: ${n.alsoMatched.map(a=>a.slug).join(", ")}`))),(n.similarTo?.length??0)>0){let a=(n.similarTo??[]).map(l=>{let d=t.findIndex(f=>f.key===l),p=d>=0?t[d]:void 0;return p?`#${d+1} "${p.pageTitle}"`:l});r.push(Lt("similar",h.yellow(`this new page looks related to ${a.join(", ")} \u2014 nothing was merged. If they are one page, push one now and re-run: the rest will resolve onto it.`)))}e.diff&&Dr(n)&&r.push(...I_(n)),r.push("")}),r}function N_(t){let e=d=>t.filter(d).length,r=t.reduce((d,p)=>d+p.entries.length,0),n=e(d=>d.withdraws),o=e(d=>d.blockedBy!=null),s=e(d=>d.needsPageRef),i=[`${r} finding${r===1?"":"s"}`,`${e(Dr)} page(s)`,`${e(d=>d.action==="update_page"&&Dr(d))} appended`,`${e(d=>d.action==="new_page"&&Dr(d))} created (unpublished)`,...s>0?[h.red(`${s} SKIPPED \u2014 correction with no page to correct`)]:[]],a=n>0?h.red(`${n} page(s) WITHDRAWN from readers`):h.dim("no page withdrawn"),l=o>0?` \xB7 ${h.red(`${o} page(s) BLOCKED by another editor`)}`:"";return`${i.join(" \xB7 ")} \xB7 ${a}${l}`}function L_(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(`${h.yellow("skipped")} ${i} \u2014 unpublished work belongs to ${o.blockedBy?Mp(o.blockedBy):"another editor"}; its findings stay pending`);continue}if(o.skipped==="unresolved_page_ref"){let l=[...new Set((s?.entries??[]).map(d=>d.kb_page_ref?.trim()).filter(d=>!!d))];n.push(`${h.yellow("skipped")} ${i} \u2014 `+(l.length>0?`no page matches ${l.map(d=>`"${d}"`).join(", ")}`:"the correction names no page")+"; nothing was written and its findings stay pending");continue}if(o.skipped){n.push(`${h.yellow("skipped")} ${i} \u2014 ${o.skipped.replace(/_/g," ")}`);continue}let a=o.created?h.green("created "):h.green("appended");n.push(`${a} ${i} \u2014 ${o.appliedEntryIds.length} finding(s) \u2192 page ${h.bold(o.documentId??"?")}`+(o.created?h.dim(" (unpublished)"):"")),o.confidence==="downgraded"?n.push(` ${h.red("withdrawn from readers:")} ${i}`):o.confidence==="already_withdrawn"?n.push(` ${h.dim("page was already unpublished \u2014 left as is")}`):o.confidence==="missing"&&n.push(` ${h.yellow("page vanished between plan and push \u2014 nothing withdrawn")}`)}return n}function Dp(t){if(t instanceof Q){let e=t.body;t.status===403&&e?.reason==="admin_required"&&w("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&&w("this instance does not serve /v1/learnings \u2014 it predates the app-developer learning loop. Ask for an instance upgrade.")}V(t,"extensions:deploy","learnings push-kb")}async function Pn(t,e){let r;try{r=await J("re-reading pushed markdown",()=>t.learningsIngest(e))}catch(o){return o instanceof Q&&o.status===404?L(h.dim("this instance ingests on deploy only \u2014 planning against the queue as it stands. If a recent edit is missing, run `turbobase apps push` then `apps deploy`.")):xu(o)?L(h.yellow(Up(o))):L(h.yellow(`could not re-read the pushed markdown: ${Up(o)} \u2014 planning anyway.`)),null}if(r.filesScanned===0)return L(h.yellow("no markdown found in this app\u2019s pushed source \u2014 nothing can be ingested. Run `turbobase apps push` (a deploy uploads the built bundle, not your .md files).")),r;let n=[`${r.filesScanned} file(s) scanned`];return r.docsIngested>0&&n.push(`${r.docsIngested} changed`),r.docsUnchanged>0&&n.push(`${r.docsUnchanged} unchanged`),n.push(`${r.entriesAdded} new finding(s)`),r.entriesDuplicate>0&&n.push(`${r.entriesDuplicate} already known`),r.parseSkipped>0&&n.push(h.yellow(`${r.parseSkipped} unparseable`)),L(h.dim(n.join(" \xB7 "))),r}function Up(t){return t instanceof Error?t.message:String(t)}async function qp(t,e=r=>new q(r)){t.section&&!En.includes(t.section.trim())&&w(`unknown --section "${t.section}" \u2014 expected one of ${En.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&w("--limit must be a positive integer.");let r=await H(t.baseUrl),n=e(r),o={...t.app?{app:t.app}:{},...t.section?{section:t.section.trim()}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{}},s=await Pn(n,t.app),i;try{i=await J("reading the pending queue",()=>n.learningsPending(o))}catch(d){Dp(d),w(`could not read the pending queue: ${d instanceof Error?d.message:String(d)}`)}if(i.items.length===0){if(i.pendingTotal===0&&s&&s.entriesDuplicate>0){L(`nothing pending \u2014 all ${s.entriesDuplicate} finding(s) in your markdown were already dealt with. Materially reword one to file it again, or see \`--reapply\` on \`skills push\` to re-emit a rule without changing its text.`);return}L(i.pendingTotal===0?"nothing pending \u2014 no ingested findings are waiting on a knowledge-base decision.":`nothing matched \u2014 ${i.pendingTotal} pending finding(s) exist but not under these filters.`);return}if(b(O_(i.items,{diff:E_(t)}).join(`
3817
+ `)),b(N_(i.items)),t.dryRun){L(h.dim("dry run \u2014 nothing was written."));return}let a=i.items.filter(Dr);if(a.length===0){L(h.yellow(`nothing to write \u2014 all ${i.items.length} group(s) are skipped (see the plan above): a correction with no page to correct, or a page whose unpublished work belongs to another editor. Fix the refs (or wait for the draft) and re-run; the findings stay pending.`));return}let l=a.reduce((d,p)=>d+p.entries.length,0);if(!t.yes){if(!Ne()){L(h.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 Le(`Push ${l} finding(s) into the knowledge base as ${a.length} page(s)?`,[{value:"yes",label:"Yes \u2014 push to the knowledge base",description:"pages land unpublished; corrections withdraw the pages listed above"},{value:"no",label:"No \u2014 leave the queue untouched"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){L("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{let d=await J("writing pages",()=>n.learningsPushKb(i.planToken,o));b(L_(d.applied,i.items).join(`
3818
+ `))}catch(d){if(d instanceof Q&&d.status===409){L(h.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),L(`re-run \`${$n} kb push\` to review the current plan.`),process.exitCode=2;return}Dp(d),L(h.red(`turbobase: ${d instanceof Error?d.message:String(d)}`)),process.exitCode=2}}mt();var Ur=t=>new q(t);async function Mr(t,e){let r=await H(t.baseUrl);return e(r)}async function rs(t,e,r,n){return n.yes?!0:Ne()?await Le(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(L("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(L(h.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function j_(t){return t.visibility!=="published"?h.dim("draft"):t.in_current_release?h.green("live"):h.yellow("unreleased")}function zp(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function D_(t){if(t.items.length===0)return["no pages in this knowledge base."];let e=Math.max(4,...t.items.map(s=>s.slug.length)),r=[];for(let s of t.items)r.push(`${zp(h.bold(s.slug),e)} ${zp(j_(s),10)} ${h.dim(s.path)}`);r.push("");let n=t.items.filter(s=>s.visibility==="published"&&s.in_current_release).length,o=t.items.filter(s=>s.visibility!=="published").length;return r.push(`${t.items.length} page(s) \xB7 ${n} readable \xB7 ${o} draft`+(t.currentVersion==null?"":` \xB7 release v${t.currentVersion}`)),r}async function Bp(t,e=Ur){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&w(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await Mr(t,e),o;try{o=await J("reading the knowledge base",()=>n.docsList(r))}catch(s){V(s,"docs:publish","read the knowledge base"),w(`could not read the knowledge base: ${s instanceof Error?s.message:String(s)}`)}b(D_(o).join(`
3819
+ `))}async function Fp(t,e,r=Ur){let n=[...new Set(t.map(l=>l.trim()).filter(Boolean))];n.length===0&&w("name at least one page slug. `turbobase kb list` shows them.");let o=await Mr(e,r);if(!await rs(`Publish ${n.length} page(s)?`,"Yes \u2014 publish them","every member can read them, and retrieval can ground answers on them, from now on",e))return;let i;try{i=await J("publishing",()=>o.docsPublish(n))}catch(l){V(l,"docs:publish","publish a page"),w(`publish failed: ${l instanceof Error?l.message:String(l)}`)}let a=i.published.map(l=>l.slug);b(h.green(`published ${a.length} page(s) \u2014 readable now.`)),i.missing.length>0&&(L(h.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1),L(h.dim(`undo with: turbobase kb unpublish ${a.join(" ")}`))}async function Hp(t,e,r=Ur){let n=[...new Set(t.map(l=>l.trim()).filter(Boolean))];n.length===0&&w("name at least one page slug. `turbobase kb list` shows them.");let o=await Mr(e,r);if(!await rs(`Hide ${n.length} page(s) from readers?`,"Yes \u2014 unpublish them","they drop out of the reader snapshot immediately; the text and its history are kept",e))return;let i;try{i=await J("unpublishing",()=>o.docsUnpublish(n))}catch(l){V(l,"docs:publish","unpublish a page"),w(`unpublish failed: ${l instanceof Error?l.message:String(l)}`)}let a=i.unpublished.map(l=>l.slug);b(h.green(`unpublished ${a.length} page(s) \u2014 retracted now.`)),L(h.dim(`re-publish with: turbobase kb publish ${a.join(" ")}`)),i.missing.length>0&&(L(h.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1)}async function Kp(t,e=Ur){let r=await Mr(t,e),n;try{n=await J("reading the releases",()=>r.docsVersions())}catch(o){V(o,"docs:publish","read the knowledge-base releases"),w(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){b("no releases yet \u2014 nothing has been published.");return}for(let o of n.items){let s=o.is_current?h.green("current"):h.dim(" ");b(`v${String(o.version_no).padEnd(4)} ${s} ${o.published_at} ${o.node_count} page(s)${o.published_by?` ${h.dim(o.published_by)}`:""}`),o.release_note&&b(` ${h.dim(o.release_note)}`)}}async function Vp(t,e,r=Ur){let n=Number(t);(!Number.isInteger(n)||n<1)&&w(`version must be a release number (got '${t}'). \`turbobase kb versions\` lists them.`);let o=await Mr(e,r);if(await rs(`Roll the knowledge base back to release v${n}?`,"Yes \u2014 roll it back","every reader sees that release\u2019s content until something is published again",e))try{let i=await J("rolling back",()=>o.docsRollback(n));b(h.green(`rolled back \u2014 release v${i.version.version_no} is current.`))}catch(i){V(i,"docs:publish","roll the knowledge base back"),w(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function Gp(t,e,r=Ur){let n=(t??"").trim();n||w("name the page slug to delete. `turbobase kb list` shows them.");let o=await Mr(e,r);if(await rs(`Delete "${n}"?`,"Yes \u2014 delete it","it drops out of the tree and every reader release; its subtree goes with it, and it stays restorable from the editor\u2019s trash",e))try{let i=await J("deleting",()=>o.docsDelete(n));b(h.green(`deleted ${i.deleted} \u2014 restorable from the knowledge-base trash.`))}catch(i){V(i,"docs:publish","delete a page"),w(`delete failed: ${i instanceof Error?i.message:String(i)}`)}}mt();function U_(t){return t.diff??!!t.dryRun}function M_(t,e){let r=[];return t.forEach((n,o)=>{let s=n.action==="new_rule"?h.green("new rule"):h.yellow("amend rule"),i=n.targetPublished?` ${h.yellow("[currently live]")}`:"";r.push(`${o+1}. ${s} ${h.bold(n.slug)}${i}`),r.push(` ${n.name}`),n.description&&r.push(` ${h.dim(n.description)}`);for(let a of n.entries)r.push(` ${h.dim("\xB7")} ${h.dim(a.app_slug)} ${a.title}`);if(e.diff){r.push("");for(let a of n.bodyMarkdown.split(`
3820
+ `))r.push(` ${h.dim("|")} ${a}`)}r.push("")}),r}function q_(t){let e=t.reduce((o,s)=>o+s.entries.length,0),r=t.filter(o=>o.targetPublished).length,n=[`${e} finding(s) \u2192 ${t.length} rule(s)`];return r>0&&n.push(h.yellow(`${r} amend a rule that is currently live`)),n.join(" \xB7 ")}async function Wp(t,e=r=>new q(r)){t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&w("--limit must be a positive integer.");let r=await H(t.baseUrl),n=e(r),o={...t.app?{app:t.app}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{},...t.reapply?{reapply:!0}:{}},s=await Pn(n,t.app),i;try{i=await J("reading the pending rules",()=>n.rulesPending(o))}catch(l){V(l,"extensions:deploy","read the pending rules"),w(`could not read the pending queue: ${l instanceof Error?l.message:String(l)}`)}if(i.items.length===0){if(i.pendingTotal===0&&!t.reapply&&s&&s.entriesDuplicate>0){L(`nothing pending \u2014 all ${s.entriesDuplicate} finding(s) in your markdown were already applied. A regroup or a cosmetic edit is the same finding by design; re-run with --reapply to re-emit them (picking up a changed \`###\` grouping), or materially reword a rule to file it as a new one.`);return}L(i.pendingTotal===0?"nothing pending \u2014 no findings are waiting under `## Agent rules`.":`nothing matched \u2014 ${i.pendingTotal} pending rule finding(s) exist but not under these filters.`);return}if(b(M_(i.items,{diff:U_(t)}).join(`
3821
+ `)),b(q_(i.items)),t.dryRun){L(h.dim("dry run \u2014 nothing was written."));return}let a=i.items.reduce((l,d)=>l+d.entries.length,0);if(!t.yes){if(!Ne()){L(h.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 Le(`Push ${a} finding(s) as ${i.items.length} draft rule(s)?`,[{value:"yes",label:"Yes \u2014 write them as draft rules",description:"they land as DRAFTS; an admin publishes them before anything is injected"},{value:"no",label:"No \u2014 leave the queue untouched"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){L("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{await J("writing the rules",()=>n.rulesPush(i.planToken,o))}catch(l){l instanceof Q&&l.status===409&&w("the pending queue changed while you were reading the plan \u2014 nothing was written. Re-run to see the new plan."),w(`push failed: ${l instanceof Error?l.message:String(l)}`)}b(h.green(`wrote ${i.items.length} draft rule(s).`)),L(h.dim("They are DRAFT \u2014 nothing is injected yet. An admin reviews and publishes them under Settings \u203A Skills."))}import{readdir as V_,readFile as G_,stat as W_}from"node:fs/promises";import{join as Xp,resolve as J_}from"node:path";var jt=class extends Error{constructor(e){super(e),this.name="SkillParseError"}},z_=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;function Jp(t){let e=t.replace(/^/,""),r=z_.exec(e);if(!r)throw new jt("SKILL.md must begin with a `---` YAML frontmatter block");let[,n,o]=r,s=B_(n??""),i=s.name,a=s.description;if(!i)throw new jt("SKILL.md frontmatter is missing required `name`");if(!a)throw new jt("SKILL.md frontmatter is missing required `description`");let l=new Set(["name","description","license","version"]),d=Object.entries(s).filter(([f])=>!l.has(f));return{frontmatter:{name:i,description:a,...s.license?{license:s.license}:{},...s.version?{version:s.version}:{},...d.length?{extra:Object.fromEntries(d)}:{}},body:(o??"").trim()}}function B_(t){let e={},r=t.split(/\r?\n/),n=0;for(;n<r.length;){let o=r[n]??"";if(!o.trim()||o.trim().startsWith("#")){n+=1;continue}if(/^\s/.test(o))throw new jt(`SKILL.md frontmatter: indented line not allowed in this parser: "${o.trim()}"`);let s=o.indexOf(":");if(s===-1)throw new jt(`SKILL.md frontmatter: expected "key: value", got "${o.trim()}"`);let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(a=H_(a),a===">"||a==="|"){let l=[];for(n+=1;n<r.length;){let d=r[n]??"";if(d.length===0||/^\s/.test(d))l.push(d.replace(/^\s{0,2}/,"")),n+=1;else break}e[i]=(a===">"?l.join(" "):l.join(`
3822
+ `)).trim();continue}e[i]=F_(a),n+=1}return e}function F_(t){return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function H_(t){let e=!1,r=!1;for(let n=0;n<t.length;n+=1){let o=t[n];if(o==="'"&&!r)e=!e;else if(o==='"'&&!e)r=!r;else if(o==="#"&&!e&&!r)return t.slice(0,n).trim()}return t}var K_=/^[a-z0-9][a-z0-9-]{1,58}[a-z0-9]$/;function Yp(t){let e=[];t.length===0&&e.push("no skill files: expected <dir>/<slug>/SKILL.md"),t.length>50&&e.push(`${t.length} skill files; at most 50 per push`);let r=new Set;for(let n of t){let o=n.slug||"(unnamed)";K_.test(n.slug??"")||e.push(`${o}: the directory name must be lowercase letters, digits and hyphens (3\u201360 characters)`),r.has(n.slug)&&e.push(`${o}: two files share this slug`),r.add(n.slug),n.name?.trim()?n.name.length>200&&e.push(`${o}: \`name\` is over 200 characters`):e.push(`${o}: frontmatter \`name\` is empty`),n.description?.trim()?n.description.length>1024&&e.push(`${o}: \`description\` is over 1024 characters`):e.push(`${o}: frontmatter \`description\` is empty \u2014 it is what an MCP client reads to choose the skill`),n.body?.trim()?Buffer.byteLength(n.body,"utf8")>65536&&e.push(`${o}: the body is over ${65536/1024} KB`):e.push(`${o}: the body after the frontmatter is empty`)}return e}mt();async function Y_(t){let e=J_(t),r;try{r=(await V_(e)).sort()}catch{w(`--from ${t}: no such directory.`)}let n=[];for(let o of r){let s=Xp(e,o,"SKILL.md");if(await W_(s).then(a=>a.isFile()).catch(()=>!1))try{let a=Jp(await G_(s,"utf8"));n.push({slug:o,name:a.frontmatter.name.trim(),description:a.frontmatter.description.trim(),body:a.body})}catch(a){throw a instanceof jt&&w(`${Xp(t,o,"SKILL.md")}: ${a.message}`),a}}return n}var ns={new:"new skill",update:"update skill",unchanged:"unchanged",refused:"REFUSED"},X_={slug_taken:"a skill with this slug exists and was not written by this app \u2014 rename the directory",owned_by_another_app:"another app owns a skill with this slug \u2014 rename the directory"};function Z_(t){let e=[];for(let r of t.items){let n=r.action==="refused"?h.red(ns.refused):r.action==="unchanged"?h.dim(ns.unchanged):r.action==="new"?h.green(ns.new):h.yellow(ns.update),o=r.targetPublished?` ${h.yellow("[currently live]")}`:"";e.push(`${n} ${h.bold(r.slug)}${o} \u2014 ${r.name}`),r.reason&&e.push(` ${h.red(X_[r.reason]??r.reason)}`)}for(let r of t.orphans)e.push(`${h.yellow("orphan")} ${h.bold(r)} \u2014 this app wrote it and no file names it now; left as it is (\`skills unpublish\` / \`skills delete\` to remove it)`);return e}async function Zp(t,e=r=>new q(r)){t.app||w("--from needs --app <slug>: the skills are the app\u2019s own, and the app owns what it writes.");let r=await Y_(t.from),n=Yp(r);n.length>0&&w(`nothing was sent:
3809
3823
  ${n.join(`
3810
3824
  `)}`);let o=await H(t.baseUrl),s=e(o),i=async _=>{try{return await J(_?"reading the plan":"writing the skills",()=>s.appSkillsPush(t.app,r,_))}catch(y){if(V(y,"extensions:deploy","push skill files"),y instanceof Q&&y.status===404){let k=y.body;w(k?.error==="app_not_found"?String(k.message):"this instance has no /v1/apps/:slug/skills \u2014 it predates `skills push --from`. Upgrade the instance first.")}w(`push failed: ${y instanceof Error?y.message:String(y)}`)}},a=await i(!0);b(Z_(a).join(`
3811
- `));let l=a.items.filter(_=>_.action==="new"||_.action==="update").length,d=a.items.filter(_=>_.action==="refused").length;if(t.dryRun){L(m.dim("dry run \u2014 nothing was written.")),d>0&&(process.exitCode=1);return}let p=a;if(l>0){if(!t.yes){if(!Ne()){L(m.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1;return}if(await Le(`Write ${l} skill(s)${t.publish?" and publish them":" as drafts"}?`,[{value:"yes",label:"Yes"},{value:"no",label:"No \u2014 write nothing"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){L("aborted \u2014 nothing was written."),process.exitCode=1;return}}p=await i(!1)}let f=p.items.filter(_=>_.action==="new"||_.action==="update").map(_=>_.slug);if(b(`${f.length} written, ${p.items.filter(_=>_.action==="unchanged").length} unchanged, ${p.items.filter(_=>_.action==="refused").length} refused.`),t.publish&&f.length>0){let _;try{_=await J("publishing",()=>s.skillsPublish(f))}catch(y){V(y,"skills:publish","publish the pushed skills"),w(`the skills were written as drafts but publishing failed: ${y instanceof Error?y.message:String(y)}`)}b(m.green(`published ${_.published.join(", ")} \u2014 live as of release ${_.version.version_no}.`))}else t.publish?b(m.dim("nothing changed \u2014 nothing to publish.")):f.length>0&&L(m.dim("They are DRAFT \u2014 nothing is served yet. Publish with `turbobase skills publish <slug>` (needs `skills:publish`), or re-run with --publish."));p.items.some(_=>_.action==="refused")&&(L(m.red("one or more skill files were refused and not written.")),process.exitCode=1)}ht();var Q_=["proposed","active","rejected"],eS=["mechanic","operator","learning","code-baseline"],os=t=>new q(t);async function ss(t,e){let r=await H(t.baseUrl);return e(r)}function Qp(t,e,r){if(!t)return;let n=t.split(",").map(o=>o.trim()).filter(o=>o.length>0);if(n.length!==0){for(let o of n)e.includes(o)||w(`${r}: unknown value '${o}' \u2014 expected one of ${e.join(", ")}.`);return n}}function tS(t){if(t===void 0)return;let e=Number(t);return(!Number.isFinite(e)||e<=0)&&w("--limit must be a positive number."),Math.floor(e)}function rm(t){let e=Qp(t.status,Q_,"--status"),r=Qp(t.provenance,eS,"--provenance"),n=tS(t.limit);return{...e?{status:e}:{},...r?{provenance:r}:{},...t.recordType?{recordType:t.recordType}:{},...t.source?{source:t.source}:{},...n?{limit:n}:{}}}function em(t){return!!(t.provenance?.length||t.recordType||t.source)}var nm=["ID","STATUS","PROVENANCE","RECORD","EVENT","SOURCE","EVIDENCE","ENFORCES"];function rS(t){return t.status==="active"?m.green("active"):t.status==="rejected"?m.dim("rejected"):m.yellow("proposed")}function nS(t){return t.message?t.message:t.kind&&t.field?m.dim(`${t.kind} ${t.field}`):t.kind?m.dim(t.kind):m.dim("(no description)")}function om(t){return[t.hookId,rS(t),t.provenance==="learning"?m.yellow(t.provenance):t.provenance,t.recordType,t.event,t.source,String(t.taughtBy.length),nS(t)]}async function sm(t={},e=os){let r=await ss(t,e),n=rm(t),o;try{o=await r.proposals(n)}catch(i){V(i,"extensions:deploy","list hook proposals"),w(`list hook proposals failed: ${i instanceof Error?i.message:String(i)}`)}if(t.json)return b(JSON.stringify(o,null,2));if(o.length===0){let i=n.status?.length?n.status.join("/"):"proposed";return b(`no ${i} hook proposals.
3812
- `+m.dim(" the Mechanic stages one when a sync failure teaches a repeatable invariant."))}b(ft(o.map(om),{head:nm})),b(m.dim(" EVIDENCE = distinct sync failures that taught the rule. Arm one with `turbobase ext proposals promote <id>`."));let s=o.filter(i=>i.provenance==="learning"&&i.status==="proposed");s.length>0&&b(m.dim(` ${s.length} learning-provenance row(s) shown \u2014 those are armed through sign-off in the console, not from here.`))}async function oS(t,e,r){return r.yes?!0:Ne()?await Le(t,[{value:"yes",label:e},{value:"no",label:"No \u2014 leave them alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(L("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(L(m.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function sS(t){return!(t instanceof Q)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function $a(t,e){sS(t)&&V(t,"extensions:deploy",e)}function Ea(t,e){let r=e instanceof Q?e.body:void 0,n=r?.error==="forbidden"?r.reason??r.error:r?.error,s=n?{learning_requires_signoff:"learning-provenance rows are armed through sign-off in the console, not from the CLI",provenance_unverified:"the instance could not read the row back \u2014 refused rather than guessed",system_reserved:"a managed-service guardrail \u2014 contact support to adjust its feature flag",not_found:"no hook proposal with that id",wrong_kind:"that id is not a hook (conduits have their own review surface)",admin_required:"the PAT resolves to a non-admin user on this instance"}[n]??n:e instanceof Error?e.message:String(e);L(ve.error(`${m.bold(t)} \u2014 ${s}`))}async function tm(t,e){try{let r=await t.proposalPromote(e);return b(ve.success(`${m.bold(e)} ${m.dim(`${r.previousStatus} \u2192`)} ${m.green(r.status)}`)),!0}catch(r){return $a(r,"promote a hook proposal"),Ea(e,r),!1}}async function im(t,e={},r=os){!e.auto&&t.length===0&&w("promote: name at least one proposal id, or pass --auto with a filter."),e.auto&&t.length>0&&w("promote: pass ids OR --auto, not both \u2014 --auto selects by filter."),!e.auto&&(e.apply||e.all)&&w("promote: --apply / --all only mean something with --auto.");let n=await ss(e,r);if(!e.auto){let p=0;for(let f of t)await tm(n,f)&&(p+=1);p>0&&b(m.dim(` ${p} hook(s) armed \u2014 the loader compiles them on its next reload.`)),p<t.length&&(process.exitCode=1);return}let o=rm({...e,status:e.status??"proposed"});o.provenance?.includes("learning")&&w("promote --auto: learning-provenance proposals are armed through sign-off in the console, not from the CLI. Drop `learning` from --provenance."),o.status?.some(p=>p!=="proposed")&&w("promote --auto: only `--status proposed` rows can be armed in bulk.");let s;try{s=await n.proposals(o)}catch(p){V(p,"extensions:deploy","list hook proposals"),w(`list hook proposals failed: ${p instanceof Error?p.message:String(p)}`)}let i=s.filter(p=>p.provenance==="learning"),a=s.filter(p=>p.provenance!=="learning");if(e.json&&(b(JSON.stringify({apply:!!e.apply,plan:a,skipped:i},null,2)),!e.apply))return;if(a.length===0){e.json||(b(`nothing to promote${em(o)?" for that filter":""}.`),i.length>0&&b(m.dim(` ${i.length} learning-provenance row(s) skipped \u2014 they need sign-off.`)));return}if(e.json||(b(e.apply?`promoting ${m.bold(String(a.length))} hook proposal(s):`:`${m.bold("dry run")} \u2014 would promote ${m.bold(String(a.length))} hook proposal(s):`),b(ft(a.map(om),{head:nm})),i.length>0&&b(m.dim(` ${i.length} learning-provenance row(s) skipped \u2014 armed through sign-off in the console.`))),!e.apply){b(""),b(ve.info("nothing was changed. Re-run with --apply to arm these."));return}if(!em(o)&&!e.all&&w(`promote --auto --apply with no filter would arm all ${a.length} proposal(s) in the queue. Narrow it with --provenance / --record-type / --source, or pass --all to mean it.`),!await oS(`Arm ${a.length} hook proposal(s)? They start rejecting writes on the next loader reload.`,`Yes \u2014 promote ${a.length}`,e))return;let d=0;for(let p of a)await tm(n,p.hookId)&&(d+=1);b(m.dim(` ${d}/${a.length} armed \u2014 the loader compiles them on its next reload. Undo one with \`turbobase ext proposals retract <id>\`.`)),d<a.length&&(process.exitCode=1)}async function am(t,e={},r=os){t.length===0&&w("retract: name at least one proposal id.");let n=await ss(e,r),o=0;for(let s of t)try{let i=await n.proposalRetract(s);b(ve.success(`${m.bold(s)} ${m.dim(`${i.previousStatus} \u2192`)} ${m.yellow(i.status)}`)),o+=1}catch(i){$a(i,"retract a hook proposal"),Ea(s,i)}o>0&&b(m.dim(" source kept \u2014 re-arm with `turbobase ext proposals promote <id>`.")),o<t.length&&(process.exitCode=1)}async function lm(t,e={},r=os){t.length===0&&w("reject: name at least one proposal id.");let n=await ss(e,r),o=0;for(let s of t)try{let i=await n.proposalReject(s,e.reason);b(ve.success(`${m.bold(s)} ${m.dim(`${i.previousStatus} \u2192`)} ${m.dim(i.status)}`)),o+=1}catch(i){$a(i,"reject a hook proposal"),Ea(s,i)}o<t.length&&(process.exitCode=1)}ht();var Pa=t=>new q(t);async function iS(t,e){let r=await H(t.baseUrl);return e(r)}function aS(t){return!(t instanceof Q)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function lS(t,e){let r=e instanceof Q?e.body:void 0,n=r?.error==="forbidden"?r.reason??r.error:r?.error,s=n?{not_found:"no extension with that id",wrong_kind:"that id is not an extension this instance manages",system_reserved:"a managed-service guardrail \u2014 contact support to adjust its feature flag",learning_requires_signoff:"learning-provenance rows are armed through sign-off in the console, not from the CLI",provenance_unverified:"the instance could not read the row back \u2014 refused rather than guessed",admin_required:"the PAT resolves to a non-admin user on this instance"}[n]??n:e instanceof Error?e.message:String(e);L(ve.error(`${m.bold(t)} \u2014 ${s}`))}async function Aa(t,e,r,n,o,s,i){e.length===0&&w(`${t}: name at least one extension id.`);let a=await iS(r,n),l=[];for(let d of e)try{let p=await o(a,d);l.push(p),r.json||b(s(p))}catch(p){aS(p)&&V(p,"extensions:deploy",`${t} an extension`),lS(d,p)}if(r.json)b(JSON.stringify(l,null,2));else{let d=i(l.length);d&&b(m.dim(d))}l.length<e.length&&(process.exitCode=1)}async function cm(t,e={},r=Pa){await Aa("disable",t,e,r,(n,o)=>n.extensionDisable(o),n=>ve.success(`${m.bold(n.id)} ${m.dim(`${n.previousStatus} \u2192`)} ${m.yellow(n.status)}`),n=>n>0?" definition kept \u2014 the loader drops it on its next reload. Put it back with `turbobase ext enable <id>`.":null)}async function dm(t,e={},r=Pa){await Aa("enable",t,e,r,(n,o)=>n.extensionEnable(o),n=>ve.success(`${m.bold(n.id)} ${m.dim(`${n.previousStatus} \u2192`)} ${m.green(n.status)}`),n=>n>0?" the loader compiles it on its next reload.":null)}async function um(t,e={},r=Pa){await Aa("remove",t,e,r,(n,o)=>n.extensionRemove(o),n=>ve.success(`${m.bold(n.id)} ${m.dim(`${n.previousStatus} \u2192`)} ${m.dim(n.status)}`),n=>n>0?" run history and everything it already wrote are kept. Redeploy the same id to bring it back.":null)}ht();var qr=t=>new q(t);async function zr(t,e){let r=await H(t.baseUrl);return e(r)}async function is(t,e,r,n){return n.yes?!0:Ne()?await Le(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(L("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(L(m.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function cS(t){return t.visibility!=="published"?m.dim("draft"):t.in_current_release?m.green("live"):m.yellow("unreleased")}function pm(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function dS(t){if(t.items.length===0)return["no skills on this instance."];let e=Math.max(4,...t.items.map(s=>s.slug.length)),r=[];for(let s of t.items)r.push(`${pm(m.bold(s.slug),e)} ${pm(cS(s),10)} ${s.surfaces.join(",")||m.dim("none")}`),s.description&&r.push(` ${m.dim(s.description)}`);r.push("");let n=t.items.filter(s=>s.visibility==="published"&&s.in_current_release).length,o=t.items.filter(s=>s.visibility!=="published").length;return r.push(`${t.items.length} skill(s) \xB7 ${n} injected \xB7 ${o} draft`+(t.currentVersion==null?"":` \xB7 release v${t.currentVersion}`)),r}async function mm(t,e=qr){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&w(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await zr(t,e),o;try{o=await J("reading the skills",()=>n.skillsList(r))}catch(s){V(s,"skills:publish","read the instance skills"),w(`could not read the skills: ${s instanceof Error?s.message:String(s)}`)}b(dS(o).join(`
3813
- `))}async function hm(t,e,r=qr){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&w("name at least one skill slug. `turbobase skills list` shows them.");let o=await zr(e,r);if(!await is(`Publish ${n.length} skill(s)?`,"Yes \u2014 publish them","their text is injected into every matching turn from now on",e))return;let i;try{i=await J("publishing",()=>o.skillsPublish(n))}catch(a){V(a,"skills:publish","publish a skill"),w(`publish failed: ${a instanceof Error?a.message:String(a)}`)}b(m.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(L(m.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),L(m.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function fm(t,e,r=qr){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&w("name at least one skill slug. `turbobase skills list` shows them.");let o=await zr(e,r);if(!await is(`Move ${n.length} skill(s) back to draft?`,"Yes \u2014 unpublish them","they stop being injected immediately; the text and its history are kept",e))return;let i;try{i=await J("unpublishing",()=>o.skillsUnpublish(n))}catch(a){V(a,"skills:publish","unpublish a skill"),w(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}b(m.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),L(m.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(L(m.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function gm(t,e,r=qr){let n=Number(t);(!Number.isInteger(n)||n<1)&&w(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let o=await zr(e,r);if(await is(`Roll the skills back to release v${n}?`,"Yes \u2014 restore that release","content only: a skill an operator has since unpublished stays off",e))try{let i=await J("rolling back",()=>o.skillsRollback(n));b(m.green(`rolled back to v${i.version.version_no}.`))}catch(i){V(i,"skills:publish","roll back a skills release"),w(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function ym(t,e=qr){let r=await zr(t,e),n;try{n=await J("reading the releases",()=>r.skillsReleases())}catch(o){V(o,"skills:publish","read the skills releases"),w(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){L("no releases yet.");return}for(let o of n.items){let s=o.is_current?m.green("*"):" ",i=o.release_note?` \u2014 ${o.release_note}`:"";b(`${s} v${o.version_no} ${o.skill_count} skill(s) ${m.dim(o.published_at)}${o.published_by?m.dim(` by ${o.published_by}`):""}${m.dim(i)}`)}}async function bm(t,e,r=qr){let n=[...new Set((t??[]).map(d=>d.trim()).filter(Boolean))];n.length===0&&w("name at least one skill to delete. `turbobase skills list` shows the slugs.");let o=await zr(e,r);if(!await is(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
3825
+ `));let l=a.items.filter(_=>_.action==="new"||_.action==="update").length,d=a.items.filter(_=>_.action==="refused").length;if(t.dryRun){L(h.dim("dry run \u2014 nothing was written.")),d>0&&(process.exitCode=1);return}let p=a;if(l>0){if(!t.yes){if(!Ne()){L(h.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1;return}if(await Le(`Write ${l} skill(s)${t.publish?" and publish them":" as drafts"}?`,[{value:"yes",label:"Yes"},{value:"no",label:"No \u2014 write nothing"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){L("aborted \u2014 nothing was written."),process.exitCode=1;return}}p=await i(!1)}let f=p.items.filter(_=>_.action==="new"||_.action==="update").map(_=>_.slug);if(b(`${f.length} written, ${p.items.filter(_=>_.action==="unchanged").length} unchanged, ${p.items.filter(_=>_.action==="refused").length} refused.`),t.publish&&f.length>0){let _;try{_=await J("publishing",()=>s.skillsPublish(f))}catch(y){V(y,"skills:publish","publish the pushed skills"),w(`the skills were written as drafts but publishing failed: ${y instanceof Error?y.message:String(y)}`)}b(h.green(`published ${_.published.join(", ")} \u2014 live as of release ${_.version.version_no}.`))}else t.publish?b(h.dim("nothing changed \u2014 nothing to publish.")):f.length>0&&L(h.dim("They are DRAFT \u2014 nothing is served yet. Publish with `turbobase skills publish <slug>` (needs `skills:publish`), or re-run with --publish."));p.items.some(_=>_.action==="refused")&&(L(h.red("one or more skill files were refused and not written.")),process.exitCode=1)}mt();var Q_=["proposed","active","rejected"],eS=["mechanic","operator","learning","code-baseline"],os=t=>new q(t);async function ss(t,e){let r=await H(t.baseUrl);return e(r)}function Qp(t,e,r){if(!t)return;let n=t.split(",").map(o=>o.trim()).filter(o=>o.length>0);if(n.length!==0){for(let o of n)e.includes(o)||w(`${r}: unknown value '${o}' \u2014 expected one of ${e.join(", ")}.`);return n}}function tS(t){if(t===void 0)return;let e=Number(t);return(!Number.isFinite(e)||e<=0)&&w("--limit must be a positive number."),Math.floor(e)}function rh(t){let e=Qp(t.status,Q_,"--status"),r=Qp(t.provenance,eS,"--provenance"),n=tS(t.limit);return{...e?{status:e}:{},...r?{provenance:r}:{},...t.recordType?{recordType:t.recordType}:{},...t.source?{source:t.source}:{},...n?{limit:n}:{}}}function eh(t){return!!(t.provenance?.length||t.recordType||t.source)}var nh=["ID","STATUS","PROVENANCE","RECORD","EVENT","SOURCE","EVIDENCE","ENFORCES"];function rS(t){return t.status==="active"?h.green("active"):t.status==="rejected"?h.dim("rejected"):h.yellow("proposed")}function nS(t){return t.message?t.message:t.kind&&t.field?h.dim(`${t.kind} ${t.field}`):t.kind?h.dim(t.kind):h.dim("(no description)")}function oh(t){return[t.hookId,rS(t),t.provenance==="learning"?h.yellow(t.provenance):t.provenance,t.recordType,t.event,t.source,String(t.taughtBy.length),nS(t)]}async function sh(t={},e=os){let r=await ss(t,e),n=rh(t),o;try{o=await r.proposals(n)}catch(i){V(i,"extensions:deploy","list hook proposals"),w(`list hook proposals failed: ${i instanceof Error?i.message:String(i)}`)}if(t.json)return b(JSON.stringify(o,null,2));if(o.length===0){let i=n.status?.length?n.status.join("/"):"proposed";return b(`no ${i} hook proposals.
3826
+ `+h.dim(" the Mechanic stages one when a sync failure teaches a repeatable invariant."))}b(ft(o.map(oh),{head:nh})),b(h.dim(" EVIDENCE = distinct sync failures that taught the rule. Arm one with `turbobase ext proposals promote <id>`."));let s=o.filter(i=>i.provenance==="learning"&&i.status==="proposed");s.length>0&&b(h.dim(` ${s.length} learning-provenance row(s) shown \u2014 those are armed through sign-off in the console, not from here.`))}async function oS(t,e,r){return r.yes?!0:Ne()?await Le(t,[{value:"yes",label:e},{value:"no",label:"No \u2014 leave them alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(L("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(L(h.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function sS(t){return!(t instanceof Q)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function $a(t,e){sS(t)&&V(t,"extensions:deploy",e)}function Ea(t,e){let r=e instanceof Q?e.body:void 0,n=r?.error==="forbidden"?r.reason??r.error:r?.error,s=n?{learning_requires_signoff:"learning-provenance rows are armed through sign-off in the console, not from the CLI",provenance_unverified:"the instance could not read the row back \u2014 refused rather than guessed",system_reserved:"a managed-service guardrail \u2014 contact support to adjust its feature flag",not_found:"no hook proposal with that id",wrong_kind:"that id is not a hook (conduits have their own review surface)",admin_required:"the PAT resolves to a non-admin user on this instance"}[n]??n:e instanceof Error?e.message:String(e);L(ve.error(`${h.bold(t)} \u2014 ${s}`))}async function th(t,e){try{let r=await t.proposalPromote(e);return b(ve.success(`${h.bold(e)} ${h.dim(`${r.previousStatus} \u2192`)} ${h.green(r.status)}`)),!0}catch(r){return $a(r,"promote a hook proposal"),Ea(e,r),!1}}async function ih(t,e={},r=os){!e.auto&&t.length===0&&w("promote: name at least one proposal id, or pass --auto with a filter."),e.auto&&t.length>0&&w("promote: pass ids OR --auto, not both \u2014 --auto selects by filter."),!e.auto&&(e.apply||e.all)&&w("promote: --apply / --all only mean something with --auto.");let n=await ss(e,r);if(!e.auto){let p=0;for(let f of t)await th(n,f)&&(p+=1);p>0&&b(h.dim(` ${p} hook(s) armed \u2014 the loader compiles them on its next reload.`)),p<t.length&&(process.exitCode=1);return}let o=rh({...e,status:e.status??"proposed"});o.provenance?.includes("learning")&&w("promote --auto: learning-provenance proposals are armed through sign-off in the console, not from the CLI. Drop `learning` from --provenance."),o.status?.some(p=>p!=="proposed")&&w("promote --auto: only `--status proposed` rows can be armed in bulk.");let s;try{s=await n.proposals(o)}catch(p){V(p,"extensions:deploy","list hook proposals"),w(`list hook proposals failed: ${p instanceof Error?p.message:String(p)}`)}let i=s.filter(p=>p.provenance==="learning"),a=s.filter(p=>p.provenance!=="learning");if(e.json&&(b(JSON.stringify({apply:!!e.apply,plan:a,skipped:i},null,2)),!e.apply))return;if(a.length===0){e.json||(b(`nothing to promote${eh(o)?" for that filter":""}.`),i.length>0&&b(h.dim(` ${i.length} learning-provenance row(s) skipped \u2014 they need sign-off.`)));return}if(e.json||(b(e.apply?`promoting ${h.bold(String(a.length))} hook proposal(s):`:`${h.bold("dry run")} \u2014 would promote ${h.bold(String(a.length))} hook proposal(s):`),b(ft(a.map(oh),{head:nh})),i.length>0&&b(h.dim(` ${i.length} learning-provenance row(s) skipped \u2014 armed through sign-off in the console.`))),!e.apply){b(""),b(ve.info("nothing was changed. Re-run with --apply to arm these."));return}if(!eh(o)&&!e.all&&w(`promote --auto --apply with no filter would arm all ${a.length} proposal(s) in the queue. Narrow it with --provenance / --record-type / --source, or pass --all to mean it.`),!await oS(`Arm ${a.length} hook proposal(s)? They start rejecting writes on the next loader reload.`,`Yes \u2014 promote ${a.length}`,e))return;let d=0;for(let p of a)await th(n,p.hookId)&&(d+=1);b(h.dim(` ${d}/${a.length} armed \u2014 the loader compiles them on its next reload. Undo one with \`turbobase ext proposals retract <id>\`.`)),d<a.length&&(process.exitCode=1)}async function ah(t,e={},r=os){t.length===0&&w("retract: name at least one proposal id.");let n=await ss(e,r),o=0;for(let s of t)try{let i=await n.proposalRetract(s);b(ve.success(`${h.bold(s)} ${h.dim(`${i.previousStatus} \u2192`)} ${h.yellow(i.status)}`)),o+=1}catch(i){$a(i,"retract a hook proposal"),Ea(s,i)}o>0&&b(h.dim(" source kept \u2014 re-arm with `turbobase ext proposals promote <id>`.")),o<t.length&&(process.exitCode=1)}async function lh(t,e={},r=os){t.length===0&&w("reject: name at least one proposal id.");let n=await ss(e,r),o=0;for(let s of t)try{let i=await n.proposalReject(s,e.reason);b(ve.success(`${h.bold(s)} ${h.dim(`${i.previousStatus} \u2192`)} ${h.dim(i.status)}`)),o+=1}catch(i){$a(i,"reject a hook proposal"),Ea(s,i)}o<t.length&&(process.exitCode=1)}mt();var Pa=t=>new q(t);async function iS(t,e){let r=await H(t.baseUrl);return e(r)}function aS(t){return!(t instanceof Q)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function lS(t,e){let r=e instanceof Q?e.body:void 0,n=r?.error==="forbidden"?r.reason??r.error:r?.error,s=n?{not_found:"no extension with that id",wrong_kind:"that id is not an extension this instance manages",system_reserved:"a managed-service guardrail \u2014 contact support to adjust its feature flag",learning_requires_signoff:"learning-provenance rows are armed through sign-off in the console, not from the CLI",provenance_unverified:"the instance could not read the row back \u2014 refused rather than guessed",admin_required:"the PAT resolves to a non-admin user on this instance"}[n]??n:e instanceof Error?e.message:String(e);L(ve.error(`${h.bold(t)} \u2014 ${s}`))}async function Aa(t,e,r,n,o,s,i){e.length===0&&w(`${t}: name at least one extension id.`);let a=await iS(r,n),l=[];for(let d of e)try{let p=await o(a,d);l.push(p),r.json||b(s(p))}catch(p){aS(p)&&V(p,"extensions:deploy",`${t} an extension`),lS(d,p)}if(r.json)b(JSON.stringify(l,null,2));else{let d=i(l.length);d&&b(h.dim(d))}l.length<e.length&&(process.exitCode=1)}async function ch(t,e={},r=Pa){await Aa("disable",t,e,r,(n,o)=>n.extensionDisable(o),n=>ve.success(`${h.bold(n.id)} ${h.dim(`${n.previousStatus} \u2192`)} ${h.yellow(n.status)}`),n=>n>0?" definition kept \u2014 the loader drops it on its next reload. Put it back with `turbobase ext enable <id>`.":null)}async function dh(t,e={},r=Pa){await Aa("enable",t,e,r,(n,o)=>n.extensionEnable(o),n=>ve.success(`${h.bold(n.id)} ${h.dim(`${n.previousStatus} \u2192`)} ${h.green(n.status)}`),n=>n>0?" the loader compiles it on its next reload.":null)}async function uh(t,e={},r=Pa){await Aa("remove",t,e,r,(n,o)=>n.extensionRemove(o),n=>ve.success(`${h.bold(n.id)} ${h.dim(`${n.previousStatus} \u2192`)} ${h.dim(n.status)}`),n=>n>0?" run history and everything it already wrote are kept. Redeploy the same id to bring it back.":null)}mt();var qr=t=>new q(t);async function zr(t,e){let r=await H(t.baseUrl);return e(r)}async function is(t,e,r,n){return n.yes?!0:Ne()?await Le(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(L("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(L(h.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function cS(t){return t.visibility!=="published"?h.dim("draft"):t.in_current_release?h.green("live"):h.yellow("unreleased")}function ph(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function dS(t){if(t.items.length===0)return["no skills on this instance."];let e=Math.max(4,...t.items.map(s=>s.slug.length)),r=[];for(let s of t.items)r.push(`${ph(h.bold(s.slug),e)} ${ph(cS(s),10)} ${s.surfaces.join(",")||h.dim("none")}`),s.description&&r.push(` ${h.dim(s.description)}`);r.push("");let n=t.items.filter(s=>s.visibility==="published"&&s.in_current_release).length,o=t.items.filter(s=>s.visibility!=="published").length;return r.push(`${t.items.length} skill(s) \xB7 ${n} injected \xB7 ${o} draft`+(t.currentVersion==null?"":` \xB7 release v${t.currentVersion}`)),r}async function hh(t,e=qr){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&w(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await zr(t,e),o;try{o=await J("reading the skills",()=>n.skillsList(r))}catch(s){V(s,"skills:publish","read the instance skills"),w(`could not read the skills: ${s instanceof Error?s.message:String(s)}`)}b(dS(o).join(`
3827
+ `))}async function mh(t,e,r=qr){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&w("name at least one skill slug. `turbobase skills list` shows them.");let o=await zr(e,r);if(!await is(`Publish ${n.length} skill(s)?`,"Yes \u2014 publish them","their text is injected into every matching turn from now on",e))return;let i;try{i=await J("publishing",()=>o.skillsPublish(n))}catch(a){V(a,"skills:publish","publish a skill"),w(`publish failed: ${a instanceof Error?a.message:String(a)}`)}b(h.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(L(h.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),L(h.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function fh(t,e,r=qr){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&w("name at least one skill slug. `turbobase skills list` shows them.");let o=await zr(e,r);if(!await is(`Move ${n.length} skill(s) back to draft?`,"Yes \u2014 unpublish them","they stop being injected immediately; the text and its history are kept",e))return;let i;try{i=await J("unpublishing",()=>o.skillsUnpublish(n))}catch(a){V(a,"skills:publish","unpublish a skill"),w(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}b(h.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),L(h.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(L(h.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function gh(t,e,r=qr){let n=Number(t);(!Number.isInteger(n)||n<1)&&w(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let o=await zr(e,r);if(await is(`Roll the skills back to release v${n}?`,"Yes \u2014 restore that release","content only: a skill an operator has since unpublished stays off",e))try{let i=await J("rolling back",()=>o.skillsRollback(n));b(h.green(`rolled back to v${i.version.version_no}.`))}catch(i){V(i,"skills:publish","roll back a skills release"),w(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function yh(t,e=qr){let r=await zr(t,e),n;try{n=await J("reading the releases",()=>r.skillsReleases())}catch(o){V(o,"skills:publish","read the skills releases"),w(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){L("no releases yet.");return}for(let o of n.items){let s=o.is_current?h.green("*"):" ",i=o.release_note?` \u2014 ${o.release_note}`:"";b(`${s} v${o.version_no} ${o.skill_count} skill(s) ${h.dim(o.published_at)}${o.published_by?h.dim(` by ${o.published_by}`):""}${h.dim(i)}`)}}async function bh(t,e,r=qr){let n=[...new Set((t??[]).map(d=>d.trim()).filter(Boolean))];n.length===0&&w("name at least one skill to delete. `turbobase skills list` shows the slugs.");let o=await zr(e,r);if(!await is(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
3814
3828
  ${n.join(`
3815
- `)}`,"Yes \u2014 delete them","permanent: the rows and their text are removed. Prior releases keep their own copy.",e))return;let i=[],a=[];for(let d of n)try{i.push(await J(`deleting ${d}`,()=>o.skillsDelete(d)))}catch(p){if(p instanceof Q&&p.status===404){a.push(d);continue}i.length>0&&L(m.dim(`deleted before the error: ${i.map(f=>f.slug).join(", ")}`)),V(p,"skills:publish","delete a skill"),w(`delete failed on '${d}': ${p instanceof Error?p.message:String(p)}`)}i.length>0&&b(m.green(`deleted ${i.length} skill(s).`));let l=i.filter(d=>d.wasPublished).map(d=>d.slug);l.length>0&&L(m.yellow(`Published until now, so no longer injected: ${l.join(", ")}`)),a.length>0&&(L(m.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as wm}from"node:fs";import{join as uS,relative as pS,resolve as mS,sep as hS}from"node:path";var fS=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),gS=new Set([".mcp.json",".env"]);function yS(t){return gS.has(t)||t.startsWith(".env.")&&t!==".env.example"}function bS(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function wS(t){return t.includes(0)}async function vm(t){let e=mS(t),r={},n=[],o=[],s=[];async function i(a){let l=await wm.readdir(a,{withFileTypes:!0});for(let d of l){let p=uS(a,d.name);if(fS.has(d.name))continue;if(d.isDirectory()){await i(p);continue}if(!d.isFile())continue;let f=pS(e,p).split(hS).join("/");if(yS(d.name)){o.push(f);continue}let _=await wm.readFile(p);if(!bS(_)){n.push(f);continue}wS(_)&&s.push(f),r[f]=_.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as vS}from"node:crypto";var _S="/_tb/app-assets",SS=16,kS=/^[0-9a-f]{32}$/;function _m(){return vS(SS).toString("hex")}function TS(t){return kS.test(t)}function Sm(t){if(!TS(t))throw new Error(`not a build id: ${t}`);return`${_S}/${t}/`}var km=7;Ia();var Oa=50*1024*1024;import as from"node:fs/promises";import An from"node:path";var Na={esbuild:"0.28.1","isolated-vm":"6.1.2"},La="@turbobase/isolated-vm-prebuilds";function ja(t,e){return`${t}-${e}`}function Da(t=process.versions){return`abi${t.modules}`}var Tm=["darwin-x64","win32-arm64"];async function xm(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=ja(e,r),o=An.join(t.home,"node_modules"),s=An.join(o,...La.split("/"),"prebuilds",n),i=An.join(o,"isolated-vm","prebuilds",n),a;try{a=await as.readdir(s)}catch{return[]}let l=[];await as.mkdir(i,{recursive:!0});for(let d of a){if(!d.endsWith(".node"))continue;let p=An.join(i,d);try{await as.copyFile(An.join(s,d),p,as.constants?.COPYFILE_EXCL??1),l.push(d)}catch{}}return l}import{homedir as xS}from"node:os";import{join as Rm}from"node:path";import{promises as Ua}from"node:fs";function Em(){let t=process.env.TURBOBASE_HOME??Rm(xS(),".turbobase");return{dir:t,file:Rm(t,"sandboxes.json")}}var RS={s:1e3,m:6e4,h:36e5,d:864e5};function $S(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*RS[e[2]]}function ES(t,e=Date.now()){return new Date(e+$S(t)).toISOString()}function PS(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function AS(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 CS(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 IS="[REDACTED]",Cn=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},Ma=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 OS(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new Ma(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:IS:n[o]=s}return n}function NS(t,e,r){return e.map(n=>OS(t,n,r))}var $m=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),LS=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function jS(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 qa(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 LS)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=jS(t);if(!$m.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...$m].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function DS(t,e=US){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function US(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function MS(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function qS(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function za(){let{file:t}=Em();try{let e=await Ua.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function Pm(t){let{dir:e,file:r}=Em();await Ua.mkdir(e,{recursive:!0}),await Ua.writeFile(r,`${JSON.stringify(t,null,2)}
3816
- `,{mode:384})}async function zS(t){let e=await za();e.push(t),await Pm(e)}async function Am(t){let e=await za(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Pm(e),n??null}async function ls(){return za()}function Ba(t,e=Date.now()){let r=[],n=[];for(let o of t)PS(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function Cm(t,e){qa(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new Cn(r);let n=AS(e.sample),o=e.now??Date.now(),s=(e.nameGen??(d=>DS(d)))(e.fromTenant),i=MS(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let d of a){let p=CS(d.rows,n),f=NS(d.table,p,d.classification);f.length>0&&await t.copyRows(i,d.table,f)}let l={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:ES(e.ttl,o),sampleFraction:n,url:qS(s,e.baseUrl)};return await zS(l),l}async function Im(t,e){qa(t.target());let n=(await ls()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await Am(e),n):null}async function Fa(t,e=Date.now()){qa(t.target());let r=await ls(),{expired:n}=Ba(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await Am(s.name),o.push(s)}return o}var In={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","mcp:data","mcp:write"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},lN=Object.keys(In).filter(t=>In[t].mintable);var uN=In.pat.prefix,BS=Object.entries(In).map(([t,e])=>[e.prefix,t]),FS=/^[A-Za-z0-9_-]{20,}$/;function HS(t){if(typeof t!="string")return null;for(let[e,r]of BS)if(t.startsWith(e)&&FS.test(t.slice(e.length)))return r;return null}function Om(t){return HS(t)==="pat"}bn();var KS=8e3,VS={revoked:"the instance REVOKED this token \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",expired:"this token has EXPIRED \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",unknown:"this instance has never seen this token \u2014 it was deleted, or it belongs to a DIFFERENT instance; check the base-url before minting a new PAT",suspended:"the user this token belongs to is SUSPENDED \u2014 an instance administrator has to restore the account; a new token will not help",malformed:"the stored credential is not shaped like a Turbobase PAT (tb_pat_\u2026) \u2014 sign in again",missing:"no token reached the instance \u2014 sign in again",transient:"the instance could not verify the token right now (a storage error, not a decision about the token) \u2014 retry"};function GS(t){return VS[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function WS(t,e,r=fetch){let n;try{n=await r(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(KS)})}catch(s){return{state:"unreachable",detail:s instanceof Error?s.message:String(s)}}if(n.status===200||n.status===403)return{state:"accepted"};if(n.status===401){let s=await n.json().catch(()=>null);return{state:"rejected",reason:typeof s?.reason=="string"&&s.reason?s.reason:"unknown"}}return(n.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${n.status} \u2014 this host does not serve the /v1 API`}}function Nm(t){return t.state==="accepted"?Ie()?m.green("accepted"):"accepted":t.state==="rejected"?Ie()?m.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Ie()?m.yellow("unreachable"):"unreachable"}async function Lm(t={},e=fetch){let r=await Ot(),{file:n}=Lo();if(r.length===0){b("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),L(m.dim(`no sign-ins stored in ${n}.`));return}let o=await mt(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await WS(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Ie())b(ft(s.map(i=>[i.active?m.green("*"):" ",m.bold(i.baseUrl),Nm(i.check),m.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} ${Nm(i.check)} (updated ${i.updatedAt})`);L(m.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(L(m.red(`${i.baseUrl}: ${GS(i.check.reason)}.`)),L(m.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&L(m.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||L("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function yA(t){let e=await Ot();e.length===0&&w("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Ne()||w("this command needs an explicit <base-url> in a non-interactive shell.");try{return await Le(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{w("cancelled.")}}async function bA(t,e){let r;try{r=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(o){return{ok:!1,kind:"unreachable",detail:o instanceof Error?o.message:String(o)}}let n=(r.headers.get("content-type")??"").includes("application/json");return r.status===200||r.status===403?{ok:!0}:r.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${r.status}`}:n?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${r.status}`}}function wA(t){L(""),L("Sharing is ON. Two things reach the Turbobase product team from this instance:"),L(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),L(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),L(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),L(" about OUR platform, with instance name, user names and ids masked before they leave."),L(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),L("")}async function vA(t,e,r){let n=await vu({baseUrl:t,token:e}),o=(await Ot()).length-1;if(b(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),wA(n.baseUrl),!r)return;let s=await bA(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(L(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),L(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),L(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?L(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):L(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function _A(t){let e=await aa(await Sn(t),zt(t)),r=_a(e);return r||w(`${t}: ${Sa(e)}`),{...r,sourceCode:e}}async function Pr(t,e,r,n){try{return await ae.access(t),"skipped"}catch{}return await ae.mkdir(zt(t),{recursive:!0}),await ae.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await ae.chmod(t,n),"wrote"}async function Lb(t,e){if(Db(t)!==".gitignore")return Pr(t,e.content,e.executable,e.mode);let r=await ae.readFile(t,"utf8").catch(()=>null);if(r===null)return Pr(t,e.content,e.executable,e.mode);let n=vp(r);return n===null?"skipped":(await ae.writeFile(t,n,"utf8"),"merged")}function qd(t){if(t!==void 0){if(t==="junit"||t==="json")return t;w(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function Oi(t){process.exit(t)}function SA(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 kA(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 TA(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 jb(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function Vd({includeInternal:t=!0}={}){let e=new gA;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.35.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",u=>u.command.parent?"":`${ha()}
3817
- `),e.hook("preAction",(u,h)=>{Op(e.opts(),h.opts())});let r=e.command("auth").description("Sign in to an instance and manage stored credentials."),n=e.command("project").description("Set up the local project and the files an agent session reads."),o=e.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),s=e.command("kb").description("Write into the instance's knowledge base."),i=e.command("skills").description("Write standing rules into the instance's agent skills.");r.command("login").description("Sign in to an instance by pasting a personal access token (PAT), stored in ~/.turbobase/credentials.").requiredOption("--base-url <url>","Instance base URL, e.g. https://acme.turbobase.app").option("--token <tb_pat_\u2026>","The PAT to store. Mint one in your app under Settings \u203A Access tokens.").option("--no-verify","Skip the post-login connectivity/token probe.").action(async u=>{let h=rt(u.baseUrl);u.token||w(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
3818
- ${$n} auth login --base-url ${h} --token tb_pat_\u2026`),Om(u.token)||w("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await vA(h,u.token,u.verify)}),r.command("status").description("Show every stored sign-in, where its token was read from, and whether the instance still accepts it.").option("--no-probe","List the stored sign-ins without asking each instance about its token.").action(async u=>Lm({probe:u.probe})),r.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async u=>{let h=u??await yA("Pick the active instance:"),v=await jo(h);if(!v){let x=await Ot();w(`no stored sign-in for ${rt(h)}.`+(x.length?` Stored: ${x.map(S=>S.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${rt(h)} --token tb_pat_\u2026\`.`)}b(`active instance \u2192 ${v.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 u=>{if(u.all){let x=await Ot();for(let S of x)await ta(S.baseUrl);b(`removed ${x.length} stored sign-in${x.length===1?"":"s"}.`);return}let h=await ta(u.baseUrl);h||w(u.baseUrl?`no stored sign-in for ${rt(u.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let v=await mt();b(`signed out of ${h}.`+(v?` Active instance \u2192 ${v.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 u=>{let{baseUrl:h,token:v}=await H(u.baseUrl),x;try{x=await mr({baseUrl:h,token:v,recordsOnly:u.recordsOnly})}catch(g){let T=g instanceof Error?g.message:String(g);if(!u.recordsOnly&&/openapi\.json failed \(401/.test(T)){L("types-gen: /v1/catalog/openapi.json needs a browser session \u2014 emitting record shapes only. The record shapes are the half apps generate against; for the OpenAPI half, run it from a signed-in browser session.");try{x=await mr({baseUrl:h,token:v,recordsOnly:!0})}catch(E){w(`types generation failed: ${E instanceof Error?E.message:String(E)}`)}}else w(`types generation failed: ${T}`)}let S=se(process.cwd(),u.out);await ae.writeFile(S,x,"utf8"),b(`wrote ${S} (${x.split(`
3819
- `).length} lines).`)}),jp(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 u=>{let{baseUrl:h,token:v}=await H(u.baseUrl),x=new URLSearchParams;u.records&&x.set("records",u.records),u.query&&x.set("query",u.query);let S=x.toString(),g=await fetch(`${h}/v1/catalog/grounding${S?`?${S}`:""}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});g.ok||w(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${g.status}`);let E=((await g.json()).markdown??"").trim(),A=se(process.cwd(),u.out),C=u.records?` records=${u.records}`:"",O=`<!-- GENERATED by \`turbobase project grounding\` against ${h}${C} \u2014 do not edit; re-run to refresh. -->
3829
+ `)}`,"Yes \u2014 delete them","permanent: the rows and their text are removed. Prior releases keep their own copy.",e))return;let i=[],a=[];for(let d of n)try{i.push(await J(`deleting ${d}`,()=>o.skillsDelete(d)))}catch(p){if(p instanceof Q&&p.status===404){a.push(d);continue}i.length>0&&L(h.dim(`deleted before the error: ${i.map(f=>f.slug).join(", ")}`)),V(p,"skills:publish","delete a skill"),w(`delete failed on '${d}': ${p instanceof Error?p.message:String(p)}`)}i.length>0&&b(h.green(`deleted ${i.length} skill(s).`));let l=i.filter(d=>d.wasPublished).map(d=>d.slug);l.length>0&&L(h.yellow(`Published until now, so no longer injected: ${l.join(", ")}`)),a.length>0&&(L(h.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as wh}from"node:fs";import{join as uS,relative as pS,resolve as hS,sep as mS}from"node:path";var fS=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),gS=new Set([".mcp.json",".env"]);function yS(t){return gS.has(t)||t.startsWith(".env.")&&t!==".env.example"}function bS(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function wS(t){return t.includes(0)}async function vh(t){let e=hS(t),r={},n=[],o=[],s=[];async function i(a){let l=await wh.readdir(a,{withFileTypes:!0});for(let d of l){let p=uS(a,d.name);if(fS.has(d.name))continue;if(d.isDirectory()){await i(p);continue}if(!d.isFile())continue;let f=pS(e,p).split(mS).join("/");if(yS(d.name)){o.push(f);continue}let _=await wh.readFile(p);if(!bS(_)){n.push(f);continue}wS(_)&&s.push(f),r[f]=_.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as vS}from"node:crypto";var _S="/_tb/app-assets",SS=16,kS=/^[0-9a-f]{32}$/;function _h(){return vS(SS).toString("hex")}function TS(t){return kS.test(t)}function Sh(t){if(!TS(t))throw new Error(`not a build id: ${t}`);return`${_S}/${t}/`}var kh=7;Ia();var Oa=50*1024*1024;import as from"node:fs/promises";import An from"node:path";var Na={esbuild:"0.28.1","isolated-vm":"6.1.2"},La="@turbobase/isolated-vm-prebuilds";function ja(t,e){return`${t}-${e}`}function Da(t=process.versions){return`abi${t.modules}`}var Th=["darwin-x64","win32-arm64"];async function xh(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=ja(e,r),o=An.join(t.home,"node_modules"),s=An.join(o,...La.split("/"),"prebuilds",n),i=An.join(o,"isolated-vm","prebuilds",n),a;try{a=await as.readdir(s)}catch{return[]}let l=[];await as.mkdir(i,{recursive:!0});for(let d of a){if(!d.endsWith(".node"))continue;let p=An.join(i,d);try{await as.copyFile(An.join(s,d),p,as.constants?.COPYFILE_EXCL??1),l.push(d)}catch{}}return l}import{homedir as xS}from"node:os";import{join as Rh}from"node:path";import{promises as Ua}from"node:fs";function Eh(){let t=process.env.TURBOBASE_HOME??Rh(xS(),".turbobase");return{dir:t,file:Rh(t,"sandboxes.json")}}var RS={s:1e3,m:6e4,h:36e5,d:864e5};function $S(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*RS[e[2]]}function ES(t,e=Date.now()){return new Date(e+$S(t)).toISOString()}function PS(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function AS(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 CS(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 IS="[REDACTED]",Cn=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},Ma=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 OS(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new Ma(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:IS:n[o]=s}return n}function NS(t,e,r){return e.map(n=>OS(t,n,r))}var $h=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),LS=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function jS(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 qa(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 LS)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=jS(t);if(!$h.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...$h].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function DS(t,e=US){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function US(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function MS(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function qS(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function za(){let{file:t}=Eh();try{let e=await Ua.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function Ph(t){let{dir:e,file:r}=Eh();await Ua.mkdir(e,{recursive:!0}),await Ua.writeFile(r,`${JSON.stringify(t,null,2)}
3830
+ `,{mode:384})}async function zS(t){let e=await za();e.push(t),await Ph(e)}async function Ah(t){let e=await za(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Ph(e),n??null}async function ls(){return za()}function Ba(t,e=Date.now()){let r=[],n=[];for(let o of t)PS(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function Ch(t,e){qa(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new Cn(r);let n=AS(e.sample),o=e.now??Date.now(),s=(e.nameGen??(d=>DS(d)))(e.fromTenant),i=MS(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let d of a){let p=CS(d.rows,n),f=NS(d.table,p,d.classification);f.length>0&&await t.copyRows(i,d.table,f)}let l={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:ES(e.ttl,o),sampleFraction:n,url:qS(s,e.baseUrl)};return await zS(l),l}async function Ih(t,e){qa(t.target());let n=(await ls()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await Ah(e),n):null}async function Fa(t,e=Date.now()){qa(t.target());let r=await ls(),{expired:n}=Ba(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await Ah(s.name),o.push(s)}return o}var In={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","mcp:data","mcp:write","rest:read","rest:write"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},lN=Object.keys(In).filter(t=>In[t].mintable);var uN=In.pat.prefix,BS=Object.entries(In).map(([t,e])=>[e.prefix,t]),FS=/^[A-Za-z0-9_-]{20,}$/;function HS(t){if(typeof t!="string")return null;for(let[e,r]of BS)if(t.startsWith(e)&&FS.test(t.slice(e.length)))return r;return null}function Oh(t){return HS(t)==="pat"}bn();var KS=8e3,VS={revoked:"the instance REVOKED this token \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",expired:"this token has EXPIRED \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",unknown:"this instance has never seen this token \u2014 it was deleted, or it belongs to a DIFFERENT instance; check the base-url before minting a new PAT",suspended:"the user this token belongs to is SUSPENDED \u2014 an instance administrator has to restore the account; a new token will not help",malformed:"the stored credential is not shaped like a Turbobase PAT (tb_pat_\u2026) \u2014 sign in again",missing:"no token reached the instance \u2014 sign in again",transient:"the instance could not verify the token right now (a storage error, not a decision about the token) \u2014 retry"};function GS(t){return VS[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function WS(t,e,r=fetch){let n;try{n=await r(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(KS)})}catch(s){return{state:"unreachable",detail:s instanceof Error?s.message:String(s)}}if(n.status===200||n.status===403)return{state:"accepted"};if(n.status===401){let s=await n.json().catch(()=>null);return{state:"rejected",reason:typeof s?.reason=="string"&&s.reason?s.reason:"unknown"}}return(n.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${n.status} \u2014 this host does not serve the /v1 API`}}function Nh(t){return t.state==="accepted"?Ie()?h.green("accepted"):"accepted":t.state==="rejected"?Ie()?h.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Ie()?h.yellow("unreachable"):"unreachable"}async function Lh(t={},e=fetch){let r=await Ot(),{file:n}=Lo();if(r.length===0){b("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),L(h.dim(`no sign-ins stored in ${n}.`));return}let o=await ht(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await WS(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Ie())b(ft(s.map(i=>[i.active?h.green("*"):" ",h.bold(i.baseUrl),Nh(i.check),h.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} ${Nh(i.check)} (updated ${i.updatedAt})`);L(h.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(L(h.red(`${i.baseUrl}: ${GS(i.check.reason)}.`)),L(h.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&L(h.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||L("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function yA(t){let e=await Ot();e.length===0&&w("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Ne()||w("this command needs an explicit <base-url> in a non-interactive shell.");try{return await Le(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{w("cancelled.")}}async function bA(t,e){let r;try{r=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(o){return{ok:!1,kind:"unreachable",detail:o instanceof Error?o.message:String(o)}}let n=(r.headers.get("content-type")??"").includes("application/json");return r.status===200||r.status===403?{ok:!0}:r.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${r.status}`}:n?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${r.status}`}}function wA(t){L(""),L("Sharing is ON. Two things reach the Turbobase product team from this instance:"),L(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),L(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),L(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),L(" about OUR platform, with instance name, user names and ids masked before they leave."),L(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),L("")}async function vA(t,e,r){let n=await vu({baseUrl:t,token:e}),o=(await Ot()).length-1;if(b(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),wA(n.baseUrl),!r)return;let s=await bA(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(L(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),L(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),L(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?L(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):L(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function _A(t){let e=await aa(await Sn(t),zt(t)),r=_a(e);return r||w(`${t}: ${Sa(e)}`),{...r,sourceCode:e}}async function Pr(t,e,r,n){try{return await ae.access(t),"skipped"}catch{}return await ae.mkdir(zt(t),{recursive:!0}),await ae.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await ae.chmod(t,n),"wrote"}async function Lb(t,e){if(Db(t)!==".gitignore")return Pr(t,e.content,e.executable,e.mode);let r=await ae.readFile(t,"utf8").catch(()=>null);if(r===null)return Pr(t,e.content,e.executable,e.mode);let n=vp(r);return n===null?"skipped":(await ae.writeFile(t,n,"utf8"),"merged")}function qd(t){if(t!==void 0){if(t==="junit"||t==="json")return t;w(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function Oi(t){process.exit(t)}function SA(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 kA(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 TA(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 jb(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function Vd({includeInternal:t=!0}={}){let e=new gA;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.37.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",u=>u.command.parent?"":`${ma()}
3831
+ `),e.hook("preAction",(u,m)=>{Op(e.opts(),m.opts())});let r=e.command("auth").description("Sign in to an instance and manage stored credentials."),n=e.command("project").description("Set up the local project and the files an agent session reads."),o=e.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),s=e.command("kb").description("Write into the instance's knowledge base."),i=e.command("skills").description("Write standing rules into the instance's agent skills.");r.command("login").description("Sign in to an instance by pasting a personal access token (PAT), stored in ~/.turbobase/credentials.").requiredOption("--base-url <url>","Instance base URL, e.g. https://acme.turbobase.app").option("--token <tb_pat_\u2026>","The PAT to store. Mint one in your app under Settings \u203A Access tokens.").option("--no-verify","Skip the post-login connectivity/token probe.").action(async u=>{let m=rt(u.baseUrl);u.token||w(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
3832
+ ${$n} auth login --base-url ${m} --token tb_pat_\u2026`),Oh(u.token)||w("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await vA(m,u.token,u.verify)}),r.command("status").description("Show every stored sign-in, where its token was read from, and whether the instance still accepts it.").option("--no-probe","List the stored sign-ins without asking each instance about its token.").action(async u=>Lh({probe:u.probe})),r.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async u=>{let m=u??await yA("Pick the active instance:"),v=await jo(m);if(!v){let x=await Ot();w(`no stored sign-in for ${rt(m)}.`+(x.length?` Stored: ${x.map(S=>S.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${rt(m)} --token tb_pat_\u2026\`.`)}b(`active instance \u2192 ${v.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 u=>{if(u.all){let x=await Ot();for(let S of x)await ta(S.baseUrl);b(`removed ${x.length} stored sign-in${x.length===1?"":"s"}.`);return}let m=await ta(u.baseUrl);m||w(u.baseUrl?`no stored sign-in for ${rt(u.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let v=await ht();b(`signed out of ${m}.`+(v?` Active instance \u2192 ${v.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 u=>{let{baseUrl:m,token:v}=await H(u.baseUrl),x;try{x=await hr({baseUrl:m,token:v,recordsOnly:u.recordsOnly})}catch(g){let T=g instanceof Error?g.message:String(g);if(!u.recordsOnly&&/openapi\.json failed \(401/.test(T)){L("types-gen: /v1/catalog/openapi.json needs a browser session \u2014 emitting record shapes only. The record shapes are the half apps generate against; for the OpenAPI half, run it from a signed-in browser session.");try{x=await hr({baseUrl:m,token:v,recordsOnly:!0})}catch(E){w(`types generation failed: ${E instanceof Error?E.message:String(E)}`)}}else w(`types generation failed: ${T}`)}let S=se(process.cwd(),u.out);await ae.writeFile(S,x,"utf8"),b(`wrote ${S} (${x.split(`
3833
+ `).length} lines).`)}),jp(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 u=>{let{baseUrl:m,token:v}=await H(u.baseUrl),x=new URLSearchParams;u.records&&x.set("records",u.records),u.query&&x.set("query",u.query);let S=x.toString(),g=await fetch(`${m}/v1/catalog/grounding${S?`?${S}`:""}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});g.ok||w(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${g.status}`);let E=((await g.json()).markdown??"").trim(),A=se(process.cwd(),u.out),C=u.records?` records=${u.records}`:"",O=`<!-- GENERATED by \`turbobase project grounding\` against ${m}${C} \u2014 do not edit; re-run to refresh. -->
3820
3834
 
3821
3835
  `;await ae.writeFile(A,O+(E?`${E}
3822
3836
  `:`(no grounding available yet)
3823
- `),"utf8"),b(`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.",u=>Number.parseInt(u,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each page\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--no-group","Plan every finding on its own instead of merging the ones that look related \u2014 N findings for one page become N sequential appends.").option("--yes","Skip the confirmation (for scripted runs).").action(u=>qp(u)),s.command("list").description("List the knowledge base\u2019s pages and whether each is actually readable. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only pages in this state.").action(u=>Bp(u)),s.command("publish").argument("<slug...>","Page slugs to publish (see `turbobase kb list`).").description("Publish pages: makes them reader-visible AND cuts a release scoped to them, so they are live when this returns.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((u,h)=>Fp(u,h)),s.command("unpublish").argument("<slug...>","Page slugs to retract.").description("Hide pages from readers immediately. The text and its history are kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((u,h)=>Hp(u,h)),s.command("versions").description("List knowledge-base releases, newest first, marking the current one. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(u=>Kp(u)),s.command("rollback").argument("<version>","Release number to restore (see `turbobase kb versions`).").description("Re-point the current knowledge-base release at an earlier one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((u,h)=>Vp(u,h)),s.command("delete").argument("<slug>","Page slug to delete (see `turbobase kb list`).").description("Delete a page and its subtree. SOFT \u2014 restorable from the editor\u2019s trash, unlike `skills delete`.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((u,h)=>Gp(u,h)),i.command("push").description("Write pending `## Agent rules` findings as draft agent rules, grouped by their `###` heading. Shows the plan and asks first; rules land unpublished and disabled.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--limit <n>","Cap how many findings to act on.",u=>Number.parseInt(u,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each rule\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--no-group","Ignore `###` headings \u2014 write one rule per finding.").option("--reapply","Also re-emit findings already applied \u2014 picks up a corrected `###` grouping or reworded body. Rules stay draft.").option("--from <dir>","Push the SKILL.md files under <dir> (one sub-directory per skill) instead of findings. Needs --app.").option("--publish","With --from: publish the skills this push wrote (new or changed). Needs a token carrying skills:publish.").option("--yes","Skip the confirmation (for scripted runs).").action(u=>(u.publish&&!u.from&&w("--publish applies to --from only: findings pushed from `## Agent rules` are published with `turbobase skills publish <slug>`."),u.from?Zp({baseUrl:u.baseUrl,from:u.from,app:u.app,dryRun:u.dryRun,publish:u.publish,yes:u.yes}):Wp(u))),i.command("list").description("List the instance\u2019s agent skills and whether each is actually injected. Needs `skills:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only skills in this state.").action(u=>mm(u)),i.command("publish").argument("<slug...>","Skill slugs to approve (see `turbobase skills list`).").description("Publish skills \u2014 live by the time this returns. Sets visibility and cuts a release scoped to these skills.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((u,h)=>hm(u,h)),i.command("unpublish").argument("<slug...>","Skill slugs to move back to draft.").description("Move skills back to draft. Retracts them from every prompt immediately \u2014 no release needed \u2014 and keeps the text.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((u,h)=>fm(u,h)),i.command("releases").description("List the skill releases, newest first \u2014 the rollback targets. Needs `skills:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(u=>ym(u)),i.command("rollback").argument("<version>","Release number to restore (see `turbobase skills releases`).").description("Re-point the current skill release at an earlier one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((u,h)=>gm(u,h)),i.command("delete").argument("<slug...>","Skill slugs to delete (see `turbobase skills list`).").description("Delete skills. Permanent; prior releases keep their own copy of the text. Takes several slugs so cleaning up a bad push is one command.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((u,h)=>bm(u,h));let a=o.command("new").description("Scaffold a new extension file.");a.command("hook").description("Scaffold a hook file under hooks/.").requiredOption("--record <type>","Record type the hook targets, e.g. salesOrder").option("--event <event>","Lifecycle event","before_save").option("--template <name>","require-field | enforce-format | blank","require-field").option("--field <name>","Field name (for require-field / enforce-format)").option("--regex <pattern>","Pattern (for enforce-format)").option("--source <source>","Source id (netsuite, stripe, \u2026)").option("--id <id>","Override the generated hook id").action(async u=>{let h;try{h=Rt("hook",{recordType:u.record,event:u.event,template:u.template,field:u.field,regex:u.regex,source:u.source,id:u.id})}catch(S){w(S instanceof Error?S.message:String(S))}let v=se(process.cwd(),h.relativePath);await Pr(v,h.content)==="skipped"&&w(`refusing to overwrite existing file: ${v}`),b(`wrote ${v}`)}),a.command("conduit").description("Scaffold a conduit file under conduits/ (cross-source bridge).").requiredOption("--source <source>","Origin source the record arrives from, e.g. shopify").requiredOption("--record <type>","Canonical record type the conduit triggers on, e.g. order").requiredOption("--to <source>","Target source the conduit bridges into, e.g. netsuite").option("--to-record <type>","Target record type (defaults to the trigger record type)").option("--event <event>","Cross-source lifecycle event","after_canonicalize_inbound").option("--id <id>","Override the generated conduit id").action(async u=>{let h;try{h=Rt("conduit",{recordType:u.record,source:u.source,to:u.to,toRecordType:u.toRecord,event:u.event,id:u.id})}catch(S){w(S instanceof Error?S.message:String(S))}let v=se(process.cwd(),h.relativePath);await Pr(v,h.content)==="skipped"&&w(`refusing to overwrite existing file: ${v}`),b(`wrote ${v}`)}),a.command("process").description("Scaffold a process file under processes/ (an invoked multi-record sequence).").requiredOption("--record <type>","Record type the first step writes, e.g. purchaseOrder").option("--then <type>","Record type of a second step that waits for the first, e.g. vendorBill").option("--on-failure <mode>","stop | rollback","stop").option("--id <id>","Override the generated process id").action(async u=>{let h;try{h=Rt("process",{recordType:u.record,then:u.then,onFailure:u.onFailure,id:u.id})}catch(S){w(S instanceof Error?S.message:String(S))}let v=se(process.cwd(),h.relativePath);await Pr(v,h.content)==="skipped"&&w(`refusing to overwrite existing file: ${v}`),b(`wrote ${v}`)}),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(u,h)=>{let v=qd(h.reporter),x=await Sn(se(process.cwd(),u)),S=se(process.cwd(),h.samples),g=await _n(S);g.length===0&&!v&&b(`no samples found under ${S} \u2014 add JSON fixtures to dry-run against.`);let T;try{T=await Ho(x,g.map(C=>C.fixture),{resolveDir:zt(se(process.cwd(),u))})}catch(C){w(`bundle failed: ${C instanceof Error?C.message:String(C)}`)}if(v){let C=SA(T);b(Vo(C,v)),Oi(C.cases.some(O=>O.status==="failed")?1:0)}let E=0;for(let C of T){let O=C.pass?m.green("PASS"):m.red("FAIL");C.pass||(E+=1);let G=C.error?` (error: ${C.error})`:C.observed!==C.expected?` (expected ${C.expected}, observed ${C.observed})`:C.rejection?` (rejected: ${C.rejection.code??"rejected"})`:"";b(` ${O} ${C.name}${G}`)}let A=`${T.length-E}/${T.length} sample(s) passed.`;b(`
3824
- ${E===0?m.green(A):m.yellow(A)}`),Oi(E>0?1:0)}),o.command("deploy").argument("[file]","The extension file to deploy (single-file mode; omit with --to).").description("Deploy one extension (POST /v1/extensions) or the whole bundle (--to \u2192 /v1/config/apply).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--to <env>","Deploy the WHOLE project config (hooks/, conduits/, turbobase/) to this env (sandbox|prod).").option("--prune","Also REMOVE anything on the instance this project no longer declares. Off by default \u2014 see `ext plan` for what it would take.").action(async(u,h)=>{if(h.to){let T=await zd(),{baseUrl:E,token:A}=await H(h.baseUrl),C=new q({baseUrl:E,token:A});try{let O=await J(`applying bundle to ${h.to}`,()=>C.configApply(T,{prune:h.prune}));b(`applied bundle to ${h.to}: +${O.applied.add} ~${O.applied.change} -${O.applied.destroy}`+(O.backfillsQueued.length?` (${O.backfillsQueued.length} backfill(s) queued)`:""));let G=O.skippedDestroys??[];if(G.length>0){L(`${G.length} resource(s) exist on ${h.to} but are not declared by this project \u2014 NOT removed:`);for(let N of G)L(` ${N.kind} ${N.id}`);L("Add them to this repo (`turbobase ext export` pulls them down), or re-run with --prune to remove them.")}}catch(O){O instanceof Q&&O.status===403&&w("apply forbidden (403) \u2014 the stored PAT is not for an admin."),w(`bundle apply failed: ${O instanceof Error?O.message:String(O)}`)}return}u||w("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:v,token:x}=await H(h.baseUrl),S=await _A(se(process.cwd(),u)),g=new q({baseUrl:v,token:x});try{let T=await J(`deploying ${Db(u)}`,()=>g.deploy(S));Ie()?b(Gt("Deployed",[`${m.bold(T.id)} ${Nr(T.status)} ${m.dim(T.outcome)}`])):b(`deployed ${T.id} \u2192 status=${T.status} (${T.outcome}).`)}catch(T){T instanceof Q&&T.status===403&&w("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),w(`deploy failed: ${T instanceof Error?T.message:String(T)}`)}});let l=e.command("apps").description("Manage hosted apps served in your Turbobase app.");l.command("deploy").description("Build the app (if needed) and deploy it \u2014 cuts a new live version at /a/<slug>.").argument("<app>","App slug or id.").argument("[dir]","Source or built directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--no-build","Upload the directory as-is; it is already a built bundle.").option("--no-install","Skip `npm install` (assume deps are present).").option("--no-pull","Do not pull generated source even when the dir has no package.json.").option("--entry <file>","SPA entrypoint served for unknown routes.","index.html").option("--create","Create the app first if it does not exist yet.").option("--proposal <id>","Widget proposal this ship realizes (defaults to .turbobase/proposal.json).").option("--preview","Deploy to a preview URL instead of going live. Nothing about /a/<slug> changes until you `apps promote` it.").option("--label <text>","Label for the preview, so several open previews are tellable apart.").option("--replace [preview-id]","Re-deploy onto an OPEN preview instead of opening a second one \u2014 the URL is unchanged, so whoever holds the link sees the new build. Omit the id when the app has exactly one open preview. Implies --preview.").option("--replace-label <text>","Re-deploy onto the open preview carrying this exact --label, opening one if there is none. The idempotent form for CI: one preview per pull request, updated in place. Implies --preview.").action(async(u,h,v)=>{let x=!!(v.preview||v.replace||v.replaceLabel);v.replace&&v.replaceLabel&&w("--replace and --replace-label both name the preview to re-deploy onto; pass one.");let S=se(process.cwd(),h??".");await ae.mkdir(S,{recursive:!0});let g=v.proposal??await $(S),{baseUrl:T,token:E}=await H(v.baseUrl),A=new q({baseUrl:T,token:E}),C=!1;try{C=(await A.appsList()).some(ie=>ie.slug===u||ie.id===u)}catch(ie){V(ie,"extensions:deploy","deploy"),w(`could not reach ${T}: ${ie instanceof Error?ie.message:String(ie)}`)}if(!C){v.create||w(`no app "${u}" on ${T} \u2014 create it with \`turbobase apps create ${u}\`, or pass --create.`);let ie=await J(`creating app ${u}`,()=>f(T,E,{slug:u},{tolerateExisting:!0}));ie.existed||b(`created ${ie.slug??u}.`)}let O;if(v.replace)if(typeof v.replace=="string")O=v.replace;else{let{previews:ie}=await F(T,E,u);if(ie.length===0&&w(`no open preview on ${u} to replace \u2014 drop --replace to open the first one, or name a handle from \`turbobase apps preview list\`.`),ie.length>1){for(let Re of ie)b(` ${Re.previewId} v${Re.version}${Re.label?` ${Re.label}`:""} ${Re.url}`);w(`${u} has ${ie.length} open previews \u2014 pass the one to replace, e.g. \`--replace ${ie[0].previewId}\`.`)}O=ie[0].previewId}let G;if(v.replaceLabel){let ie=v.replaceLabel,{previews:Re}=await F(T,E,u),xt=Re.filter(Di=>Di.label===ie);xt.length>0?(O=xt[0].previewId,xt.length>1&&L(`${xt.length} open previews carry the label "${ie}"; replacing the newest (${O}). Close the others with \`turbobase apps preview discard\`.`)):b(`no open preview labelled "${ie}" \u2014 opening one.`),G=ie}let N=ie=>ae.stat(et(S,ie)).then(()=>!0).catch(()=>!1),W=u,he=S,Z=v.build!==!1;if(Z&&!await N("package.json"))if(await N("index.html"))b("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),Z=!1;else if(v.pull===!1)w(`${S} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let ie=await J(`pulling ${u}`,()=>_(T,E,u));W=ie.slug??u,await y(S,ie.files,!0),b(`pulled generated source (rev ${ie.rev}).`)}let ye;if(Z){let ie=_m();if(ye={buildId:ie,assetBase:Sm(ie)},v.install!==!1&&!await N("node_modules")){b("installing dependencies\u2026");try{await I(["install"],S)}catch(Re){w(`npm install failed: ${Re instanceof Error?Re.message:String(Re)}`)}}b("building\u2026");try{await I(["run","build"],S,{TURBOBASE_ASSET_BASE:ye.assetBase})}catch(Re){w(`build failed: ${Re instanceof Error?Re.message:String(Re)}`)}await N("dist")||w(`no dist/ after build in ${S} \u2014 check the app's build script.`),he=et(S,"dist")}x&&!ye&&w(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${W}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let fe=await Oe(T,E,W,he,v.entry,g,ye,x?{label:v.label??G,replacePreviewId:O}:void 0);if(x){let ie=fe.previewUrl??"(no url returned)",Re=fe.expiresAt?new Date(fe.expiresAt).toLocaleDateString():`${km} days`,xt=fe.replacedVersion==null?null:`replaced v${fe.replacedVersion} \u2014 same URL`;if(Ie())b(Gt(xt?"Preview replaced":"Preview deployed",[`${m.bold(W)} ${m.green(`v${fe.version??"?"}`)} ${m.dim("not live")}`,`${m.bold(ie)}`,...xt?[m.dim(xt)]:[],m.dim(`expires ${Re}`)]));else{let Di=xt?`; ${xt}`:"";b(`preview ${W} v${fe.version??"?"} \u2192 ${ie} (expires ${Re}; /a/${W} unchanged${Di}).`)}Bt(fe),b(`next: turbobase apps promote ${W} ${fe.previewId??"<preview-id>"} # make it live`),b(` turbobase apps preview discard ${fe.previewId??"<preview-id>"}`);return}Ie()?b(Gt("Deployed",[`${m.bold(W)} ${m.green(`v${fe.version??"?"}`)} ${m.dim(fe.url??`/a/${W}`)}`])):b(`deployed ${W} \u2192 v${fe.version??"?"} (${fe.url??`/a/${W}`}).`),Bt(fe),Ft(fe),await Ht(fe,S)}),l.command("plan").description("Preflight this app's manifest against the instance \u2014 table conflicts, guardrail-blocked writes, and declared roles. Writes nothing.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim tables as `cli` or `app:<slug>`.").option("--app <slug>","The app this manifest belongs to (defaults to the slug in `--as app:<slug>`). Lets the plan tell this app's earlier role scopes from another app's, and list the content values a deploy would retire.").action(async(u,h)=>{let v=h.as?.startsWith("app:")?h.as.slice(4).trim():"";h.app!==void 0&&h.app.trim()===""&&w("--app was given an empty slug \u2014 pass the app's slug, or drop the flag.");let x=h.app?.trim()??"";x&&v&&x!==v&&w(`--app ${x} and --as app:${v} name two different apps \u2014 pass one slug.`);let S=x||v||null,g=await RA(u??".");g||w(`no public/turbobase.json under ${se(process.cwd(),u??".")}.`);let T=Array.isArray(g.manifest.tables)?g.manifest.tables:[],E=Array.isArray(g.manifest.writes)?g.manifest.writes:[],A=Array.isArray(g.manifest.roles)?g.manifest.roles:null,C=A??[],O=Array.isArray(g.manifest.labels)?g.manifest.labels:[],G=A!==null&&A.length===0;if(T.length===0&&E.length===0&&C.length===0&&O.length===0){if(!G)return b(`${g.manifestPath} declares no tables, writes, roles or labels \u2014 nothing to plan.`);if(S===null){for(let Z of ga({app:null,roles:A}))b(Z.text);return}}let{baseUrl:N,token:W}=await H(h.baseUrl),he=new q({baseUrl:N,token:W});if(T.length>0){let Z;try{Z=await J("planning tables",()=>he.tablesPlan({claimedBy:h.as,tables:T}))}catch(ye){V(ye,"extensions:deploy","plan tables"),Ro(ye)}b(`claiming as ${m.bold(Z.claimedBy)}`);for(let ye of Z.tables)xo(ye,{showClaimants:!0})}if(E.length>0||C.length>0||O.length>0||G&&S!==null){let Z;try{Z=await J("checking declared writes, roles and labels",()=>he.appsPlan({writes:E,...A!==null?{roles:A}:{},labels:O,...S!==null?{app:S}:{}}))}catch(ye){V(ye,"extensions:deploy","plan writes"),w(`plan writes failed: ${ye instanceof Error?ye.message:String(ye)}`)}Z.roles&&Ce("plan",Z.roles.verdicts,Z.roles.retired);for(let ye of ga({app:S,roles:A,retired:Z.roles?.retired??null}))b(ye.text);if(Z.labels&&Z.labels.verdicts.length>0){b(""),b(m.bold("labels"));let ye=Math.max(...Z.labels.verdicts.map(fe=>fe.name.length));for(let fe of Z.labels.verdicts){let ie=fe.name.padEnd(ye);if(fe.action==="create")b(` create ${ie} ${m.dim(fe.color)}`);else{let Re=fe.declaredColor?`${fe.color} \u2014 declared ${fe.declaredColor}, the instance's colour is kept`:fe.color;b(` ${m.dim("ok")} ${ie} ${m.dim(Re)}`)}}b(m.dim(" labels are launcher navigation \u2014 a chip on the app card and a filter pill on /apps. They grant nothing."))}E.length>0&&b("");for(let ye of Z.verdicts){let fe=`${ye.source} ${ye.recordType}.${ye.op}`;ye.allowed?ye.heldForApproval?b(`${m.dim("HELD")} ${fe} \u2014 allowed, but each write waits for operator approval.`):b(`${m.dim("ok")} ${fe}`):L(`${m.bold("DENIED")} ${fe}${ye.rule?` \u2014 guardrail "${ye.rule}"`:""} (${ye.reason})`)}Z.ok||(b(""),w(Z.message??(Z.roles&&!Z.roles.ok?"one or more declared roles cannot be created.":"a guardrail refuses one or more declared writes \u2014 an admin must allow them, or the app must stop declaring them.")))}b(""),b(m.dim("nothing was applied \u2014 this is a preflight. `turbobase apps deploy` runs the same checks and enforces them."))}),l.command("promote").description("Make a preview the live version at /a/<slug>. Promotes the exact reviewed bytes \u2014 no rebuild.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to promote (from `apps preview list`).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h,v)=>{let{baseUrl:x,token:S}=await H(v.baseUrl),g=await J(`promoting ${h}`,()=>Y(x,S,u,"promote",{previewId:h}));Ie()?b(Gt("Promoted",[`${m.bold(u)} ${m.green(`v${g.version??"?"}`)} ${m.dim(g.url??`/a/${u}`)}`])):b(`promoted ${u} \u2192 v${g.version??"?"} is now live at ${g.url??`/a/${u}`}.`);let T=fp(g);Ce("applied",T.verdicts,T.retired),Ft({labels:g.labels?{applied:!0,verdicts:g.labels}:null}),await Ht(g)});let d=l.command("preview").description("Inspect and manage an app's open previews.");d.command("list").description("List an app's open previews (newest first).").argument("<app>","App slug or id.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a line per preview.").action(async(u,h)=>{let{baseUrl:v,token:x}=await H(h.baseUrl),S=await F(v,x,u);if(h.json)return b(JSON.stringify(S.previews,null,2));if(S.previews.length===0){b(`no open previews for ${u}.`);return}for(let g of S.previews){let T=g.label?` ${g.label}`:"",E=g.expiresAt?new Date(g.expiresAt).toLocaleDateString():"?";b(`v${g.version} ${g.previewId}${T} ${g.url} (expires ${E})`)}}),d.command("discard").description("Close a preview. The URL stops resolving; the version stays in deploy history.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to discard.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h,v)=>{let{baseUrl:x,token:S}=await H(v.baseUrl);await J(`discarding ${h}`,()=>Y(x,S,u,"discard",{previewId:h})),b(`discarded ${h}.`)}),l.command("create").description("Create a new hosted app (a bare app row) so a build can be shipped to it.").argument("<slug>","URL slug the app is served under: /a/<slug>.").option("--name <name>","Display name (defaults to the slug).").option("--description <text>","Optional description.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{let{baseUrl:v,token:x}=await H(h.baseUrl),S=await J(`creating ${u}`,()=>f(v,x,{slug:u,name:h.name,description:h.description})),g=S.slug??u;Ie()?b(Gt("Created",[`${m.bold(g)} ${m.dim(S.url??`/a/${g}`)}`])):b(`created ${g} (${S.url??`/a/${g}`}).`),b(`next: turbobase apps push ${g} . # store the source`),b(` turbobase apps deploy ${g} # build + go live`)});let p=Do(fetch);async function f(u,h,v,x={}){let S=`${u.replace(/\/+$/,"")}/v1/apps`,g;try{g=await p(S,{method:"POST",headers:{Authorization:`Bearer ${h}`,"content-type":"application/json"},body:JSON.stringify({slug:v.slug,name:v.name??v.slug,description:v.description})})}catch(T){w(`create request failed: ${T instanceof Error?T.message:String(T)}`)}if(g.status===401&&w("create unauthorized (401) \u2014 re-run `turbobase auth login`."),g.status===403&&w("create forbidden (403) \u2014 the PAT is not for an admin."),g.status===409){if(x.tolerateExisting)return{slug:v.slug,existed:!0};w(`an app with slug "${v.slug}" already exists.`)}return g.ok||w(`create failed: HTTP ${g.status} ${(await g.text().catch(()=>"")).slice(0,200)}`),await g.json().catch(()=>({}))}async function _(u,h,v){let x=`${u.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(v)}/pull`,S;try{S=await p(x,{headers:{Authorization:`Bearer ${h}`}})}catch(g){w(`pull request failed: ${g instanceof Error?g.message:String(g)}`)}return S.status===401&&w("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),S.status===403&&w("pull forbidden (403) \u2014 the PAT is not for an admin."),S.status===404&&w(`no generated source for "${v}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),S.ok||w(`pull failed: HTTP ${S.status} ${(await S.text().catch(()=>"")).slice(0,200)}`),await S.json()}async function y(u,h,v){let x=se(u),S=0;for(let[g,T]of Object.entries(h)){let E=se(x,g);E!==x&&!E.startsWith(x+Hd)&&w(`refusing to write outside ${x}: ${g}`),v||await ae.stat(E).then(()=>!0).catch(()=>!1)&&w(`${E} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await ae.mkdir(zt(E),{recursive:!0}),await ae.writeFile(E,T,"utf8"),S+=1}return S}function k(u){let h=u.indexOf(","),v=u.startsWith("data:")?h>=0?u.slice(h+1):"":u;if(!v)return null;try{let x=Buffer.from(v,"base64");return x.length>0?new Uint8Array(x):null}catch{return null}}async function R(u,h,v){let x=se(u),S=async(T,E)=>{let A=se(x,T);A!==x&&!A.startsWith(x+Hd)&&w(`refusing to write outside ${x}: ${T}`),v||await ae.stat(A).then(()=>!0).catch(()=>!1)&&w(`${A} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await ae.mkdir(zt(A),{recursive:!0}),await ae.writeFile(A,E)},g=`# ${h.title||"App change request"}
3837
+ `),"utf8"),b(`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.",u=>Number.parseInt(u,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each page\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--no-group","Plan every finding on its own instead of merging the ones that look related \u2014 N findings for one page become N sequential appends.").option("--yes","Skip the confirmation (for scripted runs).").action(u=>qp(u)),s.command("list").description("List the knowledge base\u2019s pages and whether each is actually readable. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only pages in this state.").action(u=>Bp(u)),s.command("publish").argument("<slug...>","Page slugs to publish (see `turbobase kb list`).").description("Publish pages: makes them reader-visible AND cuts a release scoped to them, so they are live when this returns.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((u,m)=>Fp(u,m)),s.command("unpublish").argument("<slug...>","Page slugs to retract.").description("Hide pages from readers immediately. The text and its history are kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((u,m)=>Hp(u,m)),s.command("versions").description("List knowledge-base releases, newest first, marking the current one. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(u=>Kp(u)),s.command("rollback").argument("<version>","Release number to restore (see `turbobase kb versions`).").description("Re-point the current knowledge-base release at an earlier one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((u,m)=>Vp(u,m)),s.command("delete").argument("<slug>","Page slug to delete (see `turbobase kb list`).").description("Delete a page and its subtree. SOFT \u2014 restorable from the editor\u2019s trash, unlike `skills delete`.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((u,m)=>Gp(u,m)),i.command("push").description("Write pending `## Agent rules` findings as draft agent rules, grouped by their `###` heading. Shows the plan and asks first; rules land unpublished and disabled.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--limit <n>","Cap how many findings to act on.",u=>Number.parseInt(u,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each rule\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--no-group","Ignore `###` headings \u2014 write one rule per finding.").option("--reapply","Also re-emit findings already applied \u2014 picks up a corrected `###` grouping or reworded body. Rules stay draft.").option("--from <dir>","Push the SKILL.md files under <dir> (one sub-directory per skill) instead of findings. Needs --app.").option("--publish","With --from: publish the skills this push wrote (new or changed). Needs a token carrying skills:publish.").option("--yes","Skip the confirmation (for scripted runs).").action(u=>(u.publish&&!u.from&&w("--publish applies to --from only: findings pushed from `## Agent rules` are published with `turbobase skills publish <slug>`."),u.from?Zp({baseUrl:u.baseUrl,from:u.from,app:u.app,dryRun:u.dryRun,publish:u.publish,yes:u.yes}):Wp(u))),i.command("list").description("List the instance\u2019s agent skills and whether each is actually injected. Needs `skills:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only skills in this state.").action(u=>hh(u)),i.command("publish").argument("<slug...>","Skill slugs to approve (see `turbobase skills list`).").description("Publish skills \u2014 live by the time this returns. Sets visibility and cuts a release scoped to these skills.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((u,m)=>mh(u,m)),i.command("unpublish").argument("<slug...>","Skill slugs to move back to draft.").description("Move skills back to draft. Retracts them from every prompt immediately \u2014 no release needed \u2014 and keeps the text.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((u,m)=>fh(u,m)),i.command("releases").description("List the skill releases, newest first \u2014 the rollback targets. Needs `skills:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(u=>yh(u)),i.command("rollback").argument("<version>","Release number to restore (see `turbobase skills releases`).").description("Re-point the current skill release at an earlier one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((u,m)=>gh(u,m)),i.command("delete").argument("<slug...>","Skill slugs to delete (see `turbobase skills list`).").description("Delete skills. Permanent; prior releases keep their own copy of the text. Takes several slugs so cleaning up a bad push is one command.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((u,m)=>bh(u,m));let a=o.command("new").description("Scaffold a new extension file.");a.command("hook").description("Scaffold a hook file under hooks/.").requiredOption("--record <type>","Record type the hook targets, e.g. salesOrder").option("--event <event>","Lifecycle event","before_save").option("--template <name>","require-field | enforce-format | blank","require-field").option("--field <name>","Field name (for require-field / enforce-format)").option("--regex <pattern>","Pattern (for enforce-format)").option("--source <source>","Source id (netsuite, stripe, \u2026)").option("--id <id>","Override the generated hook id").action(async u=>{let m;try{m=Rt("hook",{recordType:u.record,event:u.event,template:u.template,field:u.field,regex:u.regex,source:u.source,id:u.id})}catch(S){w(S instanceof Error?S.message:String(S))}let v=se(process.cwd(),m.relativePath);await Pr(v,m.content)==="skipped"&&w(`refusing to overwrite existing file: ${v}`),b(`wrote ${v}`)}),a.command("conduit").description("Scaffold a conduit file under conduits/ (cross-source bridge).").requiredOption("--source <source>","Origin source the record arrives from, e.g. shopify").requiredOption("--record <type>","Canonical record type the conduit triggers on, e.g. order").requiredOption("--to <source>","Target source the conduit bridges into, e.g. netsuite").option("--to-record <type>","Target record type (defaults to the trigger record type)").option("--event <event>","Cross-source lifecycle event","after_canonicalize_inbound").option("--id <id>","Override the generated conduit id").action(async u=>{let m;try{m=Rt("conduit",{recordType:u.record,source:u.source,to:u.to,toRecordType:u.toRecord,event:u.event,id:u.id})}catch(S){w(S instanceof Error?S.message:String(S))}let v=se(process.cwd(),m.relativePath);await Pr(v,m.content)==="skipped"&&w(`refusing to overwrite existing file: ${v}`),b(`wrote ${v}`)}),a.command("process").description("Scaffold a process file under processes/ (an invoked multi-record sequence).").requiredOption("--record <type>","Record type the first step writes, e.g. purchaseOrder").option("--then <type>","Record type of a second step that waits for the first, e.g. vendorBill").option("--on-failure <mode>","stop | rollback","stop").option("--id <id>","Override the generated process id").action(async u=>{let m;try{m=Rt("process",{recordType:u.record,then:u.then,onFailure:u.onFailure,id:u.id})}catch(S){w(S instanceof Error?S.message:String(S))}let v=se(process.cwd(),m.relativePath);await Pr(v,m.content)==="skipped"&&w(`refusing to overwrite existing file: ${v}`),b(`wrote ${v}`)}),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(u,m)=>{let v=qd(m.reporter),x=await Sn(se(process.cwd(),u)),S=se(process.cwd(),m.samples),g=await _n(S);g.length===0&&!v&&b(`no samples found under ${S} \u2014 add JSON fixtures to dry-run against.`);let T;try{T=await Ho(x,g.map(C=>C.fixture),{resolveDir:zt(se(process.cwd(),u))})}catch(C){w(`bundle failed: ${C instanceof Error?C.message:String(C)}`)}if(v){let C=SA(T);b(Vo(C,v)),Oi(C.cases.some(O=>O.status==="failed")?1:0)}let E=0;for(let C of T){let O=C.pass?h.green("PASS"):h.red("FAIL");C.pass||(E+=1);let G=C.error?` (error: ${C.error})`:C.observed!==C.expected?` (expected ${C.expected}, observed ${C.observed})`:C.rejection?` (rejected: ${C.rejection.code??"rejected"})`:"";b(` ${O} ${C.name}${G}`)}let A=`${T.length-E}/${T.length} sample(s) passed.`;b(`
3838
+ ${E===0?h.green(A):h.yellow(A)}`),Oi(E>0?1:0)}),o.command("deploy").argument("[file]","The extension file to deploy (single-file mode; omit with --to).").description("Deploy one extension (POST /v1/extensions) or the whole bundle (--to \u2192 /v1/config/apply).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--to <env>","Deploy the WHOLE project config (hooks/, conduits/, turbobase/) to this env (sandbox|prod).").option("--prune","Also REMOVE anything on the instance this project no longer declares. Off by default \u2014 see `ext plan` for what it would take.").action(async(u,m)=>{if(m.to){let T=await zd(),{baseUrl:E,token:A}=await H(m.baseUrl),C=new q({baseUrl:E,token:A});try{let O=await J(`applying bundle to ${m.to}`,()=>C.configApply(T,{prune:m.prune}));b(`applied bundle to ${m.to}: +${O.applied.add} ~${O.applied.change} -${O.applied.destroy}`+(O.backfillsQueued.length?` (${O.backfillsQueued.length} backfill(s) queued)`:""));let G=O.skippedDestroys??[];if(G.length>0){L(`${G.length} resource(s) exist on ${m.to} but are not declared by this project \u2014 NOT removed:`);for(let N of G)L(` ${N.kind} ${N.id}`);L("Add them to this repo (`turbobase ext export` pulls them down), or re-run with --prune to remove them.")}}catch(O){O instanceof Q&&O.status===403&&w("apply forbidden (403) \u2014 the stored PAT is not for an admin."),w(`bundle apply failed: ${O instanceof Error?O.message:String(O)}`)}return}u||w("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:v,token:x}=await H(m.baseUrl),S=await _A(se(process.cwd(),u)),g=new q({baseUrl:v,token:x});try{let T=await J(`deploying ${Db(u)}`,()=>g.deploy(S));Ie()?b(Gt("Deployed",[`${h.bold(T.id)} ${Nr(T.status)} ${h.dim(T.outcome)}`])):b(`deployed ${T.id} \u2192 status=${T.status} (${T.outcome}).`)}catch(T){T instanceof Q&&T.status===403&&w("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),w(`deploy failed: ${T instanceof Error?T.message:String(T)}`)}});let l=e.command("apps").description("Manage hosted apps served in your Turbobase app.");l.command("deploy").description("Build the app (if needed) and deploy it \u2014 cuts a new live version at /a/<slug>.").argument("<app>","App slug or id.").argument("[dir]","Source or built directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--no-build","Upload the directory as-is; it is already a built bundle.").option("--no-install","Skip `npm install` (assume deps are present).").option("--no-pull","Do not pull generated source even when the dir has no package.json.").option("--entry <file>","SPA entrypoint served for unknown routes.","index.html").option("--create","Create the app first if it does not exist yet.").option("--proposal <id>","Widget proposal this ship realizes (defaults to .turbobase/proposal.json).").option("--preview","Deploy to a preview URL instead of going live. Nothing about /a/<slug> changes until you `apps promote` it.").option("--label <text>","Label for the preview, so several open previews are tellable apart.").option("--replace [preview-id]","Re-deploy onto an OPEN preview instead of opening a second one \u2014 the URL is unchanged, so whoever holds the link sees the new build. Omit the id when the app has exactly one open preview. Implies --preview.").option("--replace-label <text>","Re-deploy onto the open preview carrying this exact --label, opening one if there is none. The idempotent form for CI: one preview per pull request, updated in place. Implies --preview.").action(async(u,m,v)=>{let x=!!(v.preview||v.replace||v.replaceLabel);v.replace&&v.replaceLabel&&w("--replace and --replace-label both name the preview to re-deploy onto; pass one.");let S=se(process.cwd(),m??".");await ae.mkdir(S,{recursive:!0});let g=v.proposal??await $(S),{baseUrl:T,token:E}=await H(v.baseUrl),A=new q({baseUrl:T,token:E}),C=!1;try{C=(await A.appsList()).some(ie=>ie.slug===u||ie.id===u)}catch(ie){V(ie,"extensions:deploy","deploy"),w(`could not reach ${T}: ${ie instanceof Error?ie.message:String(ie)}`)}if(!C){v.create||w(`no app "${u}" on ${T} \u2014 create it with \`turbobase apps create ${u}\`, or pass --create.`);let ie=await J(`creating app ${u}`,()=>f(T,E,{slug:u},{tolerateExisting:!0}));ie.existed||b(`created ${ie.slug??u}.`)}let O;if(v.replace)if(typeof v.replace=="string")O=v.replace;else{let{previews:ie}=await F(T,E,u);if(ie.length===0&&w(`no open preview on ${u} to replace \u2014 drop --replace to open the first one, or name a handle from \`turbobase apps preview list\`.`),ie.length>1){for(let Re of ie)b(` ${Re.previewId} v${Re.version}${Re.label?` ${Re.label}`:""} ${Re.url}`);w(`${u} has ${ie.length} open previews \u2014 pass the one to replace, e.g. \`--replace ${ie[0].previewId}\`.`)}O=ie[0].previewId}let G;if(v.replaceLabel){let ie=v.replaceLabel,{previews:Re}=await F(T,E,u),xt=Re.filter(Di=>Di.label===ie);xt.length>0?(O=xt[0].previewId,xt.length>1&&L(`${xt.length} open previews carry the label "${ie}"; replacing the newest (${O}). Close the others with \`turbobase apps preview discard\`.`)):b(`no open preview labelled "${ie}" \u2014 opening one.`),G=ie}let N=ie=>ae.stat(et(S,ie)).then(()=>!0).catch(()=>!1),W=u,me=S,Z=v.build!==!1;if(Z&&!await N("package.json"))if(await N("index.html"))b("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),Z=!1;else if(v.pull===!1)w(`${S} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let ie=await J(`pulling ${u}`,()=>_(T,E,u));W=ie.slug??u,await y(S,ie.files,!0),b(`pulled generated source (rev ${ie.rev}).`)}let ye;if(Z){let ie=_h();if(ye={buildId:ie,assetBase:Sh(ie)},v.install!==!1&&!await N("node_modules")){b("installing dependencies\u2026");try{await I(["install"],S)}catch(Re){w(`npm install failed: ${Re instanceof Error?Re.message:String(Re)}`)}}b("building\u2026");try{await I(["run","build"],S,{TURBOBASE_ASSET_BASE:ye.assetBase})}catch(Re){w(`build failed: ${Re instanceof Error?Re.message:String(Re)}`)}await N("dist")||w(`no dist/ after build in ${S} \u2014 check the app's build script.`),me=et(S,"dist")}x&&!ye&&w(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${W}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let fe=await Oe(T,E,W,me,v.entry,g,ye,x?{label:v.label??G,replacePreviewId:O}:void 0);if(x){let ie=fe.previewUrl??"(no url returned)",Re=fe.expiresAt?new Date(fe.expiresAt).toLocaleDateString():`${kh} days`,xt=fe.replacedVersion==null?null:`replaced v${fe.replacedVersion} \u2014 same URL`;if(Ie())b(Gt(xt?"Preview replaced":"Preview deployed",[`${h.bold(W)} ${h.green(`v${fe.version??"?"}`)} ${h.dim("not live")}`,`${h.bold(ie)}`,...xt?[h.dim(xt)]:[],h.dim(`expires ${Re}`)]));else{let Di=xt?`; ${xt}`:"";b(`preview ${W} v${fe.version??"?"} \u2192 ${ie} (expires ${Re}; /a/${W} unchanged${Di}).`)}Bt(fe),b(`next: turbobase apps promote ${W} ${fe.previewId??"<preview-id>"} # make it live`),b(` turbobase apps preview discard ${fe.previewId??"<preview-id>"}`);return}Ie()?b(Gt("Deployed",[`${h.bold(W)} ${h.green(`v${fe.version??"?"}`)} ${h.dim(fe.url??`/a/${W}`)}`])):b(`deployed ${W} \u2192 v${fe.version??"?"} (${fe.url??`/a/${W}`}).`),Bt(fe),Ft(fe),await Ht(fe,S)}),l.command("plan").description("Preflight this app's manifest against the instance \u2014 table conflicts, guardrail-blocked writes, and declared roles. Writes nothing.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim tables as `cli` or `app:<slug>`.").option("--app <slug>","The app this manifest belongs to (defaults to the slug in `--as app:<slug>`). Lets the plan tell this app's earlier role scopes from another app's, and list the content values a deploy would retire.").action(async(u,m)=>{let v=m.as?.startsWith("app:")?m.as.slice(4).trim():"";m.app!==void 0&&m.app.trim()===""&&w("--app was given an empty slug \u2014 pass the app's slug, or drop the flag.");let x=m.app?.trim()??"";x&&v&&x!==v&&w(`--app ${x} and --as app:${v} name two different apps \u2014 pass one slug.`);let S=x||v||null,g=await RA(u??".");g||w(`no public/turbobase.json under ${se(process.cwd(),u??".")}.`);let T=Array.isArray(g.manifest.tables)?g.manifest.tables:[],E=Array.isArray(g.manifest.writes)?g.manifest.writes:[],A=Array.isArray(g.manifest.roles)?g.manifest.roles:null,C=A??[],O=Array.isArray(g.manifest.labels)?g.manifest.labels:[],G=A!==null&&A.length===0;if(T.length===0&&E.length===0&&C.length===0&&O.length===0){if(!G)return b(`${g.manifestPath} declares no tables, writes, roles or labels \u2014 nothing to plan.`);if(S===null){for(let Z of ga({app:null,roles:A}))b(Z.text);return}}let{baseUrl:N,token:W}=await H(m.baseUrl),me=new q({baseUrl:N,token:W});if(T.length>0){let Z;try{Z=await J("planning tables",()=>me.tablesPlan({claimedBy:m.as,tables:T}))}catch(ye){V(ye,"extensions:deploy","plan tables"),Ro(ye)}b(`claiming as ${h.bold(Z.claimedBy)}`);for(let ye of Z.tables)xo(ye,{showClaimants:!0})}if(E.length>0||C.length>0||O.length>0||G&&S!==null){let Z;try{Z=await J("checking declared writes, roles and labels",()=>me.appsPlan({writes:E,...A!==null?{roles:A}:{},labels:O,...S!==null?{app:S}:{}}))}catch(ye){V(ye,"extensions:deploy","plan writes"),w(`plan writes failed: ${ye instanceof Error?ye.message:String(ye)}`)}Z.roles&&Ce("plan",Z.roles.verdicts,Z.roles.retired);for(let ye of ga({app:S,roles:A,retired:Z.roles?.retired??null}))b(ye.text);if(Z.labels&&Z.labels.verdicts.length>0){b(""),b(h.bold("labels"));let ye=Math.max(...Z.labels.verdicts.map(fe=>fe.name.length));for(let fe of Z.labels.verdicts){let ie=fe.name.padEnd(ye);if(fe.action==="create")b(` create ${ie} ${h.dim(fe.color)}`);else{let Re=fe.declaredColor?`${fe.color} \u2014 declared ${fe.declaredColor}, the instance's colour is kept`:fe.color;b(` ${h.dim("ok")} ${ie} ${h.dim(Re)}`)}}b(h.dim(" labels are launcher navigation \u2014 a chip on the app card and a filter pill on /apps. They grant nothing."))}E.length>0&&b("");for(let ye of Z.verdicts){let fe=`${ye.source} ${ye.recordType}.${ye.op}`;ye.allowed?ye.heldForApproval?b(`${h.dim("HELD")} ${fe} \u2014 allowed, but each write waits for operator approval.`):b(`${h.dim("ok")} ${fe}`):L(`${h.bold("DENIED")} ${fe}${ye.rule?` \u2014 guardrail "${ye.rule}"`:""} (${ye.reason})`)}Z.ok||(b(""),w(Z.message??(Z.roles&&!Z.roles.ok?"one or more declared roles cannot be created.":"a guardrail refuses one or more declared writes \u2014 an admin must allow them, or the app must stop declaring them.")))}b(""),b(h.dim("nothing was applied \u2014 this is a preflight. `turbobase apps deploy` runs the same checks and enforces them."))}),l.command("promote").description("Make a preview the live version at /a/<slug>. Promotes the exact reviewed bytes \u2014 no rebuild.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to promote (from `apps preview list`).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,m,v)=>{let{baseUrl:x,token:S}=await H(v.baseUrl),g=await J(`promoting ${m}`,()=>Y(x,S,u,"promote",{previewId:m}));Ie()?b(Gt("Promoted",[`${h.bold(u)} ${h.green(`v${g.version??"?"}`)} ${h.dim(g.url??`/a/${u}`)}`])):b(`promoted ${u} \u2192 v${g.version??"?"} is now live at ${g.url??`/a/${u}`}.`);let T=fp(g);Ce("applied",T.verdicts,T.retired),Ft({labels:g.labels?{applied:!0,verdicts:g.labels}:null}),await Ht(g)});let d=l.command("preview").description("Inspect and manage an app's open previews.");d.command("list").description("List an app's open previews (newest first).").argument("<app>","App slug or id.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a line per preview.").action(async(u,m)=>{let{baseUrl:v,token:x}=await H(m.baseUrl),S=await F(v,x,u);if(m.json)return b(JSON.stringify(S.previews,null,2));if(S.previews.length===0){b(`no open previews for ${u}.`);return}for(let g of S.previews){let T=g.label?` ${g.label}`:"",E=g.expiresAt?new Date(g.expiresAt).toLocaleDateString():"?";b(`v${g.version} ${g.previewId}${T} ${g.url} (expires ${E})`)}}),d.command("discard").description("Close a preview. The URL stops resolving; the version stays in deploy history.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to discard.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,m,v)=>{let{baseUrl:x,token:S}=await H(v.baseUrl);await J(`discarding ${m}`,()=>Y(x,S,u,"discard",{previewId:m})),b(`discarded ${m}.`)}),l.command("create").description("Create a new hosted app (a bare app row) so a build can be shipped to it.").argument("<slug>","URL slug the app is served under: /a/<slug>.").option("--name <name>","Display name (defaults to the slug).").option("--description <text>","Optional description.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,m)=>{let{baseUrl:v,token:x}=await H(m.baseUrl),S=await J(`creating ${u}`,()=>f(v,x,{slug:u,name:m.name,description:m.description})),g=S.slug??u;Ie()?b(Gt("Created",[`${h.bold(g)} ${h.dim(S.url??`/a/${g}`)}`])):b(`created ${g} (${S.url??`/a/${g}`}).`),b(`next: turbobase apps push ${g} . # store the source`),b(` turbobase apps deploy ${g} # build + go live`)});let p=Do(fetch);async function f(u,m,v,x={}){let S=`${u.replace(/\/+$/,"")}/v1/apps`,g;try{g=await p(S,{method:"POST",headers:{Authorization:`Bearer ${m}`,"content-type":"application/json"},body:JSON.stringify({slug:v.slug,name:v.name??v.slug,description:v.description})})}catch(T){w(`create request failed: ${T instanceof Error?T.message:String(T)}`)}if(g.status===401&&w("create unauthorized (401) \u2014 re-run `turbobase auth login`."),g.status===403&&w("create forbidden (403) \u2014 the PAT is not for an admin."),g.status===409){if(x.tolerateExisting)return{slug:v.slug,existed:!0};w(`an app with slug "${v.slug}" already exists.`)}return g.ok||w(`create failed: HTTP ${g.status} ${(await g.text().catch(()=>"")).slice(0,200)}`),await g.json().catch(()=>({}))}async function _(u,m,v){let x=`${u.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(v)}/pull`,S;try{S=await p(x,{headers:{Authorization:`Bearer ${m}`}})}catch(g){w(`pull request failed: ${g instanceof Error?g.message:String(g)}`)}return S.status===401&&w("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),S.status===403&&w("pull forbidden (403) \u2014 the PAT is not for an admin."),S.status===404&&w(`no generated source for "${v}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),S.ok||w(`pull failed: HTTP ${S.status} ${(await S.text().catch(()=>"")).slice(0,200)}`),await S.json()}async function y(u,m,v){let x=se(u),S=0;for(let[g,T]of Object.entries(m)){let E=se(x,g);E!==x&&!E.startsWith(x+Hd)&&w(`refusing to write outside ${x}: ${g}`),v||await ae.stat(E).then(()=>!0).catch(()=>!1)&&w(`${E} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await ae.mkdir(zt(E),{recursive:!0}),await ae.writeFile(E,T,"utf8"),S+=1}return S}function k(u){let m=u.indexOf(","),v=u.startsWith("data:")?m>=0?u.slice(m+1):"":u;if(!v)return null;try{let x=Buffer.from(v,"base64");return x.length>0?new Uint8Array(x):null}catch{return null}}async function R(u,m,v){let x=se(u),S=async(T,E)=>{let A=se(x,T);A!==x&&!A.startsWith(x+Hd)&&w(`refusing to write outside ${x}: ${T}`),v||await ae.stat(A).then(()=>!0).catch(()=>!1)&&w(`${A} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await ae.mkdir(zt(A),{recursive:!0}),await ae.writeFile(A,E)},g=`# ${m.title||"App change request"}
3825
3839
 
3826
- > Widget proposal \`${h.proposalId}\` \u2014 build this change, then ship it with
3827
- > \`turbobase apps deploy ${h.appSlug}\`. The deploy stamps this proposal complete.
3840
+ > Widget proposal \`${m.proposalId}\` \u2014 build this change, then ship it with
3841
+ > \`turbobase apps deploy ${m.appSlug}\`. The deploy stamps this proposal complete.
3828
3842
 
3829
- ${h.bodyMarkdown||"_No description provided._"}
3843
+ ${m.bodyMarkdown||"_No description provided._"}
3830
3844
 
3831
3845
  ## Screen context
3832
3846
 
3833
- `+(h.screenshot?"A screenshot of the screen this request was filed from is saved beside this file as `proposal-screenshot.png`.\n":`No screenshot was captured with this request.
3834
- `);if(await S("PROPOSAL.md",g),h.screenshot){let T=k(h.screenshot);T&&await S("proposal-screenshot.png",T)}await S(et(".turbobase","proposal.json"),`${JSON.stringify({proposalId:h.proposalId},null,2)}
3835
- `)}async function $(u){try{let h=await ae.readFile(et(u,".turbobase","proposal.json"),"utf8"),v=JSON.parse(h);return typeof v.proposalId=="string"&&v.proposalId?v.proposalId:void 0}catch{return}}async function P(u,h,v,x,S,g){let T=new q({baseUrl:u,token:h});try{return await T.appsPush(v,x,{note:S,proposalId:g})}catch(E){if(E instanceof Q){let A=E.body;if(E.status===401&&w("push unauthorized (401) \u2014 re-run `turbobase auth login`."),E.status===403&&A?.error==="admin_required"&&w("push forbidden (403) \u2014 the PAT is not for an admin."),E.status===403&&V(E,"extensions:deploy","push app source"),E.status===404&&w(`no app "${v}" on this instance \u2014 create it with \`turbobase apps create ${v}\`.`),E.status===413&&(A?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&w("push rejected: the request body exceeded the instance limit."),w(`push rejected: ${A?.error??"too large"} (limit ${A?.limit??"?"}).`)),E.status===400){let C=A?.path?` in ${A.path}`:"",O=A?.reason?` (${A.reason})`:"";w(`push rejected: ${A?.error??"bad request"}${O}${C}.`)}}w(`push failed: ${E instanceof Error?E.message:String(E)}`)}}function I(u,h,v){return new Promise((x,S)=>{let g=Kd("npm",u,{cwd:h,stdio:"inherit",...v?{env:{...process.env,...v}}:{}});g.on("error",S),g.on("exit",T=>T===0?x():S(new Error(`npm ${u.join(" ")} exited ${T??"?"}`)))})}async function D(u,h,v,x){let S=`${u.replace(/\/+$/,"")}${v}`,g;try{g=await p(S,{method:x.method,headers:{Authorization:`Bearer ${h}`,...x.body?{"content-type":"application/json"}:{}},...x.body?{body:JSON.stringify(x.body)}:{}})}catch(T){w(`request failed: ${T instanceof Error?T.message:String(T)}`)}if(g.status===401&&w("unauthorized (401) \u2014 re-run `turbobase auth login`."),g.status===403&&w("forbidden (403) \u2014 the PAT is not for an admin."),!g.ok){let T=await g.text().catch(()=>""),E=T.slice(0,300);try{let A=JSON.parse(T);E=A.message??A.error??E}catch{}w(`failed: HTTP ${g.status} ${E}`)}return await g.json().catch(()=>({}))}async function Y(u,h,v,x,S){return await D(u,h,`/v1/apps/${encodeURIComponent(v)}/preview/${x}`,{method:"POST",body:S})}async function F(u,h,v){return{previews:(await D(u,h,`/v1/apps/${encodeURIComponent(v)}/previews`,{method:"GET"})).previews??[]}}async function Oe(u,h,v,x,S,g,T,E){let A;try{A=await J(`zipping ${x}`,()=>Wu(x))}catch(N){w(`could not zip ${x}: ${N instanceof Error?N.message:String(N)}`)}A.fileCount===0&&w(`${x} is empty \u2014 the build produced nothing.`),A.buffer.byteLength>Oa&&w(`${x} zips to ${jb(A.buffer.byteLength)} \u2014 over the ${jb(Oa)} deploy limit. Check the build output for node_modules, source maps or media that should not ship.`);let C={Authorization:`Bearer ${h}`,"Content-Type":"application/zip"};S&&(C["x-app-entry"]=S),g&&(C["x-proposal-id"]=g),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)),E.replacePreviewId&&(C["x-app-preview-replace"]=E.replacePreviewId));let O=`${u.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(v)}/deploy`,G;try{G=await J(`deploying ${v} (${A.fileCount} file${A.fileCount===1?"":"s"})`,()=>p(O,{method:"POST",headers:C,body:new Uint8Array(A.buffer)}))}catch(N){w(`deploy request failed: ${N instanceof Error?N.message:String(N)}`)}if(G.status===401&&w("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),G.status===403&&w("deploy forbidden (403) \u2014 the PAT is not for an admin."),G.status===404){let N=await G.text().catch(()=>""),W={};try{W=JSON.parse(N)}catch{}W.error==="no_preview"&&w(`${W.message??`no open preview to replace on ${v}`} \u2014 list them with \`turbobase apps preview list ${v}\`.`),w(`no app "${v}" on ${u} \u2014 create it with \`turbobase apps create ${v}\`.`)}if(!G.ok){let N=await G.text().catch(()=>""),W=N.slice(0,300);try{let he=JSON.parse(N);W=he.message??he.error??W}catch{}w(`deploy failed: HTTP ${G.status} ${W}`)}return await G.json().catch(()=>({}))}function Ce(u,h,v){for(let x of hp({mode:u,verdicts:h,retired:v}))(x.stream==="err"?L:b)(x.text)}function Bt(u){let h=u.roles;h&&Ce(h.applied?"applied":"preview",h.verdicts??[],h.retired)}function Ft(u){let h=u.labels;if(!h||h.verdicts.length===0)return;let v=h.verdicts.filter(S=>S.action!=="noop");if(v.length===0)return;b(""),b(m.bold(h.applied?"labels":"labels (preview \u2014 not applied)"));let x=Math.max(...v.map(S=>S.name.length));for(let S of v){let g=S.name.padEnd(x);if(S.action==="detach")b(` removed ${g} ${m.dim("no longer declared in the manifest")}`);else if(S.action==="create")b(` created ${g} ${m.dim(S.color)}`);else{let T=S.declaredColor?`${S.color} \u2014 declared ${S.declaredColor}, the instance's colour is kept`:S.color;b(` added ${g} ${m.dim(T)}`)}}b(m.dim(h.applied?" labels are launcher navigation only \u2014 they change nothing about who can open this app.":" nothing was changed \u2014 promoting this preview applies them."))}async function Ht(u,h){let v=ap(u,{localDocsModifiedAt:await hn(h)});v&&b(v.level==="warn"?m.yellow(v.message):m.dim(v.message))}async function hn(u){if(!u)return null;let h=null;for(let v of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let x=await ae.stat(et(u,v));(h===null||x.mtimeMs>h)&&(h=x.mtimeMs)}catch{}return h===null?null:new Date(h)}l.command("pull").description("Write an app's generated source tree to disk (from the proposal that generated it).").argument("[app]","App slug or id. Omit when using --proposal (the app is derived from it).").argument("[dir]","Directory to write into (default ./<slug>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--force","Overwrite existing files.").option("--proposal <id>","Pull the app behind a widget proposal + its request context.").action(async(u,h,v)=>{let{baseUrl:x,token:S}=await H(v.baseUrl);if(v.proposal){let A=new q({baseUrl:x,token:S}),C;try{C=await J(`fetching proposal ${v.proposal}`,()=>A.appPullContext(v.proposal))}catch(he){V(he,"extensions:deploy","pull proposal"),he instanceof Q&&he.status===404&&w(`no widget proposal "${v.proposal}" on ${x}.`),w(`could not fetch proposal ${v.proposal}: ${he instanceof Error?he.message:String(he)}`)}let O=await J(`pulling ${C.appSlug}`,()=>_(x,S,C.appSlug)),G=h??u,N=se(process.cwd(),G??C.appSlug);await ae.mkdir(N,{recursive:!0});let W=await y(N,O.files,!!v.force);await R(N,C,!!v.force),b(`pulled ${W} file${W===1?"":"s"} \u2192 ${N} (rev ${O.rev}), linked to proposal ${C.proposalId}.`),b(`next: cd ${Ni(process.cwd(),N)||"."} && turbobase apps deploy ${C.appSlug}`);return}u||w("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let g=await J(`pulling ${u}`,()=>_(x,S,u)),T=se(process.cwd(),h??g.slug??u);await ae.mkdir(T,{recursive:!0});let E=await y(T,g.files,!!v.force);b(`pulled ${E} file${E===1?"":"s"} \u2192 ${T} (rev ${g.rev}).`),b(`next: cd ${Ni(process.cwd(),T)||"."} && turbobase apps deploy ${g.slug}`)}),l.command("init").description("Scaffold a new app project locally, wired to your instance and to Claude Code.").argument("<app>","App slug \u2014 also the /a/<slug> mount path the build is pinned to.").argument("[dir]","Directory to scaffold into (default ./<app>).").option("--title <text>","Display title used in index.html and the starter component.").option("--base-url <url>","Instance to wire the project to (defaults to the active instance).").option("--no-claude","Skip the Claude Code wiring (CLAUDE.md, .mcp.json, .claude/).").option("--force","Overwrite existing files.").action(async(u,h,v)=>{let x=se(process.cwd(),h??u),S=await mt(v.baseUrl).catch(()=>null),{scaffoldAppFiles:g,starterApp:T}=await Promise.resolve().then(()=>(rh(),th)),E=v.title??u,A=g({slug:u,title:E,appTsx:T(E),instanceOrigin:S?.baseUrl});await ae.mkdir(x,{recursive:!0});let C=await y(x,A,!!v.force);if(b(`scaffolded ${C} file${C===1?"":"s"} \u2192 ${x}`),v.claude!==!1){let G=ba({baseUrl:S?.baseUrl,token:S?.token,appSlug:u}),N=0;for(let W of G){let he=await Lb(et(x,W.path),W);(he==="wrote"||he==="merged")&&(N+=1)}b(`wired Claude Code: ${N} file${N===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),S||L("not signed in \u2014 .mcp.json and the dev proxy carry placeholders. Run `turbobase auth login`, then `turbobase apps init` again (existing files are kept).")}let O=Ni(process.cwd(),x)||".";b(`next: cd ${O} && npm install && npm run dev`),b(` turbobase apps create ${u}`),b(` turbobase apps push ${u} .`),b(` turbobase apps deploy ${u} .`)}),l.command("list").description("List the hosted apps on your instance.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async u=>{let{baseUrl:h,token:v}=await H(u.baseUrl),x=new q({baseUrl:h,token:v}),S;try{S=await x.appsList()}catch(g){V(g,"extensions:deploy","list apps"),w(`list apps failed: ${g instanceof Error?g.message:String(g)}`)}if(u.json)return b(JSON.stringify(S,null,2));if(S.length===0)return b("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");b(ft(S.map(g=>[g.slug,g.name,g.deployed?"yes":"no",g.sourceRev===null?"\u2014":`rev ${g.sourceRev}`,g.audience]),{head:["SLUG","NAME","LIVE","SOURCE","AUDIENCE"]}))}),l.command("push").description("Record the local source tree as the app's newest source revision (does NOT deploy).").argument("<app>","App slug or id.").argument("[dir]","Source directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--note <text>","Short note stored with the revision.").option("--proposal <id>","Widget proposal this rev works (defaults to .turbobase/proposal.json).").action(async(u,h,v)=>{let x=se(process.cwd(),h??".");await ae.stat(x).then(Z=>Z.isDirectory()).catch(()=>!1)||w(`${x} is not a directory.`);let{baseUrl:g,token:T}=await H(v.baseUrl),E=v.proposal??await $(x),{files:A,skipped:C,secrets:O,unstorable:G}=await vm(x),N=Object.keys(A).length;if(N===0&&w(`no source files found under ${x} (build output and node_modules are skipped).`),G.length>0){for(let Z of G)L(`${Z} contains a NUL byte (U+0000), which cannot be stored.`);w(`push aborted: ${G.length} ${G.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let Z of C)L(m.dim(`skipped binary file ${Z}`));for(let Z of O)L(m.dim(`skipped ${Z} (holds credentials \u2014 never pushed)`));let W=await J(`pushing ${N} file${N===1?"":"s"}`,()=>P(g,T,u,A,v.note,E));b(`pushed ${W.files} file${W.files===1?"":"s"} \u2192 ${W.slug} rev ${W.rev} (source only, nothing deployed).`);let he=await Pn(new q({baseUrl:g,token:T}),W.slug);he&&he.entriesAdded>0&&b(`${he.entriesAdded} new finding(s) queued \u2014 run \`turbobase skills push\` / \`turbobase kb push\` to act on them.`),b(`next: turbobase apps deploy ${W.slug}`)}),o.command("plan").description("Diff this project (hooks/, conduits/, turbobase/) against a target env (no writes).").option("--from <env>","Source env the bundle was authored against (advisory).").option("--to <env>","Target env to diff against (sandbox|prod).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async u=>{let h=await zd(),{baseUrl:v,token:x}=await H(u.baseUrl),S=new q({baseUrl:v,token:x}),g;try{g=await J(`planning against ${u.to??v}`,()=>S.configPlan(h))}catch(T){w(`plan failed: ${T instanceof Error?T.message:String(T)}`)}EA(g,u.to??v)}),o.command("promote").description("Promote the bundle from one env to another behind a confirm-slug gate (fail-closed).").requiredOption("--from <env>","Source env (e.g. sandbox).").requiredOption("--to <env>","Target env (e.g. prod).").requiredOption("--confirm <slug>","Type the EXACT target instance slug to confirm (fail-closed).").option("--base-url <url>","Target instance base URL (defaults to the active instance).").option("--prune","Also REMOVE anything on the target this project no longer declares. Off by default.").action(async u=>{let h=await zd(),{baseUrl:v,token:x}=await H(u.baseUrl),S=h.tenant??PA(v),g=xp(u.confirm,S);g.ok||w(`promote refused (fail-closed): ${g.reason}`);let T=new q({baseUrl:v,token:x});try{let E=await J(`promoting ${u.from} \u2192 ${u.to} (${S})`,()=>T.configApply(h,{prune:u.prune}));if(Ie()){let C=[`${m.bold(`${u.from} \u2192 ${u.to}`)} ${m.dim(S??"")}`,`${Vt.add(String(E.applied.add))} ${Vt.change(String(E.applied.change))} ${Vt.destroy(String(E.applied.destroy))}`];E.backfillsQueued.length&&C.push(m.dim(`${E.backfillsQueued.length} backfill(s) queued`)),b(Gt("Promoted",C))}else b(`promoted ${u.from} \u2192 ${u.to} (${S}): +${E.applied.add} ~${E.applied.change} -${E.applied.destroy}`+(E.backfillsQueued.length?` (${E.backfillsQueued.length} backfill(s) queued)`:""));let A=E.skippedDestroys??[];if(A.length>0){L(`${A.length} resource(s) on ${u.to} are not declared by this project \u2014 NOT removed:`);for(let C of A)L(` ${C.kind} ${C.id}`);L("Re-run with --prune to remove them, or add them to this repo.")}}catch(E){E instanceof Q&&E.status===403&&w("promote forbidden (403) \u2014 the stored PAT is not for an admin."),w(`promote failed: ${E instanceof Error?E.message:String(E)}`)}}),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(u,h)=>{let v=qd(h.reporter),x=se(process.cwd(),u),S=await Sn(x),g=Yu(S);v?b(Vo(kA(u,g),v)):b(Xu(u,g,{warn:m.yellow,ok:m.green,dim:m.dim})),h.ci&&g.warnings.length>0&&process.exit(1)}),o.command("replay").argument("<file>","The conduit file to replay").description("Dry-run a conduit through dispatch\u2192transform\u2192apply (offline against a fixture).").option("--fixture <file>","JSON conduit-trigger fixture to replay against.").option("--against <target>","Replay against a running sandbox (online; deferred without a local DB).").option("--trace","Emit the per-stage trace (guards, atlas, apply-branch, bindings).").option("--reporter <fmt>","Emit machine-readable output: junit | json (one case per stage).").action(async(u,h)=>{let v=qd(h.reporter),x=await Bu(se(process.cwd(),u));if(h.against){h.against!=="sandbox"&&w(`unknown --against target '${h.against}' (only 'sandbox' is supported).`);try{await qu(da(x))}catch(T){w(T instanceof Error?T.message:String(T))}return}h.fixture||w("replay needs a --fixture <file> (offline) or --against sandbox (online).");let S;try{S=await zu(se(process.cwd(),h.fixture))}catch(T){w(`could not read fixture ${h.fixture}: ${T instanceof Error?T.message:String(T)}`)}let g=await Mu(x,S,h.fixture,{resolveDir:zt(se(process.cwd(),u))});if(v){let T=TA(g);b(Vo(T,v)),Oi(T.cases.some(E=>E.status==="failed")?1:0)}b(Fu(g,!!h.trace)),Oi(g.error?1:0)}),o.command("binding").description("List conduit source bindings (--status divergent) or re-enqueue one (--retry <id>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <status>","Filter by write_status (ok|pending|blocked|divergent|muted).").option("--retry <id>","Re-enqueue the fan-out write for this binding id (admin-only).").option("--limit <n>","Max rows listed").action(async u=>{let{baseUrl:h,token:v}=await H(u.baseUrl),x=new q({baseUrl:h,token:v});try{await op(x,{status:u.status,retry:u.retry,limit:u.limit?Number(u.limit):void 0,sink:b})}catch(S){S instanceof Q&&S.status===403&&w("forbidden (403) \u2014 binding --retry requires an admin PAT."),S instanceof Q&&S.status===409&&w("binding is not retryable (only divergent/blocked bindings can be retried)."),w(`ext binding failed: ${S instanceof Error?S.message:String(S)}`)}});let dr=o.command("proposals").description("Review the hook proposals waiting on a decision \u2014 list, promote, retract, reject.");dr.command("list").description("List hook proposals and the evidence behind each (defaults to the pending queue).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <list>","proposed | active | rejected (comma-joined). Default: proposed.").option("--provenance <list>","mechanic | operator | learning | code-baseline (comma-joined).").option("--record-type <type>","Only proposals for this record type.").option("--source <system>","Only proposals for this adapter id.").option("--limit <n>","Max rows listed (default 200).").option("--json","Emit raw JSON instead of a table.").action(async u=>{await sm(u)}),dr.command("promote [ids...]").description("Arm hook proposals so the loader enforces them \u2014 by id, or by filter with --auto.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--auto","Select by filter instead of by id. Prints the plan; writes nothing without --apply.").option("--apply","With --auto: actually arm the planned proposals.").option("--provenance <list>","Restrict --auto to these provenances (mechanic | operator | code-baseline).").option("--record-type <type>","Restrict --auto to this record type.").option("--source <system>","Restrict --auto to this adapter id.").option("--limit <n>","Cap how many proposals --auto considers.").option("--all","Required to --apply an UNFILTERED plan (arm the whole queue).").option("-y, --yes","Skip the confirmation prompt (required on a non-interactive terminal).").option("--json","Emit the plan as JSON.").action(async(u,h)=>{await im(u??[],h)}),dr.command("retract <ids...>").description("Send armed hooks back to proposed \u2014 inert immediately, source kept, re-promotable.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{await am(u,h)}),dr.command("reject <ids...>").description("Decline proposals for good \u2014 the id becomes the denylist. Prefer `retract` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--reason <text>","Why \u2014 recorded on the row and in the audit log.").action(async(u,h)=>{await lm(u,h)}),o.command("disable <ids...>").description("Take armed extensions out of service \u2014 inert on the next reload, definition kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(u,h)=>{await cm(u,h)}),o.command("enable <ids...>").description("Put disabled extensions back into service.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(u,h)=>{await dm(u,h)}),o.command("remove <ids...>").description("Delete extension definitions. Run history and what they already wrote are kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(u,h)=>{await um(u,h)}),o.command("install").argument("<spec>","Extension name, optionally name@version").description("Install an extension from the marketplace into your instance's extension store.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--connection <id>",'Bind this connection id (required when the extension declares a { type:"connection" } input).').action(async(u,h)=>{let v=u.lastIndexOf("@"),x=v>0?u.slice(0,v):u,S=v>0?u.slice(v+1):void 0,g=sa();g||w(`marketplace not configured \u2014 set ${Cr} and ${Uo}.
3836
- Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let T=ia(g.registryUrl);T&&w(T);let{baseUrl:E,token:A}=await H(h.baseUrl),C=new wn(g),O;try{O=await J(`fetching ${u}`,()=>C.fetchBundle(x,S))}catch(Z){w(`marketplace fetch failed for ${u}: ${Z instanceof Error?Z.message:String(Z)}`)}let G=Eo(O.manifest),N=null;if(G.length>0){if(!h.connection){let Z=G.map(ye=>ye.source_system).join(", ");w(`${O.name}@${O.version} declares a connection input (source: ${Z}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}N=h.connection}let W=xA(O.bundle,O.name,O.kind),he=new q({baseUrl:E,token:A});try{let Z=await J(`installing ${O.name}@${O.version}`,()=>he.deploy({...W,provenance:"marketplace",...N?{connectionId:N}:{}}));b(`installed ${O.name}@${O.version} \u2192 ${Z.id} (status=${Z.status}, ${Z.outcome})`+(N?` bound to connection ${N}.`:"."))}catch(Z){Z instanceof Q&&Z.status===403&&w("install forbidden (403) \u2014 the stored PAT is not for an admin."),w(`install failed: ${Z instanceof Error?Z.message:String(Z)}`)}}),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(u,h)=>{let v=sa();v||w(`marketplace not configured \u2014 set ${Cr} and ${Uo}.
3837
- Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let x=ia(v.registryUrl);x&&w(x);let S=se(process.cwd(),u),g=await Sn(S),T=/\bdefineConduit\s*[<(]/.test(g)?"conduit":"hook",E={};if(h.manifest){let O=se(process.cwd(),h.manifest),G;try{G=await ae.readFile(O,"utf8")}catch{w(`manifest not found at ${h.manifest}.`)}let N;try{N=JSON.parse(G)}catch{w(`manifest is not valid JSON: ${h.manifest}.`)}(typeof N!="object"||N===null||Array.isArray(N))&&w("manifest must be a JSON object."),E=N}try{qi(E,g)}catch(O){O instanceof Kt&&w(O.message),w(`manifest validation failed: ${O instanceof Error?O.message:String(O)}`)}let A=new wn(v);try{await J(`publishing ${h.name}@${h.pkgVersion}`,()=>A.publish({name:h.name,version:h.pkgVersion,kind:T,bundle:g,manifest:E}))}catch(O){O instanceof Q&&O.status===403&&w("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),O instanceof Q&&O.status===409&&w(`version already published \u2014 ${h.name}@${h.pkgVersion} exists. Bump the version.`),w(`publish failed: ${O instanceof Error?O.message:String(O)}`)}let C=Eo(E);b(`published ${h.name}@${h.pkgVersion} (kind=${T}) to the marketplace.`),C.length>0&&b(` declares ${C.length} connection input(s): ${C.map(O=>O.source_system).join(", ")} \u2014 bound at install.`)}),n.command("init").description("Scaffold a Claude-Code extension project in the current dir.").option("--base-url <url>","Instance to wire .mcp.json to (defaults to the active instance).").action(async u=>{let h=await mt(u.baseUrl).catch(()=>null),v=ba({baseUrl:h?.baseUrl,token:h?.token}),x=0,S=0,g=0;for(let T of v){let E=se(process.cwd(),T.path),A=await Lb(E,T);A==="wrote"?(x+=1,b(` wrote ${T.path}`)):A==="merged"?(g+=1,b(` merged ${T.path} (added the .mcp.json rule)`)):(S+=1,b(` skipped ${T.path} (exists)`))}b(`
3838
- project init: ${x} written, ${g} merged, ${S} skipped.`)}),n.command("ci").description(`Write the reusable release-deploy GitHub Action to ${ya} (non-destructive).`).action(async()=>{let u=gp(),h=0,v=0;for(let x of u){let S=se(process.cwd(),x.path);await Pr(S,x.content,x.executable)==="wrote"?(h+=1,b(` wrote ${x.path}`)):(v+=1,b(` skipped ${x.path} (exists)`))}b(`
3839
- project ci: ${h} written, ${v} skipped.`),h>0&&(b(`
3840
- Next: mint a releases:write PAT in your Turbobase app (Settings \u203A Access tokens),`),b("store it as the GitHub Actions secret TURBOBASE_RELEASE_PAT, and set the repo"),b("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 u=>{let{baseUrl:h,token:v}=await H(u.baseUrl),x=new q({baseUrl:h,token:v}),S;try{S=await x.catalogRecords()}catch(C){C instanceof Q&&(C.status===401||C.status===403)&&w("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),w(`catalog fetch failed: ${C instanceof Error?C.message:String(C)}`)}if(S.length===0){b("no records in the instance catalog \u2014 nothing to generate.");return}let g=se(process.cwd(),u.out),T=Ku(S,{event:u.event}),E=0,A=0;for(let{recordType:C,fixture:O}of T){let G=et(g,`${C}.json`),N=`${JSON.stringify(O,null,2)}
3847
+ `+(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.
3848
+ `);if(await S("PROPOSAL.md",g),m.screenshot){let T=k(m.screenshot);T&&await S("proposal-screenshot.png",T)}await S(et(".turbobase","proposal.json"),`${JSON.stringify({proposalId:m.proposalId},null,2)}
3849
+ `)}async function $(u){try{let m=await ae.readFile(et(u,".turbobase","proposal.json"),"utf8"),v=JSON.parse(m);return typeof v.proposalId=="string"&&v.proposalId?v.proposalId:void 0}catch{return}}async function P(u,m,v,x,S,g){let T=new q({baseUrl:u,token:m});try{return await T.appsPush(v,x,{note:S,proposalId:g})}catch(E){if(E instanceof Q){let A=E.body;if(E.status===401&&w("push unauthorized (401) \u2014 re-run `turbobase auth login`."),E.status===403&&A?.error==="admin_required"&&w("push forbidden (403) \u2014 the PAT is not for an admin."),E.status===403&&V(E,"extensions:deploy","push app source"),E.status===404&&w(`no app "${v}" on this instance \u2014 create it with \`turbobase apps create ${v}\`.`),E.status===413&&(A?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&w("push rejected: the request body exceeded the instance limit."),w(`push rejected: ${A?.error??"too large"} (limit ${A?.limit??"?"}).`)),E.status===400){let C=A?.path?` in ${A.path}`:"",O=A?.reason?` (${A.reason})`:"";w(`push rejected: ${A?.error??"bad request"}${O}${C}.`)}}w(`push failed: ${E instanceof Error?E.message:String(E)}`)}}function I(u,m,v){return new Promise((x,S)=>{let g=Kd("npm",u,{cwd:m,stdio:"inherit",...v?{env:{...process.env,...v}}:{}});g.on("error",S),g.on("exit",T=>T===0?x():S(new Error(`npm ${u.join(" ")} exited ${T??"?"}`)))})}async function D(u,m,v,x){let S=`${u.replace(/\/+$/,"")}${v}`,g;try{g=await p(S,{method:x.method,headers:{Authorization:`Bearer ${m}`,...x.body?{"content-type":"application/json"}:{}},...x.body?{body:JSON.stringify(x.body)}:{}})}catch(T){w(`request failed: ${T instanceof Error?T.message:String(T)}`)}if(g.status===401&&w("unauthorized (401) \u2014 re-run `turbobase auth login`."),g.status===403&&w("forbidden (403) \u2014 the PAT is not for an admin."),!g.ok){let T=await g.text().catch(()=>""),E=T.slice(0,300);try{let A=JSON.parse(T);E=A.message??A.error??E}catch{}w(`failed: HTTP ${g.status} ${E}`)}return await g.json().catch(()=>({}))}async function Y(u,m,v,x,S){return await D(u,m,`/v1/apps/${encodeURIComponent(v)}/preview/${x}`,{method:"POST",body:S})}async function F(u,m,v){return{previews:(await D(u,m,`/v1/apps/${encodeURIComponent(v)}/previews`,{method:"GET"})).previews??[]}}async function Oe(u,m,v,x,S,g,T,E){let A;try{A=await J(`zipping ${x}`,()=>Wu(x))}catch(N){w(`could not zip ${x}: ${N instanceof Error?N.message:String(N)}`)}A.fileCount===0&&w(`${x} is empty \u2014 the build produced nothing.`),A.buffer.byteLength>Oa&&w(`${x} zips to ${jb(A.buffer.byteLength)} \u2014 over the ${jb(Oa)} deploy limit. Check the build output for node_modules, source maps or media that should not ship.`);let C={Authorization:`Bearer ${m}`,"Content-Type":"application/zip"};S&&(C["x-app-entry"]=S),g&&(C["x-proposal-id"]=g),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)),E.replacePreviewId&&(C["x-app-preview-replace"]=E.replacePreviewId));let O=`${u.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(v)}/deploy`,G;try{G=await J(`deploying ${v} (${A.fileCount} file${A.fileCount===1?"":"s"})`,()=>p(O,{method:"POST",headers:C,body:new Uint8Array(A.buffer)}))}catch(N){w(`deploy request failed: ${N instanceof Error?N.message:String(N)}`)}if(G.status===401&&w("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),G.status===403&&w("deploy forbidden (403) \u2014 the PAT is not for an admin."),G.status===404){let N=await G.text().catch(()=>""),W={};try{W=JSON.parse(N)}catch{}W.error==="no_preview"&&w(`${W.message??`no open preview to replace on ${v}`} \u2014 list them with \`turbobase apps preview list ${v}\`.`),w(`no app "${v}" on ${u} \u2014 create it with \`turbobase apps create ${v}\`.`)}if(!G.ok){let N=await G.text().catch(()=>""),W=N.slice(0,300);try{let me=JSON.parse(N);W=me.message??me.error??W}catch{}w(`deploy failed: HTTP ${G.status} ${W}`)}return await G.json().catch(()=>({}))}function Ce(u,m,v){for(let x of mp({mode:u,verdicts:m,retired:v}))(x.stream==="err"?L:b)(x.text)}function Bt(u){let m=u.roles;m&&Ce(m.applied?"applied":"preview",m.verdicts??[],m.retired)}function Ft(u){let m=u.labels;if(!m||m.verdicts.length===0)return;let v=m.verdicts.filter(S=>S.action!=="noop");if(v.length===0)return;b(""),b(h.bold(m.applied?"labels":"labels (preview \u2014 not applied)"));let x=Math.max(...v.map(S=>S.name.length));for(let S of v){let g=S.name.padEnd(x);if(S.action==="detach")b(` removed ${g} ${h.dim("no longer declared in the manifest")}`);else if(S.action==="create")b(` created ${g} ${h.dim(S.color)}`);else{let T=S.declaredColor?`${S.color} \u2014 declared ${S.declaredColor}, the instance's colour is kept`:S.color;b(` added ${g} ${h.dim(T)}`)}}b(h.dim(m.applied?" labels are launcher navigation only \u2014 they change nothing about who can open this app.":" nothing was changed \u2014 promoting this preview applies them."))}async function Ht(u,m){let v=ap(u,{localDocsModifiedAt:await mn(m)});v&&b(v.level==="warn"?h.yellow(v.message):h.dim(v.message))}async function mn(u){if(!u)return null;let m=null;for(let v of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let x=await ae.stat(et(u,v));(m===null||x.mtimeMs>m)&&(m=x.mtimeMs)}catch{}return m===null?null:new Date(m)}l.command("pull").description("Write an app's generated source tree to disk (from the proposal that generated it).").argument("[app]","App slug or id. Omit when using --proposal (the app is derived from it).").argument("[dir]","Directory to write into (default ./<slug>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--force","Overwrite existing files.").option("--proposal <id>","Pull the app behind a widget proposal + its request context.").action(async(u,m,v)=>{let{baseUrl:x,token:S}=await H(v.baseUrl);if(v.proposal){let A=new q({baseUrl:x,token:S}),C;try{C=await J(`fetching proposal ${v.proposal}`,()=>A.appPullContext(v.proposal))}catch(me){V(me,"extensions:deploy","pull proposal"),me instanceof Q&&me.status===404&&w(`no widget proposal "${v.proposal}" on ${x}.`),w(`could not fetch proposal ${v.proposal}: ${me instanceof Error?me.message:String(me)}`)}let O=await J(`pulling ${C.appSlug}`,()=>_(x,S,C.appSlug)),G=m??u,N=se(process.cwd(),G??C.appSlug);await ae.mkdir(N,{recursive:!0});let W=await y(N,O.files,!!v.force);await R(N,C,!!v.force),b(`pulled ${W} file${W===1?"":"s"} \u2192 ${N} (rev ${O.rev}), linked to proposal ${C.proposalId}.`),b(`next: cd ${Ni(process.cwd(),N)||"."} && turbobase apps deploy ${C.appSlug}`);return}u||w("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let g=await J(`pulling ${u}`,()=>_(x,S,u)),T=se(process.cwd(),m??g.slug??u);await ae.mkdir(T,{recursive:!0});let E=await y(T,g.files,!!v.force);b(`pulled ${E} file${E===1?"":"s"} \u2192 ${T} (rev ${g.rev}).`),b(`next: cd ${Ni(process.cwd(),T)||"."} && turbobase apps deploy ${g.slug}`)}),l.command("init").description("Scaffold a new app project locally, wired to your instance and to Claude Code.").argument("<app>","App slug \u2014 also the /a/<slug> mount path the build is pinned to.").argument("[dir]","Directory to scaffold into (default ./<app>).").option("--title <text>","Display title used in index.html and the starter component.").option("--base-url <url>","Instance to wire the project to (defaults to the active instance).").option("--no-claude","Skip the Claude Code wiring (CLAUDE.md, .mcp.json, .claude/).").option("--force","Overwrite existing files.").action(async(u,m,v)=>{let x=se(process.cwd(),m??u),S=await ht(v.baseUrl).catch(()=>null),{scaffoldAppFiles:g,starterApp:T}=await Promise.resolve().then(()=>(rm(),tm)),E=v.title??u,A=g({slug:u,title:E,appTsx:T(E),instanceOrigin:S?.baseUrl});await ae.mkdir(x,{recursive:!0});let C=await y(x,A,!!v.force);if(b(`scaffolded ${C} file${C===1?"":"s"} \u2192 ${x}`),v.claude!==!1){let G=ba({baseUrl:S?.baseUrl,token:S?.token,appSlug:u}),N=0;for(let W of G){let me=await Lb(et(x,W.path),W);(me==="wrote"||me==="merged")&&(N+=1)}b(`wired Claude Code: ${N} file${N===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),S||L("not signed in \u2014 .mcp.json and the dev proxy carry placeholders. Run `turbobase auth login`, then `turbobase apps init` again (existing files are kept).")}let O=Ni(process.cwd(),x)||".";b(`next: cd ${O} && npm install && npm run dev`),b(` turbobase apps create ${u}`),b(` turbobase apps push ${u} .`),b(` turbobase apps deploy ${u} .`)}),l.command("list").description("List the hosted apps on your instance.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async u=>{let{baseUrl:m,token:v}=await H(u.baseUrl),x=new q({baseUrl:m,token:v}),S;try{S=await x.appsList()}catch(g){V(g,"extensions:deploy","list apps"),w(`list apps failed: ${g instanceof Error?g.message:String(g)}`)}if(u.json)return b(JSON.stringify(S,null,2));if(S.length===0)return b("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");b(ft(S.map(g=>[g.slug,g.name,g.deployed?"yes":"no",g.sourceRev===null?"\u2014":`rev ${g.sourceRev}`,g.audience]),{head:["SLUG","NAME","LIVE","SOURCE","AUDIENCE"]}))}),l.command("push").description("Record the local source tree as the app's newest source revision (does NOT deploy).").argument("<app>","App slug or id.").argument("[dir]","Source directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--note <text>","Short note stored with the revision.").option("--proposal <id>","Widget proposal this rev works (defaults to .turbobase/proposal.json).").action(async(u,m,v)=>{let x=se(process.cwd(),m??".");await ae.stat(x).then(Z=>Z.isDirectory()).catch(()=>!1)||w(`${x} is not a directory.`);let{baseUrl:g,token:T}=await H(v.baseUrl),E=v.proposal??await $(x),{files:A,skipped:C,secrets:O,unstorable:G}=await vh(x),N=Object.keys(A).length;if(N===0&&w(`no source files found under ${x} (build output and node_modules are skipped).`),G.length>0){for(let Z of G)L(`${Z} contains a NUL byte (U+0000), which cannot be stored.`);w(`push aborted: ${G.length} ${G.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let Z of C)L(h.dim(`skipped binary file ${Z}`));for(let Z of O)L(h.dim(`skipped ${Z} (holds credentials \u2014 never pushed)`));let W=await J(`pushing ${N} file${N===1?"":"s"}`,()=>P(g,T,u,A,v.note,E));b(`pushed ${W.files} file${W.files===1?"":"s"} \u2192 ${W.slug} rev ${W.rev} (source only, nothing deployed).`);let me=await Pn(new q({baseUrl:g,token:T}),W.slug);me&&me.entriesAdded>0&&b(`${me.entriesAdded} new finding(s) queued \u2014 run \`turbobase skills push\` / \`turbobase kb push\` to act on them.`),b(`next: turbobase apps deploy ${W.slug}`)}),o.command("plan").description("Diff this project (hooks/, conduits/, turbobase/) against a target env (no writes).").option("--from <env>","Source env the bundle was authored against (advisory).").option("--to <env>","Target env to diff against (sandbox|prod).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async u=>{let m=await zd(),{baseUrl:v,token:x}=await H(u.baseUrl),S=new q({baseUrl:v,token:x}),g;try{g=await J(`planning against ${u.to??v}`,()=>S.configPlan(m))}catch(T){w(`plan failed: ${T instanceof Error?T.message:String(T)}`)}EA(g,u.to??v)}),o.command("promote").description("Promote the bundle from one env to another behind a confirm-slug gate (fail-closed).").requiredOption("--from <env>","Source env (e.g. sandbox).").requiredOption("--to <env>","Target env (e.g. prod).").requiredOption("--confirm <slug>","Type the EXACT target instance slug to confirm (fail-closed).").option("--base-url <url>","Target instance base URL (defaults to the active instance).").option("--prune","Also REMOVE anything on the target this project no longer declares. Off by default.").action(async u=>{let m=await zd(),{baseUrl:v,token:x}=await H(u.baseUrl),S=m.tenant??PA(v),g=xp(u.confirm,S);g.ok||w(`promote refused (fail-closed): ${g.reason}`);let T=new q({baseUrl:v,token:x});try{let E=await J(`promoting ${u.from} \u2192 ${u.to} (${S})`,()=>T.configApply(m,{prune:u.prune}));if(Ie()){let C=[`${h.bold(`${u.from} \u2192 ${u.to}`)} ${h.dim(S??"")}`,`${Vt.add(String(E.applied.add))} ${Vt.change(String(E.applied.change))} ${Vt.destroy(String(E.applied.destroy))}`];E.backfillsQueued.length&&C.push(h.dim(`${E.backfillsQueued.length} backfill(s) queued`)),b(Gt("Promoted",C))}else b(`promoted ${u.from} \u2192 ${u.to} (${S}): +${E.applied.add} ~${E.applied.change} -${E.applied.destroy}`+(E.backfillsQueued.length?` (${E.backfillsQueued.length} backfill(s) queued)`:""));let A=E.skippedDestroys??[];if(A.length>0){L(`${A.length} resource(s) on ${u.to} are not declared by this project \u2014 NOT removed:`);for(let C of A)L(` ${C.kind} ${C.id}`);L("Re-run with --prune to remove them, or add them to this repo.")}}catch(E){E instanceof Q&&E.status===403&&w("promote forbidden (403) \u2014 the stored PAT is not for an admin."),w(`promote failed: ${E instanceof Error?E.message:String(E)}`)}}),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(u,m)=>{let v=qd(m.reporter),x=se(process.cwd(),u),S=await Sn(x),g=Yu(S);v?b(Vo(kA(u,g),v)):b(Xu(u,g,{warn:h.yellow,ok:h.green,dim:h.dim})),m.ci&&g.warnings.length>0&&process.exit(1)}),o.command("replay").argument("<file>","The conduit file to replay").description("Dry-run a conduit through dispatch\u2192transform\u2192apply (offline against a fixture).").option("--fixture <file>","JSON conduit-trigger fixture to replay against.").option("--against <target>","Replay against a running sandbox (online; deferred without a local DB).").option("--trace","Emit the per-stage trace (guards, atlas, apply-branch, bindings).").option("--reporter <fmt>","Emit machine-readable output: junit | json (one case per stage).").action(async(u,m)=>{let v=qd(m.reporter),x=await Bu(se(process.cwd(),u));if(m.against){m.against!=="sandbox"&&w(`unknown --against target '${m.against}' (only 'sandbox' is supported).`);try{await qu(da(x))}catch(T){w(T instanceof Error?T.message:String(T))}return}m.fixture||w("replay needs a --fixture <file> (offline) or --against sandbox (online).");let S;try{S=await zu(se(process.cwd(),m.fixture))}catch(T){w(`could not read fixture ${m.fixture}: ${T instanceof Error?T.message:String(T)}`)}let g=await Mu(x,S,m.fixture,{resolveDir:zt(se(process.cwd(),u))});if(v){let T=TA(g);b(Vo(T,v)),Oi(T.cases.some(E=>E.status==="failed")?1:0)}b(Fu(g,!!m.trace)),Oi(g.error?1:0)}),o.command("binding").description("List conduit source bindings (--status divergent) or re-enqueue one (--retry <id>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <status>","Filter by write_status (ok|pending|blocked|divergent|muted).").option("--retry <id>","Re-enqueue the fan-out write for this binding id (admin-only).").option("--limit <n>","Max rows listed").action(async u=>{let{baseUrl:m,token:v}=await H(u.baseUrl),x=new q({baseUrl:m,token:v});try{await op(x,{status:u.status,retry:u.retry,limit:u.limit?Number(u.limit):void 0,sink:b})}catch(S){S instanceof Q&&S.status===403&&w("forbidden (403) \u2014 binding --retry requires an admin PAT."),S instanceof Q&&S.status===409&&w("binding is not retryable (only divergent/blocked bindings can be retried)."),w(`ext binding failed: ${S instanceof Error?S.message:String(S)}`)}});let dr=o.command("proposals").description("Review the hook proposals waiting on a decision \u2014 list, promote, retract, reject.");dr.command("list").description("List hook proposals and the evidence behind each (defaults to the pending queue).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <list>","proposed | active | rejected (comma-joined). Default: proposed.").option("--provenance <list>","mechanic | operator | learning | code-baseline (comma-joined).").option("--record-type <type>","Only proposals for this record type.").option("--source <system>","Only proposals for this adapter id.").option("--limit <n>","Max rows listed (default 200).").option("--json","Emit raw JSON instead of a table.").action(async u=>{await sh(u)}),dr.command("promote [ids...]").description("Arm hook proposals so the loader enforces them \u2014 by id, or by filter with --auto.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--auto","Select by filter instead of by id. Prints the plan; writes nothing without --apply.").option("--apply","With --auto: actually arm the planned proposals.").option("--provenance <list>","Restrict --auto to these provenances (mechanic | operator | code-baseline).").option("--record-type <type>","Restrict --auto to this record type.").option("--source <system>","Restrict --auto to this adapter id.").option("--limit <n>","Cap how many proposals --auto considers.").option("--all","Required to --apply an UNFILTERED plan (arm the whole queue).").option("-y, --yes","Skip the confirmation prompt (required on a non-interactive terminal).").option("--json","Emit the plan as JSON.").action(async(u,m)=>{await ih(u??[],m)}),dr.command("retract <ids...>").description("Send armed hooks back to proposed \u2014 inert immediately, source kept, re-promotable.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,m)=>{await ah(u,m)}),dr.command("reject <ids...>").description("Decline proposals for good \u2014 the id becomes the denylist. Prefer `retract` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--reason <text>","Why \u2014 recorded on the row and in the audit log.").action(async(u,m)=>{await lh(u,m)}),o.command("disable <ids...>").description("Take armed extensions out of service \u2014 inert on the next reload, definition kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(u,m)=>{await ch(u,m)}),o.command("enable <ids...>").description("Put disabled extensions back into service.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(u,m)=>{await dh(u,m)}),o.command("remove <ids...>").description("Delete extension definitions. Run history and what they already wrote are kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(u,m)=>{await uh(u,m)}),o.command("install").argument("<spec>","Extension name, optionally name@version").description("Install an extension from the marketplace into your instance's extension store.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--connection <id>",'Bind this connection id (required when the extension declares a { type:"connection" } input).').action(async(u,m)=>{let v=u.lastIndexOf("@"),x=v>0?u.slice(0,v):u,S=v>0?u.slice(v+1):void 0,g=sa();g||w(`marketplace not configured \u2014 set ${Cr} and ${Uo}.
3850
+ Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let T=ia(g.registryUrl);T&&w(T);let{baseUrl:E,token:A}=await H(m.baseUrl),C=new wn(g),O;try{O=await J(`fetching ${u}`,()=>C.fetchBundle(x,S))}catch(Z){w(`marketplace fetch failed for ${u}: ${Z instanceof Error?Z.message:String(Z)}`)}let G=Eo(O.manifest),N=null;if(G.length>0){if(!m.connection){let Z=G.map(ye=>ye.source_system).join(", ");w(`${O.name}@${O.version} declares a connection input (source: ${Z}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}N=m.connection}let W=xA(O.bundle,O.name,O.kind),me=new q({baseUrl:E,token:A});try{let Z=await J(`installing ${O.name}@${O.version}`,()=>me.deploy({...W,provenance:"marketplace",...N?{connectionId:N}:{}}));b(`installed ${O.name}@${O.version} \u2192 ${Z.id} (status=${Z.status}, ${Z.outcome})`+(N?` bound to connection ${N}.`:"."))}catch(Z){Z instanceof Q&&Z.status===403&&w("install forbidden (403) \u2014 the stored PAT is not for an admin."),w(`install failed: ${Z instanceof Error?Z.message:String(Z)}`)}}),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(u,m)=>{let v=sa();v||w(`marketplace not configured \u2014 set ${Cr} and ${Uo}.
3851
+ Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let x=ia(v.registryUrl);x&&w(x);let S=se(process.cwd(),u),g=await Sn(S),T=/\bdefineConduit\s*[<(]/.test(g)?"conduit":"hook",E={};if(m.manifest){let O=se(process.cwd(),m.manifest),G;try{G=await ae.readFile(O,"utf8")}catch{w(`manifest not found at ${m.manifest}.`)}let N;try{N=JSON.parse(G)}catch{w(`manifest is not valid JSON: ${m.manifest}.`)}(typeof N!="object"||N===null||Array.isArray(N))&&w("manifest must be a JSON object."),E=N}try{qi(E,g)}catch(O){O instanceof Kt&&w(O.message),w(`manifest validation failed: ${O instanceof Error?O.message:String(O)}`)}let A=new wn(v);try{await J(`publishing ${m.name}@${m.pkgVersion}`,()=>A.publish({name:m.name,version:m.pkgVersion,kind:T,bundle:g,manifest:E}))}catch(O){O instanceof Q&&O.status===403&&w("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),O instanceof Q&&O.status===409&&w(`version already published \u2014 ${m.name}@${m.pkgVersion} exists. Bump the version.`),w(`publish failed: ${O instanceof Error?O.message:String(O)}`)}let C=Eo(E);b(`published ${m.name}@${m.pkgVersion} (kind=${T}) to the marketplace.`),C.length>0&&b(` declares ${C.length} connection input(s): ${C.map(O=>O.source_system).join(", ")} \u2014 bound at install.`)}),n.command("init").description("Scaffold a Claude-Code extension project in the current dir.").option("--base-url <url>","Instance to wire .mcp.json to (defaults to the active instance).").action(async u=>{let m=await ht(u.baseUrl).catch(()=>null),v=ba({baseUrl:m?.baseUrl,token:m?.token}),x=0,S=0,g=0;for(let T of v){let E=se(process.cwd(),T.path),A=await Lb(E,T);A==="wrote"?(x+=1,b(` wrote ${T.path}`)):A==="merged"?(g+=1,b(` merged ${T.path} (added the .mcp.json rule)`)):(S+=1,b(` skipped ${T.path} (exists)`))}b(`
3852
+ project init: ${x} written, ${g} merged, ${S} skipped.`)}),n.command("ci").description(`Write the reusable release-deploy GitHub Action to ${ya} (non-destructive).`).action(async()=>{let u=gp(),m=0,v=0;for(let x of u){let S=se(process.cwd(),x.path);await Pr(S,x.content,x.executable)==="wrote"?(m+=1,b(` wrote ${x.path}`)):(v+=1,b(` skipped ${x.path} (exists)`))}b(`
3853
+ project ci: ${m} written, ${v} skipped.`),m>0&&(b(`
3854
+ Next: mint a releases:write PAT in your Turbobase app (Settings \u203A Access tokens),`),b("store it as the GitHub Actions secret TURBOBASE_RELEASE_PAT, and set the repo"),b("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 u=>{let{baseUrl:m,token:v}=await H(u.baseUrl),x=new q({baseUrl:m,token:v}),S;try{S=await x.catalogRecords()}catch(C){C instanceof Q&&(C.status===401||C.status===403)&&w("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),w(`catalog fetch failed: ${C instanceof Error?C.message:String(C)}`)}if(S.length===0){b("no records in the instance catalog \u2014 nothing to generate.");return}let g=se(process.cwd(),u.out),T=Ku(S,{event:u.event}),E=0,A=0;for(let{recordType:C,fixture:O}of T){let G=et(g,`${C}.json`),N=`${JSON.stringify(O,null,2)}
3841
3855
  `;u.force?(await ae.mkdir(zt(G),{recursive:!0}),await ae.writeFile(G,N,{mode:420}),E+=1,b(` wrote ${u.out}/${C}.json`)):await Pr(G,N)==="wrote"?(E+=1,b(` wrote ${u.out}/${C}.json`)):(A+=1,b(` skipped ${u.out}/${C}.json (exists \u2014 use --force to overwrite)`))}b(`
3842
- samples init: ${E} written, ${A} skipped.`)});let Tt=e.command("guardrails").description("Control PG\u2192source write-back with policy rules (staged write rollout)."),Li=u=>[u.name??m.dim(u.id.slice(0,8)),u.status==="active"?m.green("active"):u.status==="proposed"?m.yellow("proposed"):m.dim("inactive"),u.decision==="deny"?m.red(u.decision):u.decision==="require_confirm"?m.yellow(u.decision):m.green(u.decision),String(u.priority),u.source,u.record??u.op,u.actor??m.dim("any"),u.when||m.dim("(always)"),u.reason??""],Ub=["NAME","STATUS","DECISION","PRIO","SOURCE","RECORD","ACTOR","WHEN","REASON"];Tt.command("list").description("List every write guardrail on your instance, in evaluation order.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async u=>{let{baseUrl:h,token:v}=await H(u.baseUrl),x=new q({baseUrl:h,token:v}),S;try{S=await x.guardrailsList()}catch(g){V(g,"extensions:deploy","list guardrails"),w(`list guardrails failed: ${g instanceof Error?g.message:String(g)}`)}if(u.json)return b(JSON.stringify(S,null,2));if(S.length===0)return b(`no write guardrails \u2014 every record the admin entitlement allows is writable.
3843
- `+m.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));b(ft(S.map(Li),{head:Ub})),b(m.dim(" first match wins; lower PRIO is evaluated first."))}),Tt.command("create <name>").description("Create a rule gating PG\u2192source writes that match it.").option("--source <system>","Adapter id to scope to, or '*' for every source.","*").option("--record <type>","Record type to scope to, or '*' for every record.","*").option("--op <glob>","Raw op glob, when gating something other than a record write.").option("--target <glob>","Row address glob, e.g. 'salesOrder.12345'.").option("--actor <glob>","Only match this caller, e.g. 'agent:*' to gate AI writes but not human ones.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.","deny").option("--priority <n>","Lower is evaluated first (default 100).",u=>Number(u)).option("--when <expr>","Row predicate, e.g. 'total gt 10000'. Omit to match every row.").option("--reason <text>","Why this rule exists \u2014 shown to a blocked writer and in `list`.").option("--disabled","Create the rule parked, so it takes effect only when activated.").option("--confirm-freeze-all","Required for an unconditional deny across '*'/'*'.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{let{baseUrl:v,token:x}=await H(h.baseUrl),S=new q({baseUrl:v,token:x}),g;try{g=await S.guardrailCreate({name:u,source:h.source,record:h.record,decision:h.decision,...h.op?{op:h.op}:{},...h.target?{target:h.target}:{},...h.actor?{actor:h.actor}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when?{when:h.when}:{},...h.reason?{reason:h.reason}:{},...h.disabled?{enabled:!1}:{},...h.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(T){V(T,"extensions:deploy","create a guardrail"),w(`create guardrail failed: ${T instanceof Error?T.message:String(T)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(g.name??g.id)} created${g.status==="active"?"":m.dim(` (${g.status} \u2014 activate it to take effect)`)}`),b(m.dim(` ${g.decision} ${g.source}/${g.record??g.op}${g.actor?` actor=${g.actor}`:""}${g.when?` where ${g.when}`:""} @prio ${g.priority}`)),b(m.dim(` verify with: turbobase guardrails test --source ${g.source==="*"?"<source>":g.source} --record <record>`))}),Tt.command("edit <name>").description("Change a rule \u2014 its decision, priority, predicate or reason.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.").option("--priority <n>","Lower is evaluated first.",u=>Number(u)).option("--when <expr>","New row predicate. Pass '' to match every row.").option("--reason <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{h.decision===void 0&&h.priority===void 0&&h.when===void 0&&h.reason===void 0&&w("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:v,token:x}=await H(h.baseUrl),S=new q({baseUrl:v,token:x}),g;try{g=await S.guardrailUpdate(u,{...h.decision!==void 0?{decision:h.decision}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when!==void 0?{when:h.when}:{},...h.reason!==void 0?{reason:h.reason}:{}})}catch(T){V(T,"extensions:deploy","edit a guardrail"),w(`edit guardrail failed: ${T instanceof Error?T.message:String(T)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(g.name??g.id)} updated`),b(m.dim(` ${g.decision} ${g.source}/${g.record??g.op}${g.when?` where ${g.when}`:""} @prio ${g.priority}`))});for(let[u,h,v]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])Tt.command(`${u} <name>`).description(h==="active"?"Arm a parked or proposed rule.":"Park a rule without deleting it \u2014 the reversible move mid-rollout.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(x,S)=>{let{baseUrl:g,token:T}=await H(S.baseUrl),E=new q({baseUrl:g,token:T});try{await E.guardrailUpdate(x,{status:h})}catch(A){V(A,"extensions:deploy",`${u} a guardrail`),w(`${u} guardrail failed: ${A instanceof Error?A.message:String(A)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(x)} ${v}`),h==="inactive"&&b(m.dim(" writes it was gating now fall through to the other rules."))});Tt.command("delete <name>").description("Remove a rule. Prefer `deactivate` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{let{baseUrl:v,token:x}=await H(h.baseUrl),S=new q({baseUrl:v,token:x});try{await S.guardrailDelete(u)}catch(g){V(g,"extensions:deploy","delete a guardrail"),w(`delete guardrail failed: ${g instanceof Error?g.message:String(g)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(u)} deleted`)}),Tt.command("posture [mode]").description("Show or set the GLOBAL default. 'allow' = deny-list (unmatched writes allowed, carve with deny rules). 'deny' = allow-list (unmatched writes denied, open with allow rules).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{let{baseUrl:v,token:x}=await H(h.baseUrl),S=new q({baseUrl:v,token:x}),g=A=>A==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(u===void 0){let A;try{A=await S.guardrailPostureGet()}catch(C){V(C,"extensions:deploy","read the guardrail posture"),w(`read posture failed: ${C instanceof Error?C.message:String(C)}`)}b(`guardrail posture: ${m.bold(g(A.mode))}`),b(m.dim(A.mode==="deny"?" Unmatched writes are DENIED. Open records with `guardrails create <name> --decision allow`.":" Unmatched writes are allowed-with-audit. Freeze records with `guardrails create <name> --decision deny`."));return}let T=u.trim().toLowerCase();T!=="allow"&&T!=="deny"&&w("posture must be 'allow' or 'deny'.");let E;try{E=await S.guardrailPostureSet(T)}catch(A){V(A,"extensions:deploy","set the guardrail posture"),w(`set posture failed: ${A instanceof Error?A.message:String(A)}`)}b(`${m.green("\u2713")} guardrail posture set to ${m.bold(g(E.mode))}`),E.mode==="deny"&&b(m.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),Tt.command("test").description("What happens to this write? Runs the real evaluator; writes nothing.").requiredOption("--source <system>","Adapter id the write targets.").requiredOption("--record <type>","Record type the write targets.").option("--actor <actor>","Caller to simulate, e.g. 'agent:ai' or 'user:<id>'.").option("--external-id <id>","Source-side row id, for target-scoped rules.").option("--fields <json>","A candidate row as JSON, so `when` predicates can be decided.").option("--op <op>","Write op: 'delete' tests <record>.delete; omitted tests <record>.write.").option("--phase <phase>","boundary | cdc | worker | adapter. Defaults to worker (the last gate).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON.").action(async u=>{let h;if(u.fields)try{h=JSON.parse(u.fields)}catch(E){w(`--fields must be valid JSON: ${E instanceof Error?E.message:String(E)}`)}let{baseUrl:v,token:x}=await H(u.baseUrl),S=new q({baseUrl:v,token:x}),g;try{g=await S.guardrailTest({source:u.source,record:u.record,...u.actor?{actor:u.actor}:{},...u.externalId?{externalId:u.externalId}:{},...h?{fields:h}:{},...u.op?{op:u.op}:{},...u.phase?{phase:u.phase}:{}})}catch(E){V(E,"extensions:deploy","test guardrails"),w(`guardrails test failed: ${E instanceof Error?E.message:String(E)}`)}if(u.json)return b(JSON.stringify(g,null,2));let T=`${u.source}/${g.op??u.record}`;g.degraded?(b(`${m.red("\u2717")} ${T} \u2014 guardrail policy is UNREADABLE; writes fail closed`),b(m.dim(` ${g.reason}`))):g.allowed?b(`${m.green("\u2713")} ${T} \u2014 ${g.decision}`+(g.blockedBy?m.dim(` (rule ${g.blockedBy})`):m.dim(" (no rule matched)"))):(b(`${m.red("\u2717")} ${T} \u2014 ${g.decision} by ${m.bold(g.blockedBy??"?")} at the ${g.phase} gate`),g.message&&b(m.dim(` ${g.message}`))),g.decision==="require_confirm"&&b(m.yellow(" this write is HELD for operator approval, not refused.")),g.allowed||(process.exitCode=1)});let fn=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),xo=(u,h={})=>{let v=`${m.bold(u.table)} ${m.dim(u.displayName)}`;b(u.exists===!1?`${v} ${m.dim("(new)")}`:v);for(let x of u.fields){let S=[x.required?"required":null].filter(Boolean).join(", "),g=h.showClaimants&&x.claimedBy?.length?` ${m.dim(`\u2190 ${x.claimedBy.join(", ")}`)}`:"";b(` ${x.column.padEnd(28)} ${x.type}${S?` (${S})`:""}${g}`)}h.showClaimants&&u.claimants.length>1&&b(m.dim(` claimed by ${u.claimants.join(", ")}`))};function Ro(u){if(u instanceof Q&&u.status===409){let h=u.body;h?.error==="table_conflict"&&h.message&&(L(h.message),process.exit(1))}w(`tables: ${u instanceof Error?u.message:String(u)}`)}let Gd=async u=>{let h=et(se(process.cwd(),u),"public","turbobase.json"),v=await ae.readFile(h,"utf8").catch(()=>null);if(v===null)return null;let x;try{x=JSON.parse(v)}catch(g){w(`${h} is not valid JSON: ${g instanceof Error?g.message:String(g)}`)}let S=x.tables;return S===void 0?{tables:[],manifestPath:h}:(Array.isArray(S)||w(`${h}: "tables" must be an array.`),{tables:S,manifestPath:h})};fn.command("list").description("List the custom tables on your instance and who claims each one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async u=>{let{baseUrl:h,token:v}=await H(u.baseUrl),x=new q({baseUrl:h,token:v}),S;try{S=await x.tablesList()}catch(g){V(g,"extensions:deploy","list tables"),w(`list tables failed: ${g instanceof Error?g.message:String(g)}`)}if(u.json)return b(JSON.stringify(S,null,2));if(S.length===0)return b("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");b(ft(S.map(g=>[g.table,g.displayName,String(g.fields.length),g.status,g.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),fn.command("plan").description("Preview what this project's declared tables would do. Writes nothing; exits 1 on a conflict.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: the app slug in .turbobase, else cli).").action(async(u,h)=>{let v=await Gd(u??".");if(v||w(`no public/turbobase.json under ${se(process.cwd(),u??".")}.`),v.tables.length===0)return b(`${v.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:x,token:S}=await H(h.baseUrl),g=new q({baseUrl:x,token:S}),T;try{T=await J("planning tables",()=>g.tablesPlan({claimedBy:h.as,tables:v.tables}))}catch(E){V(E,"extensions:deploy","plan tables"),Ro(E)}b(`claiming as ${m.bold(T.claimedBy)}`);for(let E of T.tables)xo(E,{showClaimants:!0});b(""),b(m.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),fn.command("apply").description("Apply this project's declared tables to the instance.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: cli).").action(async(u,h)=>{let v=await Gd(u??".");if(v||w(`no public/turbobase.json under ${se(process.cwd(),u??".")}.`),v.tables.length===0)return b(`${v.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:x,token:S}=await H(h.baseUrl),g=new q({baseUrl:x,token:S}),T;try{T=await J("applying tables",()=>g.tablesApply({claimedBy:h.as,tables:v.tables}))}catch(E){V(E,"extensions:deploy","apply tables"),Ro(E)}for(let E of T.tables)xo(E,{showClaimants:!0});b(`applied ${T.tables.length} table${T.tables.length===1?"":"s"} as ${T.claimedBy}.`)}),fn.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(u,h)=>[...h??[],u],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{let v=h.field.map(E=>{let[A,C,O]=E.split(":");return(!A||!C)&&w(`--field "${E}" must be name:type[:required] (e.g. title:text:required).`),O!==void 0&&O!=="required"&&w(`--field "${E}": the third part may only be "required".`),{name:A,type:C,...O==="required"?{required:!0}:{}}}),{baseUrl:x,token:S}=await H(h.baseUrl),g=new q({baseUrl:x,token:S}),T;try{T=await J(`creating cr_${u}`,()=>g.tablesApply({tables:[{slug:u,displayName:h.name??u,fields:v,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(E){V(E,"extensions:deploy","create a table"),Ro(E)}for(let E of T.tables)xo(E);b(""),b(m.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),fn.command("drop").description("Drop a table and everything in it. Irreversible.").argument("<slug>","Table slug (without the cr_ prefix).").requiredOption("--confirm <slug>","Type the EXACT slug to confirm (fail-closed).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{h.confirm!==u&&w(`drop refused: --confirm "${h.confirm}" does not match "${u}".`);let{baseUrl:v,token:x}=await H(h.baseUrl),S=new q({baseUrl:v,token:x}),g;try{g=await J(`dropping cr_${u}`,()=>S.tablesDrop(u,h.confirm))}catch(T){V(T,"extensions:deploy","drop a table"),w(`drop failed: ${T instanceof Error?T.message:String(T)}`)}if(!g.removed)return b(`no table named "${u}" on this instance \u2014 nothing dropped.`);b(`dropped ${g.table} and every row in it.`)});let ji=e.command("sandbox").description("Ephemeral local authoring sandboxes.");ji.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 u=>{process.env.TURBOBASE_SANDBOX="1";let h=Bd(),v;try{v=await Cm(h,{fromTenant:u.from,ttl:u.ttl,sample:u.sample,baseUrl:u.baseUrl})}catch(x){x instanceof Cn&&w(x.message),w(`sandbox create failed: ${x instanceof Error?x.message:String(x)}`)}b(`sandbox ${v.name} ready.`),b(` source: ${v.fromTenant} (sampled ${Math.round(v.sampleFraction*100)}%, redacted)`),b(` url: ${v.url}`),b(` expires: ${v.expiresAt}`)}),ji.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async u=>{let h=Bd();await Fa(h).catch(()=>[]);let v;try{v=await Im(h,u)}catch(x){w(`sandbox destroy failed: ${x instanceof Error?x.message:String(x)}`)}v||w(`no sandbox named '${u}'.`),b(`destroyed sandbox ${v.name} (dropped ${v.database}).`)}),ji.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let u=Bd(),h=await Fa(u).catch(()=>[]),v=await ls(),{active:x}=Ba(v);if(x.length===0)b("no active sandboxes.");else{for(let S of x)b(` ${S.name} from=${S.fromTenant} expires=${S.expiresAt} ${S.url}`);b(`
3844
- ${x.length} active sandbox(es).`)}h.length>0&&b(`(reaped ${h.length} expired sandbox(es).)`)}),o.command("export").description("Pull the live instance into turbobase/bundle.json (adopt an instance into a repo).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",Xo).action(async u=>{let{baseUrl:h,token:v}=await H(u.baseUrl),x=new q({baseUrl:h,token:v}),S;try{S=await J("exporting instance config",()=>x.configExport())}catch(E){E instanceof Q&&(E.status===401||E.status===403)&&w("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),w(`ext export failed: ${E instanceof Error?E.message:String(E)}`)}let g=typeof S.serialized=="string"?S.serialized:`${JSON.stringify(S.manifest??S,null,2)}
3856
+ samples init: ${E} written, ${A} skipped.`)});let Tt=e.command("guardrails").description("Control PG\u2192source write-back with policy rules (staged write rollout)."),Li=u=>[u.name??h.dim(u.id.slice(0,8)),u.status==="active"?h.green("active"):u.status==="proposed"?h.yellow("proposed"):h.dim("inactive"),u.decision==="deny"?h.red(u.decision):u.decision==="require_confirm"?h.yellow(u.decision):h.green(u.decision),String(u.priority),u.source,u.record??u.op,u.actor??h.dim("any"),u.when||h.dim("(always)"),u.reason??""],Ub=["NAME","STATUS","DECISION","PRIO","SOURCE","RECORD","ACTOR","WHEN","REASON"];Tt.command("list").description("List every write guardrail on your instance, in evaluation order.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async u=>{let{baseUrl:m,token:v}=await H(u.baseUrl),x=new q({baseUrl:m,token:v}),S;try{S=await x.guardrailsList()}catch(g){V(g,"extensions:deploy","list guardrails"),w(`list guardrails failed: ${g instanceof Error?g.message:String(g)}`)}if(u.json)return b(JSON.stringify(S,null,2));if(S.length===0)return b(`no write guardrails \u2014 every record the admin entitlement allows is writable.
3857
+ `+h.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));b(ft(S.map(Li),{head:Ub})),b(h.dim(" first match wins; lower PRIO is evaluated first."))}),Tt.command("create <name>").description("Create a rule gating PG\u2192source writes that match it.").option("--source <system>","Adapter id to scope to, or '*' for every source.","*").option("--record <type>","Record type to scope to, or '*' for every record.","*").option("--op <glob>","Raw op glob, when gating something other than a record write.").option("--target <glob>","Row address glob, e.g. 'salesOrder.12345'.").option("--actor <glob>","Only match this caller, e.g. 'agent:*' to gate AI writes but not human ones.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.","deny").option("--priority <n>","Lower is evaluated first (default 100).",u=>Number(u)).option("--when <expr>","Row predicate, e.g. 'total gt 10000'. Omit to match every row.").option("--reason <text>","Why this rule exists \u2014 shown to a blocked writer and in `list`.").option("--disabled","Create the rule parked, so it takes effect only when activated.").option("--confirm-freeze-all","Required for an unconditional deny across '*'/'*'.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,m)=>{let{baseUrl:v,token:x}=await H(m.baseUrl),S=new q({baseUrl:v,token:x}),g;try{g=await S.guardrailCreate({name:u,source:m.source,record:m.record,decision:m.decision,...m.op?{op:m.op}:{},...m.target?{target:m.target}:{},...m.actor?{actor:m.actor}:{},...Number.isFinite(m.priority)?{priority:Number(m.priority)}:{},...m.when?{when:m.when}:{},...m.reason?{reason:m.reason}:{},...m.disabled?{enabled:!1}:{},...m.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(T){V(T,"extensions:deploy","create a guardrail"),w(`create guardrail failed: ${T instanceof Error?T.message:String(T)}`)}b(`${h.green("\u2713")} guardrail ${h.bold(g.name??g.id)} created${g.status==="active"?"":h.dim(` (${g.status} \u2014 activate it to take effect)`)}`),b(h.dim(` ${g.decision} ${g.source}/${g.record??g.op}${g.actor?` actor=${g.actor}`:""}${g.when?` where ${g.when}`:""} @prio ${g.priority}`)),b(h.dim(` verify with: turbobase guardrails test --source ${g.source==="*"?"<source>":g.source} --record <record>`))}),Tt.command("edit <name>").description("Change a rule \u2014 its decision, priority, predicate or reason.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.").option("--priority <n>","Lower is evaluated first.",u=>Number(u)).option("--when <expr>","New row predicate. Pass '' to match every row.").option("--reason <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,m)=>{m.decision===void 0&&m.priority===void 0&&m.when===void 0&&m.reason===void 0&&w("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:v,token:x}=await H(m.baseUrl),S=new q({baseUrl:v,token:x}),g;try{g=await S.guardrailUpdate(u,{...m.decision!==void 0?{decision:m.decision}:{},...Number.isFinite(m.priority)?{priority:Number(m.priority)}:{},...m.when!==void 0?{when:m.when}:{},...m.reason!==void 0?{reason:m.reason}:{}})}catch(T){V(T,"extensions:deploy","edit a guardrail"),w(`edit guardrail failed: ${T instanceof Error?T.message:String(T)}`)}b(`${h.green("\u2713")} guardrail ${h.bold(g.name??g.id)} updated`),b(h.dim(` ${g.decision} ${g.source}/${g.record??g.op}${g.when?` where ${g.when}`:""} @prio ${g.priority}`))});for(let[u,m,v]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])Tt.command(`${u} <name>`).description(m==="active"?"Arm a parked or proposed rule.":"Park a rule without deleting it \u2014 the reversible move mid-rollout.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(x,S)=>{let{baseUrl:g,token:T}=await H(S.baseUrl),E=new q({baseUrl:g,token:T});try{await E.guardrailUpdate(x,{status:m})}catch(A){V(A,"extensions:deploy",`${u} a guardrail`),w(`${u} guardrail failed: ${A instanceof Error?A.message:String(A)}`)}b(`${h.green("\u2713")} guardrail ${h.bold(x)} ${v}`),m==="inactive"&&b(h.dim(" writes it was gating now fall through to the other rules."))});Tt.command("delete <name>").description("Remove a rule. Prefer `deactivate` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,m)=>{let{baseUrl:v,token:x}=await H(m.baseUrl),S=new q({baseUrl:v,token:x});try{await S.guardrailDelete(u)}catch(g){V(g,"extensions:deploy","delete a guardrail"),w(`delete guardrail failed: ${g instanceof Error?g.message:String(g)}`)}b(`${h.green("\u2713")} guardrail ${h.bold(u)} deleted`)}),Tt.command("posture [mode]").description("Show or set the GLOBAL default. 'allow' = deny-list (unmatched writes allowed, carve with deny rules). 'deny' = allow-list (unmatched writes denied, open with allow rules).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,m)=>{let{baseUrl:v,token:x}=await H(m.baseUrl),S=new q({baseUrl:v,token:x}),g=A=>A==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(u===void 0){let A;try{A=await S.guardrailPostureGet()}catch(C){V(C,"extensions:deploy","read the guardrail posture"),w(`read posture failed: ${C instanceof Error?C.message:String(C)}`)}b(`guardrail posture: ${h.bold(g(A.mode))}`),b(h.dim(A.mode==="deny"?" Unmatched writes are DENIED. Open records with `guardrails create <name> --decision allow`.":" Unmatched writes are allowed-with-audit. Freeze records with `guardrails create <name> --decision deny`."));return}let T=u.trim().toLowerCase();T!=="allow"&&T!=="deny"&&w("posture must be 'allow' or 'deny'.");let E;try{E=await S.guardrailPostureSet(T)}catch(A){V(A,"extensions:deploy","set the guardrail posture"),w(`set posture failed: ${A instanceof Error?A.message:String(A)}`)}b(`${h.green("\u2713")} guardrail posture set to ${h.bold(g(E.mode))}`),E.mode==="deny"&&b(h.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),Tt.command("test").description("What happens to this write? Runs the real evaluator; writes nothing.").requiredOption("--source <system>","Adapter id the write targets.").requiredOption("--record <type>","Record type the write targets.").option("--actor <actor>","Caller to simulate, e.g. 'agent:ai' or 'user:<id>'.").option("--external-id <id>","Source-side row id, for target-scoped rules.").option("--fields <json>","A candidate row as JSON, so `when` predicates can be decided.").option("--op <op>","Write op: 'delete' tests <record>.delete; omitted tests <record>.write.").option("--phase <phase>","boundary | cdc | worker | adapter. Defaults to worker (the last gate).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON.").action(async u=>{let m;if(u.fields)try{m=JSON.parse(u.fields)}catch(E){w(`--fields must be valid JSON: ${E instanceof Error?E.message:String(E)}`)}let{baseUrl:v,token:x}=await H(u.baseUrl),S=new q({baseUrl:v,token:x}),g;try{g=await S.guardrailTest({source:u.source,record:u.record,...u.actor?{actor:u.actor}:{},...u.externalId?{externalId:u.externalId}:{},...m?{fields:m}:{},...u.op?{op:u.op}:{},...u.phase?{phase:u.phase}:{}})}catch(E){V(E,"extensions:deploy","test guardrails"),w(`guardrails test failed: ${E instanceof Error?E.message:String(E)}`)}if(u.json)return b(JSON.stringify(g,null,2));let T=`${u.source}/${g.op??u.record}`;g.degraded?(b(`${h.red("\u2717")} ${T} \u2014 guardrail policy is UNREADABLE; writes fail closed`),b(h.dim(` ${g.reason}`))):g.allowed?b(`${h.green("\u2713")} ${T} \u2014 ${g.decision}`+(g.blockedBy?h.dim(` (rule ${g.blockedBy})`):h.dim(" (no rule matched)"))):(b(`${h.red("\u2717")} ${T} \u2014 ${g.decision} by ${h.bold(g.blockedBy??"?")} at the ${g.phase} gate`),g.message&&b(h.dim(` ${g.message}`))),g.decision==="require_confirm"&&b(h.yellow(" this write is HELD for operator approval, not refused.")),g.allowed||(process.exitCode=1)});let fn=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),xo=(u,m={})=>{let v=`${h.bold(u.table)} ${h.dim(u.displayName)}`;b(u.exists===!1?`${v} ${h.dim("(new)")}`:v);for(let x of u.fields){let S=[x.required?"required":null].filter(Boolean).join(", "),g=m.showClaimants&&x.claimedBy?.length?` ${h.dim(`\u2190 ${x.claimedBy.join(", ")}`)}`:"";b(` ${x.column.padEnd(28)} ${x.type}${S?` (${S})`:""}${g}`)}m.showClaimants&&u.claimants.length>1&&b(h.dim(` claimed by ${u.claimants.join(", ")}`))};function Ro(u){if(u instanceof Q&&u.status===409){let m=u.body;m?.error==="table_conflict"&&m.message&&(L(m.message),process.exit(1))}w(`tables: ${u instanceof Error?u.message:String(u)}`)}let Gd=async u=>{let m=et(se(process.cwd(),u),"public","turbobase.json"),v=await ae.readFile(m,"utf8").catch(()=>null);if(v===null)return null;let x;try{x=JSON.parse(v)}catch(g){w(`${m} is not valid JSON: ${g instanceof Error?g.message:String(g)}`)}let S=x.tables;return S===void 0?{tables:[],manifestPath:m}:(Array.isArray(S)||w(`${m}: "tables" must be an array.`),{tables:S,manifestPath:m})};fn.command("list").description("List the custom tables on your instance and who claims each one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async u=>{let{baseUrl:m,token:v}=await H(u.baseUrl),x=new q({baseUrl:m,token:v}),S;try{S=await x.tablesList()}catch(g){V(g,"extensions:deploy","list tables"),w(`list tables failed: ${g instanceof Error?g.message:String(g)}`)}if(u.json)return b(JSON.stringify(S,null,2));if(S.length===0)return b("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");b(ft(S.map(g=>[g.table,g.displayName,String(g.fields.length),g.status,g.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),fn.command("plan").description("Preview what this project's declared tables would do. Writes nothing; exits 1 on a conflict.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: the app slug in .turbobase, else cli).").action(async(u,m)=>{let v=await Gd(u??".");if(v||w(`no public/turbobase.json under ${se(process.cwd(),u??".")}.`),v.tables.length===0)return b(`${v.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:x,token:S}=await H(m.baseUrl),g=new q({baseUrl:x,token:S}),T;try{T=await J("planning tables",()=>g.tablesPlan({claimedBy:m.as,tables:v.tables}))}catch(E){V(E,"extensions:deploy","plan tables"),Ro(E)}b(`claiming as ${h.bold(T.claimedBy)}`);for(let E of T.tables)xo(E,{showClaimants:!0});b(""),b(h.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),fn.command("apply").description("Apply this project's declared tables to the instance.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: cli).").action(async(u,m)=>{let v=await Gd(u??".");if(v||w(`no public/turbobase.json under ${se(process.cwd(),u??".")}.`),v.tables.length===0)return b(`${v.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:x,token:S}=await H(m.baseUrl),g=new q({baseUrl:x,token:S}),T;try{T=await J("applying tables",()=>g.tablesApply({claimedBy:m.as,tables:v.tables}))}catch(E){V(E,"extensions:deploy","apply tables"),Ro(E)}for(let E of T.tables)xo(E,{showClaimants:!0});b(`applied ${T.tables.length} table${T.tables.length===1?"":"s"} as ${T.claimedBy}.`)}),fn.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(u,m)=>[...m??[],u],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,m)=>{let v=m.field.map(E=>{let[A,C,O]=E.split(":");return(!A||!C)&&w(`--field "${E}" must be name:type[:required] (e.g. title:text:required).`),O!==void 0&&O!=="required"&&w(`--field "${E}": the third part may only be "required".`),{name:A,type:C,...O==="required"?{required:!0}:{}}}),{baseUrl:x,token:S}=await H(m.baseUrl),g=new q({baseUrl:x,token:S}),T;try{T=await J(`creating cr_${u}`,()=>g.tablesApply({tables:[{slug:u,displayName:m.name??u,fields:v,...m.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(E){V(E,"extensions:deploy","create a table"),Ro(E)}for(let E of T.tables)xo(E);b(""),b(h.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),fn.command("drop").description("Drop a table and everything in it. Irreversible.").argument("<slug>","Table slug (without the cr_ prefix).").requiredOption("--confirm <slug>","Type the EXACT slug to confirm (fail-closed).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,m)=>{m.confirm!==u&&w(`drop refused: --confirm "${m.confirm}" does not match "${u}".`);let{baseUrl:v,token:x}=await H(m.baseUrl),S=new q({baseUrl:v,token:x}),g;try{g=await J(`dropping cr_${u}`,()=>S.tablesDrop(u,m.confirm))}catch(T){V(T,"extensions:deploy","drop a table"),w(`drop failed: ${T instanceof Error?T.message:String(T)}`)}if(!g.removed)return b(`no table named "${u}" on this instance \u2014 nothing dropped.`);b(`dropped ${g.table} and every row in it.`)});let ji=e.command("sandbox").description("Ephemeral local authoring sandboxes.");ji.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 u=>{process.env.TURBOBASE_SANDBOX="1";let m=Bd(),v;try{v=await Ch(m,{fromTenant:u.from,ttl:u.ttl,sample:u.sample,baseUrl:u.baseUrl})}catch(x){x instanceof Cn&&w(x.message),w(`sandbox create failed: ${x instanceof Error?x.message:String(x)}`)}b(`sandbox ${v.name} ready.`),b(` source: ${v.fromTenant} (sampled ${Math.round(v.sampleFraction*100)}%, redacted)`),b(` url: ${v.url}`),b(` expires: ${v.expiresAt}`)}),ji.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async u=>{let m=Bd();await Fa(m).catch(()=>[]);let v;try{v=await Ih(m,u)}catch(x){w(`sandbox destroy failed: ${x instanceof Error?x.message:String(x)}`)}v||w(`no sandbox named '${u}'.`),b(`destroyed sandbox ${v.name} (dropped ${v.database}).`)}),ji.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let u=Bd(),m=await Fa(u).catch(()=>[]),v=await ls(),{active:x}=Ba(v);if(x.length===0)b("no active sandboxes.");else{for(let S of x)b(` ${S.name} from=${S.fromTenant} expires=${S.expiresAt} ${S.url}`);b(`
3858
+ ${x.length} active sandbox(es).`)}m.length>0&&b(`(reaped ${m.length} expired sandbox(es).)`)}),o.command("export").description("Pull the live instance into turbobase/bundle.json (adopt an instance into a repo).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",Xo).action(async u=>{let{baseUrl:m,token:v}=await H(u.baseUrl),x=new q({baseUrl:m,token:v}),S;try{S=await J("exporting instance config",()=>x.configExport())}catch(E){E instanceof Q&&(E.status===401||E.status===403)&&w("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),w(`ext export failed: ${E instanceof Error?E.message:String(E)}`)}let g=typeof S.serialized=="string"?S.serialized:`${JSON.stringify(S.manifest??S,null,2)}
3845
3859
  `,T=se(process.cwd(),u.out,xn);await ae.mkdir(zt(T),{recursive:!0}),await ae.writeFile(T,g,"utf8"),b(`wrote ${u.out}/${xn} (${g.split(`
3846
- `).length} lines).`)});let Wd=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),Mb=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Jd=()=>process.env.TURBOBASE_HOME?.trim()||et(fA(),".turbobase"),qb=()=>"1.35.0",$o=async()=>Promise.all(Mb.map(async u=>{try{return await import(u.name),{...u,present:!0}}catch{return{...u,present:!1}}}));Wd.command("status").description("Report which optional native packages are installed.").action(async()=>{let u=await $o();for(let h of u)b(`${h.present?ve.success("installed"):ve.warn("missing")} ${m.bold(h.name)} \u2014 ${h.needs}`);u.some(h=>!h.present)&&b(`
3847
- run \`${$n} ext extras install\` to fetch them into ${Jd()}.`)}),Wd.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let u=await $o();if(u.every(A=>A.present)){b(ve.success("extras already installed \u2014 nothing to do."));return}let h=Jd();await ae.mkdir(h,{recursive:!0});let v=u.filter(A=>!A.present).map(A=>A.name),x=ja(process.platform,process.arch),S=async(A,C)=>{let{code:O,stderr:G}=await To("npm",["install","--prefix",h,"--no-audit","--no-fund",...A]);O!==0&&w(`extras install failed while installing ${C} (npm exited ${O}).
3860
+ `).length} lines).`)});let Wd=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),Mb=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Jd=()=>process.env.TURBOBASE_HOME?.trim()||et(fA(),".turbobase"),qb=()=>"1.37.0",$o=async()=>Promise.all(Mb.map(async u=>{try{return await import(u.name),{...u,present:!0}}catch{return{...u,present:!1}}}));Wd.command("status").description("Report which optional native packages are installed.").action(async()=>{let u=await $o();for(let m of u)b(`${m.present?ve.success("installed"):ve.warn("missing")} ${h.bold(m.name)} \u2014 ${m.needs}`);u.some(m=>!m.present)&&b(`
3861
+ run \`${$n} ext extras install\` to fetch them into ${Jd()}.`)}),Wd.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let u=await $o();if(u.every(A=>A.present)){b(ve.success("extras already installed \u2014 nothing to do."));return}let m=Jd();await ae.mkdir(m,{recursive:!0});let v=u.filter(A=>!A.present).map(A=>A.name),x=ja(process.platform,process.arch),S=async(A,C)=>{let{code:O,stderr:G}=await To("npm",["install","--prefix",m,"--no-audit","--no-fund",...A]);O!==0&&w(`extras install failed while installing ${C} (npm exited ${O}).
3848
3862
  ${G.trim()}
3849
- These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},g=v.filter(A=>A!=="isolated-vm");if(g.length>0){let A=g.map(C=>`${C}@${Na[C]??"latest"}`);b(`installing ${A.join(", ")} \u2192 ${h}/node_modules \u2026`),await S(A,g.join(", "))}if(v.includes("isolated-vm")){let A=`isolated-vm@${Na["isolated-vm"]}`;if(b(`installing ${A} \u2192 ${h}/node_modules \u2026`),await S(["--ignore-scripts",A],"isolated-vm"),Tm.includes(x)){let O=`${La}@${qb()}`;b(`fetching ${O} (no upstream binary for ${x}) \u2026`);let{code:G}=await To("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",O]);G!==0&&b(ve.warn(`could not fetch ${O} \u2014 falling back to a source build.`))}let C=await xm({home:h});C.length>0&&b(` ${ve.success("prebuilt")} ${C.join(", ")} \u2192 isolated-vm/prebuilds/${x}`)}let T=await $o(),E=T.filter(A=>!A.present).map(A=>A.name);if(E.includes("isolated-vm")){b(ve.warn(`no prebuilt isolated-vm for ${x} / Node ${process.versions.node} (${Da()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:A}=await To("npm",["rebuild","--prefix",h,"isolated-vm"]);A===0&&(T=await $o(),E=T.filter(C=>!C.present).map(C=>C.name))}E.length>0&&w(`npm succeeded but ${E.join(", ")} still will not load \u2014 no prebuilt binary for ${x} / Node ${process.versions.node} (${Da()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),b(ve.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let Ar=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return Ar.command("deploy").description("Enqueue a server-side release deploy. UPLOADS the SDF project src/ from the checkout (the producer swap) when present; else a solution-only live-fetch deploy. An approved target requires --approved-by.").requiredOption("--target <mode>","Deploy posture: auto (apply now) | approved (needs a recorded approval).").option("--solution <id>","The solution id the release delivers (omit for an upload-only deploy).").option("--project <dir>","SDF project dir whose src/ is uploaded (default: cwd).").option("--git-repo <repo>","Git provenance LINK: source repo (default $GITHUB_REPOSITORY or `git remote get-url origin`).").option("--git-ref <ref>","Git provenance LINK: ref/branch/tag (default $GITHUB_REF).").option("--ref <committish>","Git provenance: the ref/branch/tag/sha the upload was built from; resolved to a commit sha via `git rev-parse` (default $GITHUB_SHA or HEAD).").option("--pr-url <url>","Git provenance LINK: the PR this deploy came from (default $PR_URL).").option("--approved-by <email>","Record the approval (REQUIRED for --target approved).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async u=>{let h=u.target==="approved"?"approved":u.target==="auto"?"auto":null;h||w(`--target must be 'auto' or 'approved' (got '${u.target}').`);let v=await AA(se(process.cwd(),u.project??".")),x=Object.keys(v).length;!u.solution&&x===0&&w("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let g=(u.ref?await Fd(["rev-parse",u.ref])??u.ref:null)??process.env.GITHUB_SHA??await Fd(["rev-parse","HEAD"]),T=u.gitRepo??process.env.GITHUB_REPOSITORY??await Fd(["remote","get-url","origin"]),E=u.gitRef??process.env.GITHUB_REF??null,A=u.prUrl??process.env.PR_URL??null,{baseUrl:C,token:O}=await H(u.baseUrl),G=new q({baseUrl:C,token:O}),N;try{N=await G.releaseDeploy({solutionId:u.solution??null,target:h,approvedBy:u.approvedBy??null,files:x>0?v:null,gitRepo:T,gitRef:E,gitSha:g,prUrl:A})}catch(W){V(W,"releases:write","release deploy"),W instanceof Q&&W.status===404&&w("solution_not_found \u2014 no solution with that id."),w(`release deploy failed: ${W instanceof Error?W.message:String(W)}`)}b(`release ${N.releaseId} enqueued \u2192 taskId=${N.taskId} (target=${h}`+(x>0?`, uploaded ${x} bundle file(s)`:", live-fetch")+")."),u.follow&&await Ta(()=>G.releaseStatus(N.releaseId),`release ${N.releaseId}`,u.intervalMs)}),Ar.command("pull").argument("<id>","The release id").description("Write the SDF project a FAILED release built into <dir>: owned/ (yours, editable) and context/ (the rest of the bundle, read-only). Edit owned/, then `release push`.").requiredOption("--dir <path>","Directory to write the project into (created if absent).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{let{baseUrl:v,token:x}=await H(h.baseUrl),S=new q({baseUrl:v,token:x}),g;try{g=await S.releaseFiles(u)}catch(A){A instanceof Q&&A.status===404&&w(`release ${u} not found.`),A instanceof Q&&A.status===409&&w(`no built project was retained for release ${u}. Files are kept for a FAILED attempt only \u2014 a shipped bundle is recoverable from the account.`),V(A,"releases:write","pull a release"),w(`release pull failed: ${A instanceof Error?A.message:String(A)}`)}let T=se(process.cwd(),h.dir),E=0;for(let[A,C]of[["owned",g.owned],["context",g.context]])for(let[O,G]of Object.entries(C)){let N=et(T,A,O);await ae.mkdir(zt(N),{recursive:!0}),await ae.writeFile(N,G,"utf8"),E++}await ae.writeFile(et(T,".turbobase-release.json"),JSON.stringify({releaseId:g.releaseId,version:g.version,contentDigest:g.contentDigest},null,2),"utf8"),b(`pulled release ${g.releaseId} (${g.status}) \u2192 ${T}
3863
+ These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},g=v.filter(A=>A!=="isolated-vm");if(g.length>0){let A=g.map(C=>`${C}@${Na[C]??"latest"}`);b(`installing ${A.join(", ")} \u2192 ${m}/node_modules \u2026`),await S(A,g.join(", "))}if(v.includes("isolated-vm")){let A=`isolated-vm@${Na["isolated-vm"]}`;if(b(`installing ${A} \u2192 ${m}/node_modules \u2026`),await S(["--ignore-scripts",A],"isolated-vm"),Th.includes(x)){let O=`${La}@${qb()}`;b(`fetching ${O} (no upstream binary for ${x}) \u2026`);let{code:G}=await To("npm",["install","--prefix",m,"--no-audit","--no-fund","--ignore-scripts",O]);G!==0&&b(ve.warn(`could not fetch ${O} \u2014 falling back to a source build.`))}let C=await xh({home:m});C.length>0&&b(` ${ve.success("prebuilt")} ${C.join(", ")} \u2192 isolated-vm/prebuilds/${x}`)}let T=await $o(),E=T.filter(A=>!A.present).map(A=>A.name);if(E.includes("isolated-vm")){b(ve.warn(`no prebuilt isolated-vm for ${x} / Node ${process.versions.node} (${Da()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:A}=await To("npm",["rebuild","--prefix",m,"isolated-vm"]);A===0&&(T=await $o(),E=T.filter(C=>!C.present).map(C=>C.name))}E.length>0&&w(`npm succeeded but ${E.join(", ")} still will not load \u2014 no prebuilt binary for ${x} / Node ${process.versions.node} (${Da()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),b(ve.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let Ar=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return Ar.command("deploy").description("Enqueue a server-side release deploy. UPLOADS the SDF project src/ from the checkout (the producer swap) when present; else a solution-only live-fetch deploy. An approved target requires --approved-by.").requiredOption("--target <mode>","Deploy posture: auto (apply now) | approved (needs a recorded approval).").option("--solution <id>","The solution id the release delivers (omit for an upload-only deploy).").option("--project <dir>","SDF project dir whose src/ is uploaded (default: cwd).").option("--git-repo <repo>","Git provenance LINK: source repo (default $GITHUB_REPOSITORY or `git remote get-url origin`).").option("--git-ref <ref>","Git provenance LINK: ref/branch/tag (default $GITHUB_REF).").option("--ref <committish>","Git provenance: the ref/branch/tag/sha the upload was built from; resolved to a commit sha via `git rev-parse` (default $GITHUB_SHA or HEAD).").option("--pr-url <url>","Git provenance LINK: the PR this deploy came from (default $PR_URL).").option("--approved-by <email>","Record the approval (REQUIRED for --target approved).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async u=>{let m=u.target==="approved"?"approved":u.target==="auto"?"auto":null;m||w(`--target must be 'auto' or 'approved' (got '${u.target}').`);let v=await AA(se(process.cwd(),u.project??".")),x=Object.keys(v).length;!u.solution&&x===0&&w("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let g=(u.ref?await Fd(["rev-parse",u.ref])??u.ref:null)??process.env.GITHUB_SHA??await Fd(["rev-parse","HEAD"]),T=u.gitRepo??process.env.GITHUB_REPOSITORY??await Fd(["remote","get-url","origin"]),E=u.gitRef??process.env.GITHUB_REF??null,A=u.prUrl??process.env.PR_URL??null,{baseUrl:C,token:O}=await H(u.baseUrl),G=new q({baseUrl:C,token:O}),N;try{N=await G.releaseDeploy({solutionId:u.solution??null,target:m,approvedBy:u.approvedBy??null,files:x>0?v:null,gitRepo:T,gitRef:E,gitSha:g,prUrl:A})}catch(W){V(W,"releases:write","release deploy"),W instanceof Q&&W.status===404&&w("solution_not_found \u2014 no solution with that id."),w(`release deploy failed: ${W instanceof Error?W.message:String(W)}`)}b(`release ${N.releaseId} enqueued \u2192 taskId=${N.taskId} (target=${m}`+(x>0?`, uploaded ${x} bundle file(s)`:", live-fetch")+")."),u.follow&&await Ta(()=>G.releaseStatus(N.releaseId),`release ${N.releaseId}`,u.intervalMs)}),Ar.command("pull").argument("<id>","The release id").description("Write the SDF project a FAILED release built into <dir>: owned/ (yours, editable) and context/ (the rest of the bundle, read-only). Edit owned/, then `release push`.").requiredOption("--dir <path>","Directory to write the project into (created if absent).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,m)=>{let{baseUrl:v,token:x}=await H(m.baseUrl),S=new q({baseUrl:v,token:x}),g;try{g=await S.releaseFiles(u)}catch(A){A instanceof Q&&A.status===404&&w(`release ${u} not found.`),A instanceof Q&&A.status===409&&w(`no built project was retained for release ${u}. Files are kept for a FAILED attempt only \u2014 a shipped bundle is recoverable from the account.`),V(A,"releases:write","pull a release"),w(`release pull failed: ${A instanceof Error?A.message:String(A)}`)}let T=se(process.cwd(),m.dir),E=0;for(let[A,C]of[["owned",g.owned],["context",g.context]])for(let[O,G]of Object.entries(C)){let N=et(T,A,O);await ae.mkdir(zt(N),{recursive:!0}),await ae.writeFile(N,G,"utf8"),E++}await ae.writeFile(et(T,".turbobase-release.json"),JSON.stringify({releaseId:g.releaseId,version:g.version,contentDigest:g.contentDigest},null,2),"utf8"),b(`pulled release ${g.releaseId} (${g.status}) \u2192 ${T}
3850
3864
  ${Object.keys(g.owned).length} owned file(s), ${Object.keys(g.context).length} context file(s), ${E} total
3851
3865
  `+(g.logTail?`
3852
3866
  the failure these bytes produced:
3853
3867
  ${g.logTail.trim()}
3854
3868
  `:"")+`
3855
3869
  edit the files under owned/, then:
3856
- turbobase release push ${g.releaseId} --dir ${h.dir}`)}),Ar.command("push").argument("<id>","The release id the project was pulled from").description("Ship the edited project as a NEW release delivering the same solution. Refuses if a context/ file changed \u2014 those belong to other solutions.").requiredOption("--dir <path>","The directory `release pull` wrote.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--target <target>","'auto' (default) or 'approved'.","auto").option("--approved-by <who>","Required for an approved target (fails closed without it).").action(async(u,h)=>{let{baseUrl:v,token:x}=await H(h.baseUrl),S=new q({baseUrl:v,token:x}),g=se(process.cwd(),h.dir),T;try{T=await S.releaseFiles(u)}catch(N){N instanceof Q&&N.status===404&&w(`release ${u} not found.`),V(N,"releases:write","push a release"),w(`release push failed: ${N instanceof Error?N.message:String(N)}`)}let E=async(N,W)=>{try{return await ae.readFile(et(g,N,W),"utf8")}catch{return null}},A=[];for(let[N,W]of Object.entries(T.context)){let he=await E("context",N);he!==null&&he!==W&&A.push(N)}A.length>0&&w(`refusing to push \u2014 these context/ files were modified, and they belong to other solutions in the same bundle:
3870
+ turbobase release push ${g.releaseId} --dir ${m.dir}`)}),Ar.command("push").argument("<id>","The release id the project was pulled from").description("Ship the edited project as a NEW release delivering the same solution. Refuses if a context/ file changed \u2014 those belong to other solutions.").requiredOption("--dir <path>","The directory `release pull` wrote.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--target <target>","'auto' (default) or 'approved'.","auto").option("--approved-by <who>","Required for an approved target (fails closed without it).").action(async(u,m)=>{let{baseUrl:v,token:x}=await H(m.baseUrl),S=new q({baseUrl:v,token:x}),g=se(process.cwd(),m.dir),T;try{T=await S.releaseFiles(u)}catch(N){N instanceof Q&&N.status===404&&w(`release ${u} not found.`),V(N,"releases:write","push a release"),w(`release push failed: ${N instanceof Error?N.message:String(N)}`)}let E=async(N,W)=>{try{return await ae.readFile(et(g,N,W),"utf8")}catch{return null}},A=[];for(let[N,W]of Object.entries(T.context)){let me=await E("context",N);me!==null&&me!==W&&A.push(N)}A.length>0&&w(`refusing to push \u2014 these context/ files were modified, and they belong to other solutions in the same bundle:
3857
3871
  `+A.map(N=>` context/${N}`).join(`
3858
- `)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let C={...T.context},O=0;for(let[N,W]of Object.entries(T.owned)){let he=await E("owned",N);C[N]=he??W,he!==null&&he!==W&&O++}O===0&&b("nothing changed under owned/ \u2014 pushing the same bytes the release already built.");let G=h.target==="approved"?"approved":"auto";try{let N=await S.releasePush(u,{files:C,target:G,...h.approvedBy?{approvedBy:h.approvedBy}:{}});b(`pushed ${Object.keys(C).length} file(s) (${O} edited) \u2192 release ${N.releaseId} (task ${N.taskId}).
3872
+ `)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let C={...T.context},O=0;for(let[N,W]of Object.entries(T.owned)){let me=await E("owned",N);C[N]=me??W,me!==null&&me!==W&&O++}O===0&&b("nothing changed under owned/ \u2014 pushing the same bytes the release already built.");let G=m.target==="approved"?"approved":"auto";try{let N=await S.releasePush(u,{files:C,target:G,...m.approvedBy?{approvedBy:m.approvedBy}:{}});b(`pushed ${Object.keys(C).length} file(s) (${O} edited) \u2192 release ${N.releaseId} (task ${N.taskId}).
3859
3873
  follow it with:
3860
- turbobase release status ${N.releaseId} --follow`)}catch(N){N instanceof Q&&N.status===403&&w("an approved target needs --approved-by (the deploy gate fails closed)."),N instanceof Q&&N.status===409&&w("that solution already has an active release \u2014 roll it back or wait for it."),V(N,"releases:write","push a release"),w(`release push failed: ${N instanceof Error?N.message:String(N)}`)}}),Ar.command("status").argument("<id>","The release id").description("Show a release deploy job's status; with --follow, poll to completion.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async(u,h)=>{let{baseUrl:v,token:x}=await H(h.baseUrl),S=new q({baseUrl:v,token:x});if(h.follow){await Ta(()=>S.releaseStatus(u),`release ${u}`,h.intervalMs);return}let g;try{g=await S.releaseStatus(u)}catch(T){V(T,"releases:write","release status"),T instanceof Q&&T.status===404&&w(`release ${u} not found.`),w(`release status failed: ${T instanceof Error?T.message:String(T)}`)}b(`release ${u}: status=${g.releaseStatus??"?"} stage=${g.stage} ${g.percent}%`+(g.runStatus?` (${g.runStatus})`:"")),g.outputTail&&b(g.outputTail.replace(/\n+$/,""))}),Ar.command("rollback").argument("<id>","The release id to roll back").description("Roll back a live release (LIFO-guarded; server-side reverse deploy).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{let{baseUrl:v,token:x}=await H(h.baseUrl),S=new q({baseUrl:v,token:x}),g;try{g=await S.releaseRollback(u)}catch(T){V(T,"releases:write","release rollback"),T instanceof Q&&T.status===404&&w(`release ${u} not found.`),T instanceof Q&&T.status===409&&w(`release ${u} cannot be rolled back (not live, or a newer release advanced past it).`),w(`release rollback failed: ${T instanceof Error?T.message:String(T)}`)}b(`release ${g.releaseId} rolled back \u2192 status=${g.release?.status??"rolled_back"}.`)}),Ar.command("list").description("List releases, newest-first, with delivered titles + latest status.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async u=>{let{baseUrl:h,token:v}=await H(u.baseUrl),x=new q({baseUrl:h,token:v}),S;try{S=await x.releaseList()}catch(g){V(g,"releases:write","release list"),w(`release list failed: ${g instanceof Error?g.message:String(g)}`)}if(S.length===0){b("no releases.");return}if(Ie())b(ft(S.map(g=>[g.id,Nr(g.status),g.target,g.backend,g.solutionTitles?.length?g.solutionTitles.map(T=>`"${T}"`).join(", "):m.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let g of S){let T=g.solutionTitles?.length?` "${g.solutionTitles.join('", "')}"`:"";b(` ${g.id} ${g.status.padEnd(11)} target=${g.target} backend=${g.backend}${T}`)}b(`
3861
- ${S.length} release(s).`)}),e.command("logs").description("Read the platform event log \u2014 guardrails, hooks, scheduled tasks, conduits and sync in one stream. Absorbs the old `ext logs` via --extension / --conduit.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--subsystem <s>","guardrails | hooks | tasks | conduits | sync").option("--severity <s>","Minimum severity: debug | info | warn | error (a THRESHOLD \u2014 `warn` includes errors).").option("--code <code>","One event code, e.g. guardrails.write_denied").option("--since <window>","Relative window (10m, 2h, 3d) or an ISO timestamp.").option("--correlation-id <id>","Follow one root action across every subsystem it touched.").option("--extension <id>","One extension's own log ring buffer (was `ext logs <id>`).").option("--conduit <id>","One conduit's run ledger (was `ext logs <id> --follow`).").option("--follow","Poll for new rows and print them as they land.").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").option("--limit <n>","Max rows on the first read (default 100, max 500).").option("--json","Emit raw rows as JSON, one per line.").action(async u=>{let{baseUrl:h,token:v}=await H(u.baseUrl),x=new q({baseUrl:h,token:v}),S=u.limit?Number(u.limit):void 0,g=u.intervalMs?Number(u.intervalMs):void 0;if(u.conduit){try{await np(x,u.conduit,{...u.follow?{follow:!0}:{},...S!==void 0?{limit:S}:{},...g!==void 0?{intervalMs:g}:{},sink:b})}catch(T){w(`logs --conduit failed: ${T instanceof Error?T.message:String(T)}`)}return}if(u.extension){try{let T=await x.logs(u.extension,S);T.length===0&&b(`no logs for ${u.extension}.`);for(let E of T)b(` [${E.level}] ${E.ts??""} ${E.message}`)}catch(T){w(`logs --extension failed: ${T instanceof Error?T.message:String(T)}`)}return}try{await sp(x,{...u.subsystem?{subsystem:u.subsystem}:{},...u.severity?{severity:u.severity}:{},...u.code?{code:u.code}:{},...u.since?{since:u.since}:{},...u.correlationId?{correlationId:u.correlationId}:{},...u.follow?{follow:!0}:{},...u.json?{json:!0}:{},...S!==void 0?{limit:S}:{},...g!==void 0?{intervalMs:g}:{},sink:b})}catch(T){w(`logs failed: ${T instanceof Error?T.message:String(T)}`)}}),e.command("mcp").description("Run the local stdio authoring MCP server, for clients pointed at a process rather than a URL. (The .mcp.json that `project init` writes uses the instance's HTTP servers instead.)").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async u=>{let{runAuthoringMcpServer:h}=await Promise.resolve().then(()=>(Nb(),Ob));await h({baseUrl:u.baseUrl})}),e.addHelpText("after",["","Common flows:"," turbobase auth login --base-url https://acme.turbobase.app --token tb_pat_\u2026"," turbobase project init && turbobase project types"," turbobase ext new hook --record salesOrder && turbobase ext test hooks/\u2026"," turbobase ext deploy --to prod"," turbobase apps deploy my-app ./app","","Run `turbobase <group> --help` for a group (auth, project, ext, apps, kb, sandbox, mcp).","Docs: https://docs.turbobase.io/cli/overview/"].join(`
3874
+ turbobase release status ${N.releaseId} --follow`)}catch(N){N instanceof Q&&N.status===403&&w("an approved target needs --approved-by (the deploy gate fails closed)."),N instanceof Q&&N.status===409&&w("that solution already has an active release \u2014 roll it back or wait for it."),V(N,"releases:write","push a release"),w(`release push failed: ${N instanceof Error?N.message:String(N)}`)}}),Ar.command("status").argument("<id>","The release id").description("Show a release deploy job's status; with --follow, poll to completion.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async(u,m)=>{let{baseUrl:v,token:x}=await H(m.baseUrl),S=new q({baseUrl:v,token:x});if(m.follow){await Ta(()=>S.releaseStatus(u),`release ${u}`,m.intervalMs);return}let g;try{g=await S.releaseStatus(u)}catch(T){V(T,"releases:write","release status"),T instanceof Q&&T.status===404&&w(`release ${u} not found.`),w(`release status failed: ${T instanceof Error?T.message:String(T)}`)}b(`release ${u}: status=${g.releaseStatus??"?"} stage=${g.stage} ${g.percent}%`+(g.runStatus?` (${g.runStatus})`:"")),g.outputTail&&b(g.outputTail.replace(/\n+$/,""))}),Ar.command("rollback").argument("<id>","The release id to roll back").description("Roll back a live release (LIFO-guarded; server-side reverse deploy).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,m)=>{let{baseUrl:v,token:x}=await H(m.baseUrl),S=new q({baseUrl:v,token:x}),g;try{g=await S.releaseRollback(u)}catch(T){V(T,"releases:write","release rollback"),T instanceof Q&&T.status===404&&w(`release ${u} not found.`),T instanceof Q&&T.status===409&&w(`release ${u} cannot be rolled back (not live, or a newer release advanced past it).`),w(`release rollback failed: ${T instanceof Error?T.message:String(T)}`)}b(`release ${g.releaseId} rolled back \u2192 status=${g.release?.status??"rolled_back"}.`)}),Ar.command("list").description("List releases, newest-first, with delivered titles + latest status.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async u=>{let{baseUrl:m,token:v}=await H(u.baseUrl),x=new q({baseUrl:m,token:v}),S;try{S=await x.releaseList()}catch(g){V(g,"releases:write","release list"),w(`release list failed: ${g instanceof Error?g.message:String(g)}`)}if(S.length===0){b("no releases.");return}if(Ie())b(ft(S.map(g=>[g.id,Nr(g.status),g.target,g.backend,g.solutionTitles?.length?g.solutionTitles.map(T=>`"${T}"`).join(", "):h.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let g of S){let T=g.solutionTitles?.length?` "${g.solutionTitles.join('", "')}"`:"";b(` ${g.id} ${g.status.padEnd(11)} target=${g.target} backend=${g.backend}${T}`)}b(`
3875
+ ${S.length} release(s).`)}),e.command("logs").description("Read the platform event log \u2014 guardrails, hooks, scheduled tasks, conduits and sync in one stream. Absorbs the old `ext logs` via --extension / --conduit.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--subsystem <s>","guardrails | hooks | tasks | conduits | sync").option("--severity <s>","Minimum severity: debug | info | warn | error (a THRESHOLD \u2014 `warn` includes errors).").option("--code <code>","One event code, e.g. guardrails.write_denied").option("--since <window>","Relative window (10m, 2h, 3d) or an ISO timestamp.").option("--correlation-id <id>","Follow one root action across every subsystem it touched.").option("--extension <id>","One extension's own log ring buffer (was `ext logs <id>`).").option("--conduit <id>","One conduit's run ledger (was `ext logs <id> --follow`).").option("--follow","Poll for new rows and print them as they land.").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").option("--limit <n>","Max rows on the first read (default 100, max 500).").option("--json","Emit raw rows as JSON, one per line.").action(async u=>{let{baseUrl:m,token:v}=await H(u.baseUrl),x=new q({baseUrl:m,token:v}),S=u.limit?Number(u.limit):void 0,g=u.intervalMs?Number(u.intervalMs):void 0;if(u.conduit){try{await np(x,u.conduit,{...u.follow?{follow:!0}:{},...S!==void 0?{limit:S}:{},...g!==void 0?{intervalMs:g}:{},sink:b})}catch(T){w(`logs --conduit failed: ${T instanceof Error?T.message:String(T)}`)}return}if(u.extension){try{let T=await x.logs(u.extension,S);T.length===0&&b(`no logs for ${u.extension}.`);for(let E of T)b(` [${E.level}] ${E.ts??""} ${E.message}`)}catch(T){w(`logs --extension failed: ${T instanceof Error?T.message:String(T)}`)}return}try{await sp(x,{...u.subsystem?{subsystem:u.subsystem}:{},...u.severity?{severity:u.severity}:{},...u.code?{code:u.code}:{},...u.since?{since:u.since}:{},...u.correlationId?{correlationId:u.correlationId}:{},...u.follow?{follow:!0}:{},...u.json?{json:!0}:{},...S!==void 0?{limit:S}:{},...g!==void 0?{intervalMs:g}:{},sink:b})}catch(T){w(`logs failed: ${T instanceof Error?T.message:String(T)}`)}}),e.command("mcp").description("Run the local stdio authoring MCP server, for clients pointed at a process rather than a URL. (The .mcp.json that `project init` writes uses the instance's HTTP servers instead.)").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async u=>{let{runAuthoringMcpServer:m}=await Promise.resolve().then(()=>(Nb(),Ob));await m({baseUrl:u.baseUrl})}),e.addHelpText("after",["","Common flows:"," turbobase auth login --base-url https://acme.turbobase.app --token tb_pat_\u2026"," turbobase project init && turbobase project types"," turbobase ext new hook --record salesOrder && turbobase ext test hooks/\u2026"," turbobase ext deploy --to prod"," turbobase apps deploy my-app ./app","","Run `turbobase <group> --help` for a group (auth, project, ext, apps, kb, sandbox, mcp).","Docs: https://docs.turbobase.io/cli/overview/"].join(`
3862
3876
  `)),t&&void 0,e}function xA(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 RA(t){let e=et(se(process.cwd(),t),"public","turbobase.json"),r=await ae.readFile(e,"utf8").catch(()=>null);if(r===null)return null;let n;try{n=JSON.parse(r)}catch(o){w(`${e} is not valid JSON: ${o instanceof Error?o.message:String(o)}`)}return(typeof n!="object"||n===null||Array.isArray(n))&&w(`${e} must be a JSON object.`),{manifest:n,manifestPath:e}}async function $A(){let t=se(process.cwd(),Xo,xn),e;try{e=await ae.readFile(t,"utf8")}catch{w(`no config found \u2014 this project authors none (no ${Qo}/, ${es}/, ${Wt} or ${Jt}) and there is no ${Xo}/${xn}.
3863
3877
  Author a hook with \`turbobase ext new hook\`, or adopt an existing instance with \`turbobase ext export\`.`)}try{return Tp(e)}catch(r){w(`bundle is invalid: ${r instanceof Error?r.message:String(r)}`)}}async function zd(){let t=process.cwd();if(!await Ep(t))return $A();let e;try{e=await Pp(t,{inline:aa})}catch(r){w(`could not build the config bundle from this project: ${r instanceof Error?r.message:String(r)}`)}for(let r of e.unparsed)L(`${r.file}: ${r.reason} \u2014 NOT included in the plan.`);return e.unparsed.length>0&&w(`${e.unparsed.length} extension file(s) could not be identified. Every hook/conduit needs a literal \`id:\`, \`recordType:\` and \`event:\`/\`on:\` \u2014 run \`turbobase ext lint <file>\` on each.`),e.manifest}function EA(t,e){b(`plan against ${e}:`);for(let r of t.add)b(` ${Vt.add(`${r.kind} ${r.id}`)}`);for(let r of t.change)b(` ${Vt.change(`${r.kind} ${r.id}`)}`);for(let r of t.destroy)b(` ${Vt.destroy(`${r.kind} ${r.id}`)}`);b(`
3864
3878
  ${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 PA(t){try{let r=new URL(t).hostname.split(".")[0];return r&&r!=="localhost"?r:void 0}catch{return}}function To(t,e,r){return new Promise(n=>{let o=Kd(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 Bd(){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 To("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 To("supabase",["migration","up","--db-url",n]);if(o.code!==0)throw new Error(`supabase migration up failed (exit ${o.code}): ${o.stderr.trim()}`)},dataCopyUnavailable:()=>"seeding a sandbox from an instance is not implemented yet: it needs a per-column PII classification for the source tables, and a sandbox will never copy a column it cannot prove is safe. Nothing was created. Use `turbobase ext test <file>` or `turbobase ext replay <file> --fixture <f>` for the offline paths.",readSourceTables:async r=>{throw new Error("sandbox data copy is not implemented.")},copyRows:async(r,n,o)=>{let s=Object.keys(o[0]??{});if(s.length===0)return;let i=o.map(a=>`(${s.map(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 AA(t){let e=se(t,"src"),r={},n=async o=>{let s;try{s=await ae.readdir(o,{withFileTypes:!0})}catch{return}for(let i of s){let a=et(o,i.name);if(i.isDirectory())await n(a);else if(i.isFile()){let l=Ni(e,a).split(Hd).join("/");r[l]=await ae.readFile(a,"utf8")}}};return await n(e),r}function Fd(t){return new Promise(e=>{let r=Kd("git",t,{stdio:["ignore","pipe","ignore"]}),n="";r.stdout?.on("data",o=>{n+=o.toString()}),r.on("error",()=>e(null)),r.on("exit",o=>e(o===0&&n.trim()?n.trim():null))})}var CA=!1;CA&&Vd().parseAsync(process.argv).catch(t=>w(t instanceof Error?t.message:String(t)));Vd().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}