@adhd/apigen-engine-runtime 0.1.4 โ†’ 0.2.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.
Files changed (4) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/index.js +1 -1
  3. package/index.mjs +215 -178
  4. package/package.json +5 -5
package/CHANGELOG.md CHANGED
@@ -1,3 +1,15 @@
1
+ ## 0.1.5 (2026-07-25)
2
+
3
+
4
+ ### ๐Ÿ”ฅ Performance
5
+
6
+ - **test:** bound vitest thread pools to curb CPU oversubscription (DEBT-TEST-CPU-OVERSUBSCRIBED-001)
7
+
8
+
9
+ ### โค๏ธ Thank You
10
+
11
+ - pseudosky
12
+
1
13
  ## 0.1.4 (2026-07-24)
2
14
 
3
15
  This was a version bump only for apigen-engine-runtime to align it with other projects, there were no code changes.
package/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("ts-morph");require("node:fs");require("node:path");require("ts-json-schema-generator");const O=require("pino"),ke=require("ajv"),Ie=require("ajv-formats"),k="$apigen";class W extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}}function Ce(e){const t=new Map;return{register(r,n){if(t.has(r.id)&&!(n!=null&&n.override))throw new W(`E_DUP_CODEC: a codec is already registered for id "${r.id}"`);t.set(r.id,r)},resolve(r){for(const n of t.values())if(n.matches(r))return n},get(r){return t.get(r)},ids(){return[...t.keys()]},freeze(){const r=new Map(t),n={register(){throw new W("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(o){for(const i of r.values())if(i.matches(o))return i},get(o){return r.get(o)},ids(){return[...r.keys()]},freeze(){return n}};return n}}}const U="x-apigen-logical",L="x-apigen-codec",I="x-apigen-ctor",C="x-apigen-tojson",xe="0.1.0";function H(e,t){return{registry:e,resolve:r=>{throw new Error(`[apigen-logical] $ref "${r}" cannot be resolved in run-mode without a descriptor root. Supply a resolve() in the ctx override to handle $ref.`)},seen:new WeakSet,path:"",mode:"strict",...t}}function v(e,t,r){const n=r.registry.resolve(t);if(n)return n.encode(e,t,r);const o=t.$ref;if(typeof o=="string"){const a=r.resolve(o);return v(e,a,r)}const i=t.oneOf;if(Array.isArray(i)){const a=ie(e,i,t);return v(e,a,r)}const s=t.type;if(s==="array"){if(!Array.isArray(e))return A(e,t,r);const a=t.items;if(!a)return e.map(c=>w(c));const f=r.path;return Array.isArray(a)?e.map((c,u)=>{const p=a[u];return p===void 0?w(c):v(c,p,{...r,path:`${f}/${u}`})}):e.map((c,u)=>v(c,a,{...r,path:`${f}/${u}`}))}if(s==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return A(e,t,r);const a=t.properties;if(!a)return w(e);const f=r.path,c={};for(const[u,p]of Object.entries(a)){const l=e[u];l!==void 0&&(c[u]=v(l,p,{...r,path:`${f}/${u}`}))}return c}return s==null?A(e,t,r):w(e)}function $(e,t,r){const n=r.registry.resolve(t);if(n)return n.decode(e,t,r);const o=t.$ref;if(typeof o=="string"){const a=r.resolve(o);return $(e,a,r)}const i=t.oneOf;if(Array.isArray(i)){const a=ie(e,i,t);return $(e,a,r)}const s=t.type;if(s==="array"){if(!Array.isArray(e))return e;const a=t.items;if(!a)return e;const f=r.path;return Array.isArray(a)?e.map((c,u)=>{const p=a[u];return p===void 0?c:$(c,p,{...r,path:`${f}/${u}`})}):e.map((c,u)=>$(c,a,{...r,path:`${f}/${u}`}))}if(s==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const f=r.path,c={};for(const[u,p]of Object.entries(a)){const l=e[u];l!==void 0&&(c[u]=$(l,p,{...r,path:`${f}/${u}`}))}return c}return s==null?Me(e,r):e}function ie(e,t,r,n){const o=r.discriminator;if(o!=null&&o.propertyName){const i=e!==null&&typeof e=="object"?e[o.propertyName]:void 0;if(typeof i=="string"&&o.mapping){const s=o.mapping[i];if(s){const a=t.find(f=>f.$ref===s);if(a)return a}}}return t[0]??{}}function A(e,t,r){for(const n of r.registry.ids()){const o=r.registry.get(n);if(o)try{const i=o.encode(e,o.schema,r);return{[k]:n,v:i}}catch{}}return w(e)}function Me(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&k in e){const r=e,n=r[k],o=t.registry.get(n);if(o)return o.decode(r.v,o.schema,t)}return e}function w(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(w);if(typeof e=="object"){const t={};for(const[r,n]of Object.entries(e))n!==void 0&&(t[r]=w(n));return t}return null}function Te(e){return{encode(t,r,n){const o=H(e,n);return v(t,r,o)},decode(t,r,n){const o=H(e,n);return $(t,r,o)}}}const D={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},encode(e,t,r){return e.toISOString()},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${r.path}", got ${typeof e}`);return new Date(String(e))}if(r.mode==="strict"&&Number.isNaN(new Date(e).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${r.path}": ${JSON.stringify(e)}`);return new Date(e)}},F={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},encode(e,t,r){return String(e)},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${r.path}", got ${typeof e}`);try{return BigInt(Math.trunc(Number(e)))}catch{return BigInt(0)}}if(r.mode==="strict")return BigInt(e);if(/^-?\d+$/.test(e))try{return BigInt(e)}catch{return BigInt(0)}return BigInt(0)}},R={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(e){return e.type==="string"&&e.format==="decimal"},encode(e,t,r){return e},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${r.path}", got ${typeof e}`);return String(e)}if(r.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(e))throw new TypeError(`[decimal] wire value "${e}" at "${r.path}" is not a valid decimal string`);return e}},q={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},encode(e,t,r){return Buffer.from(e).toString("base64")},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${r.path}", got ${typeof e}`);return new Uint8Array(0)}if(r.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(e))throw new TypeError(`[byte] wire value at "${r.path}" is not standard base64 (format:byte): "${e}"`);return new Uint8Array(Buffer.from(e,"base64"))}},Pe=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,K={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(e){return e.type==="string"&&e.format==="uuid"},encode(e,t,r){return e.toLowerCase()},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${r.path}", got ${typeof e}`);return String(e).toLowerCase()}if(r.mode==="strict"&&!Pe.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${r.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},x="NaN",M="Infinity",T="-Infinity",Ue=new Set([x,M,T]),B={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},encode(e,t,r){return Number.isNaN(e)?x:e===1/0?M:e===-1/0?T:e},decode(e,t,r){if(typeof e=="number")return e;if(typeof e=="string"){if(e===x)return NaN;if(e===M)return 1/0;if(e===T)return-1/0;const n=Number(e);if(!Number.isNaN(n))return n}if(r.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${r.path}": ${JSON.stringify(e)}. Expected a number or one of ${[...Ue].join(", ")}.`);return NaN}},Le=[D,F,R,q,K,B];function De(e,t={}){for(const r of Le)e.register(r,{override:t.override??!1})}D.id,F.id,R.id,q.id,K.id,B.id;const se=Ce();De(se);const ae=Te(se.freeze());function ce(e,t){var n;const r=((n=e.input)==null?void 0:n.properties)??{};return t in r}function ue(e){var r,n;const t=(n=(r=e.input)==null?void 0:r.properties)==null?void 0:n.data;return Object.keys((t==null?void 0:t.properties)??{})}function Fe(e,t){var o,i,s;const r=(s=(i=(o=e.input)==null?void 0:o.properties)==null?void 0:i.data)==null?void 0:s.properties,n=r==null?void 0:r[t];return n!==void 0?n:void 0}function Re(e,t){return t===void 0||e===void 0?e:ae.decode(e,t)}function _(e,t){const r=t.output;return!r||Object.keys(r).length===0?e:ae.encode(e,r)}async function fe(e,t,r,n,o,i){const a=ue(r).map(c=>Re(i[c],Fe(r,c)));if(ce(r,"session")&&t){const c=await t({session:o.session}),u=await e[n](c,...a);return _(u,r)}if(r.hasCtx){const c=t?await t(o):void 0,u=await e[n](c,...a);return _(u,r)}const f=await e[n](...a);return _(f,r)}class pe{constructor(){this._map=new Map}set(t,r){this._map.set(t,r)}get(t){return this._map.get(t)}has(t){return this._map.has(t)}}function de(e=[]){return async function(r,n,o){const i=o.schemas[r];if(!i)throw new Error(`apigen/invoke: no schema found for operation "${r}"`);const s=()=>fe(o.fns,o.createClient,i,r,n.envelope,n.domainArgs);return e.reduceRight((f,c)=>()=>c(n,f),s)()}}function qe(e){return e}class le{constructor(){this.handlers=new Map}on(t,r){const n=this.handlers.get(t)??[];return this.handlers.set(t,[...n,r]),()=>this.off(t,r)}off(t,r){const n=this.handlers.get(t);if(!n)return;const o=n.filter(i=>i!==r);o.length===0?this.handlers.delete(t):this.handlers.set(t,o)}clear(){this.handlers.clear()}async emit(t){for(const[r,n]of this.handlers)if(Ke(r,t))for(const o of n)await o(t)}}function Ke(e,t){const[r,n,o]=e.split(":");return!(r!=="*"&&r!==t.module||n&&n!=="*"&&n!==t.method||o&&o!=="*"&&o!==t.lifecycle)}function ye(e,t){for(const r of e)if(r.eventMapping)for(const[n,o]of Object.entries(r.eventMapping))t.on(n,o)}async function he(e,t,r){let n={...t};for(const o of e)if(o.createContext){await r.emit({module:o.id,method:"createContext",lifecycle:"start",ctx:n});try{const i=await o.createContext(n);n={...n,...i},await r.emit({module:o.id,method:"createContext",lifecycle:"complete",ctx:n})}catch(i){throw await r.emit({module:o.id,method:"createContext",lifecycle:"error",ctx:n,error:i}),i}}return n}function z(e,t){const r=new Set,n=[e];for(;n.length>0;){const o=n.pop();if(!o||r.has(o))continue;r.add(o);const i=o.$ref;if(typeof i=="string"){if(t){const p=t[i];if(!p){const l=Object.keys(t).join(", ")||"(none)";throw new Error(`[apigen-logical] $ref "${i}" cannot be resolved. Available $defs: ${l}`)}n.push(p)}continue}const s=o.oneOf;if(Array.isArray(s))for(const p of s)typeof p=="object"&&p!==null&&n.push(p);const a=o.properties;if(a)for(const p of Object.values(a))n.push(p);const f=o.items;if(Array.isArray(f))for(const p of f)typeof p=="object"&&p!==null&&n.push(p);else typeof f=="object"&&f!==null&&n.push(f);const c=o.additionalProperties;typeof c=="object"&&c!==null&&n.push(c);const u=o.propertyNames;typeof u=="object"&&u!==null&&n.push(u)}}const G=new Set(["string","number","boolean","integer"]);function Be(e){if(typeof e!="object"||e===null)return!1;const t=e;if(t.$ref!==void 0||t.oneOf||t.anyOf||t.allOf)return!1;const{type:r}=t;return typeof r=="string"?G.has(r):Array.isArray(r)?r.every(n=>G.has(n)||n==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(n=>["string","number","boolean"].includes(typeof n)):!1}function me(e){if(!e||typeof e!="object")return!1;const t=e.properties;return t===void 0||typeof t!="object"||t===null?!1:Object.values(t).every(Be)}function Ve(e){const t={},r=n=>{for(const o of["definitions","$defs"]){const i=n[o];if(i)for(const[s,a]of Object.entries(i)){const f=s.startsWith("#/")?s:`#/${o}/${s}`;t[f]=a}}};for(const n of Object.values(e.schemas))r(n.input),r(n.output);if(Object.keys(t).length!==0)for(const[n,o]of Object.entries(e.schemas))try{z(o.input,t),z(o.output,t)}catch(i){throw new Error(`[apigen-core-client] Schema validation failed for function "${n}": ${i.message}`)}}function We(e,t){const r=['apigen calling convention: all domain parameters go inside a "data" envelope โ€” e.g. { "data": { ... } }'+(t?".":" (an empty object for this zero-parameter tool).")];return e.length>0&&r.push(`Field(s) ${e.map(n=>`"${n}"`).join(", ")} are transport-level envelope metadata, NOT domain data โ€” do not nest them under "data". Over MCP they are read from arguments._meta["x-<pluginId>-<field>"] (default pluginId "adhd"); see @adhd/apigen-engine-naming's envelopeMetaKey/envelopeCliFlag/envelopeEnvVar for the HTTP-header / CLI-flag / env-var equivalents.`),r.join(" ")}function He(e,t,r){Ve(e);const n={};for(const[o,i]of Object.entries(e.schemas)){const s=(r==null?void 0:r[o])??{},a=i.input.properties??{},f=i.input.required??[],c={},u=[],p={};for(const m of t)if(m.envelope&&s[m.id]!==!1)for(const[b,Se]of Object.entries(m.envelope))c[b]=Se,p[b]=m.id,u.includes(b)||u.push(b);const l={type:"object",properties:a,additionalProperties:!1,...f.length>0?{required:f}:{}},y=i.safe===!0||me(i.input),d=i.input.definitions,h=i.input.$defs;n[o]={input:{type:"object",properties:{...c,data:l},required:[...u,...f.length>0?["data"]:[]],additionalProperties:!1,description:We(Object.keys(c),Object.keys(a).length>0),...d?{definitions:d}:{},...h?{$defs:h}:{}},output:i.output,...i.hasCtx?{hasCtx:!0}:{},"x-apigen-safe":y,...Object.keys(p).length>0?{"x-apigen-envelope":p}:{}}}return n}const ze={"decimal.js":"Decimal"};function Ge(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(ze).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Ge(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));class P extends Error{constructor(t){super(t),this.name="ConfigurationError"}}function ge(e){for(const t of e)for(const r of Object.keys(t.eventMapping??{})){const[n]=r.split(":");if(n!=="*"&&n===t.id)throw new P(`Middleware "${t.id}" subscribes to its own events via "${r}". This would cause infinite recursion.`)}}function Je(e){const{domainSchemas:t,middlewares:r,overrides:n={},strict:o=!1}=e;ge(r);for(const c of Object.keys(n))if(!(c in t.schemas)){const u=`Override key "${c}" not found in domain schemas.`;if(o)throw new P(u);console.warn("[apigen-runtime]",u)}const i=new Set(r.map(c=>c.id));for(const[c,u]of Object.entries(n))for(const p of Object.keys(u??{}))if(!i.has(p)){const l=`Override key "${c}.${p}" does not match any declared middleware id.`;if(o)throw new P(l);console.warn("[apigen-runtime]",l)}const s=He(t,r,n),a=new le;return ye(r,a),{schemas:s,createClient:async c=>he(r,c,a),dispose:()=>a.clear()}}function Ye(e={}){const t=e.level??"info",r=typeof e.destination=="string"&&e.destination.length>0,n=!r&&!!process.stderr.isTTY,o=e.format??(n?"pretty":"json"),i={level:t};if(o==="pretty")return i.transport={target:"pino-pretty",options:{colorize:!r,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...r?{destination:e.destination,mkdir:!0}:{destination:2}}},O(i);const s=r?O.destination({dest:e.destination,mkdir:!0,sync:!0}):O.destination(2);return O(i,s)}function we(e){return e?e.type==="array"?`${we(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function be(e){var a;const r=(a=((e==null?void 0:e.input)??{}).properties)==null?void 0:a.data,n=(r==null?void 0:r.properties)??{},o=new Set((r==null?void 0:r.required)??[]),i=Object.entries(n).map(([f,c])=>({name:f,type:we(c),required:o.has(f)})),s=i.map(f=>`${f.name}${f.required?"":"?"}: ${f.type}`).join(", ");return{params:i,text:s}}function Qe(e){let t;return Array.isArray(e)?t=e:e?t=[e]:t=[],t.find(r=>r==="number"||r==="integer"||r==="boolean")}function Xe(e,t){var i,s;const n=((s=(i=((t==null?void 0:t.input)??{}).properties)==null?void 0:i.data)==null?void 0:s.properties)??{},o={...e};for(const[a,f]of Object.entries(n)){const c=o[a];if(typeof c!="string")continue;const u=Qe(f==null?void 0:f.type);if(u==="number"||u==="integer"){const p=Number(c);!Number.isNaN(p)&&c.trim()!==""&&(o[a]=p)}else u==="boolean"&&(c==="true"?o[a]=!0:c==="false"&&(o[a]=!1))}return o}const J=new Set(["default","module.exports","__esModule"]);function Ze(e){const t={},r=(n,o)=>{for(const[i,s]of Object.entries(n))if(typeof s=="function"){!J.has(i)&&!(i in t)&&(t[i]=s);const a=s.name;a&&!(a in t)&&(t[a]=s)}else s&&typeof s=="object"&&o<2&&J.has(i)&&r(s,o+1)};return r(e,0),t}const et=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];class V extends Error{constructor(t,r,n){super(r),this.name="ApiError",this.code=t,this.details=n,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const t={code:this.code,message:this.message};return this.details!==void 0&&(t.details=this.details),t}}function tt(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&et.includes(e.code)&&typeof e.toJSON=="function"}function Y(e,t,r=0){return e==="before-first-chunk"?{phase:e,error:t}:{phase:e,error:t,chunksDelivered:r}}const N=new ke({allErrors:!0});Ie(N);for(const e of[U,L,I,C,"discriminator"])N.addKeyword({keyword:e,valid:!0});N.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function ve(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}const rt=async(e,t)=>{const r=e.ctx.get($e);if(r===void 0)return t();const n=e.operation.id,o=r[n];if(o===void 0)return t();const i={data:e.domainArgs,...e.envelope},s=N.compile(o.input);if(!s(i)){const f=s.errors??[];throw new V("invalid_argument",`Validation failed: ${ve(f)}`,f)}return t()},$e=Symbol("ValidateSchemasToken");function Ne(e){return async function(r,n){const o=r.operation.id,i=e[o];if(i===void 0)return n();const s={data:r.domainArgs,...r.envelope},a=N.compile(i.input);if(!a(s)){const c=a.errors??[];throw new V("invalid_argument",`Validation failed: ${ve(c)}`,c)}return n()}}function nt(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}class ot{constructor(t={}){var n,o;this._store=new Map,this._sweeper=null,this._defaultTtlMs=t.defaultTtlMs;let r=null;t.sweepIntervalMs===0?r=null:t.sweepIntervalMs!==void 0?r=t.sweepIntervalMs:this._defaultTtlMs!==void 0?r=Math.max(1e3,Math.floor(this._defaultTtlMs/4)):r=null,r!==null&&r>0&&(this._sweeper=setInterval(()=>this._sweep(),r),(o=(n=this._sweeper).unref)==null||o.call(n))}create(t,r=[],n){const o=new t(...r),i=nt(),s=n??this._defaultTtlMs,a=s!==void 0?Date.now()+s:null;return this._store.set(i,{instance:o,expiresAt:a}),{instanceId:i}}get(t){const r=this._store.get(t);if(!r)throw new Error(`[instance-registry] Unknown instanceId: "${t}"`);if(r.expiresAt!==null&&Date.now()>r.expiresAt)throw this._evict(t,r),new Error(`[instance-registry] Instance "${t}" has expired`);return r.instance}async dispatch(t,r,n=[]){const o=this.get(t),i=o[r];if(typeof i!="function")throw new Error(`[instance-registry] Method "${r}" not found on instance "${t}"`);return i.call(o,...n)}async dispose(t){const r=this._store.get(t);r&&(this._store.delete(t),await E(r.instance))}async disposeAll(){this._sweeper!==null&&(clearInterval(this._sweeper),this._sweeper=null);const t=[...this._store.entries()];this._store.clear(),await Promise.all(t.map(([,r])=>E(r.instance)))}get size(){return this._store.size}_sweep(){const t=Date.now();for(const[r,n]of this._store)n.expiresAt!==null&&t>n.expiresAt&&this._evict(r,n)}_evict(t,r){this._store.delete(t),E(r.instance)}}async function E(e){if(e!==null&&typeof e=="object"&&"dispose"in e){const t=e.dispose;typeof t=="function"&&await t.call(e)}}function it(e){const{produce:t,signal:r}=e,n=r??new AbortController().signal;return{[Symbol.asyncIterator](){const o=t(n);return{async next(){return n.aborted?(await o.return(void 0),{done:!0,value:void 0}):o.next()},async return(i){return await o.return(i),{done:!0,value:void 0}},async throw(i){return await o.throw(i),{done:!0,value:void 0}}}}}}async function st(e){const t=[];for await(const r of e)t.push(r);return t}async function at(e){const t=[];try{for await(const r of e)t.push(r);return{ok:!0,chunks:t}}catch(r){const n=tt(r)?r:new V("internal",r instanceof Error?r.message:String(r));return t.length===0?{ok:!1,carrier:Y("before-first-chunk",n)}:{ok:!1,carrier:Y("after-first-chunk",n,t.length)}}}function ct(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}class g extends Error{constructor(t,r){super(r),this.name="UnionCodecError",this.code=t}}function S(e){const t=e.discriminator;if(t===null||typeof t!="object"||Array.isArray(t))return;const r=t;if(typeof r.propertyName!="string")return;const n=r.mapping;if(!(n===null||typeof n!="object"||Array.isArray(n)))return{propertyName:r.propertyName,mapping:n}}function Oe(e,t){const r=e[L];if(typeof r=="string"){const n=t.registry.get(r);if(n)return n}return t.registry.resolve(e)}function ut(e,t,r){const n=Oe(t,r);return n?n.encode(e,t,r):e}function ft(e,t,r){const n=Oe(t,r);return n?n.decode(e,t,r):e}function je(e){const{id:t,schema:r}=e;return{id:t,kind:"union",schema:r,matches(n){if(n[U]==="union")return!0;const o=n.oneOf;return!Array.isArray(o)||o.length===0?!1:S(n)!==void 0},encode(n,o,i){const s=S(o);if(!s)throw new g("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${i.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:f}=s,c=n[a];if(c==null)throw new g("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${i.path}" is missing the discriminator property "${a}".`);const u=String(c),p=f[u];if(!p)throw new g("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${u}" at "${i.path}" is not in the mapping (known: ${Object.keys(f).join(", ")}).`);const l=i.resolve(p);return ut(n,l,{...i,path:`${i.path}[${u}]`})},decode(n,o,i){if(n===null||typeof n!="object"||Array.isArray(n)){let d;throw n===null?d="null":Array.isArray(n)?d="array":d=typeof n,new g("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${d}.`)}const s=n,a=S(o);if(!a)throw new g("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${i.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:f,mapping:c}=a,u=s[f];if(u==null)throw new g("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${i.path}" is missing the discriminator property "${f}".`);const p=String(u),l=c[p];if(!l)throw new g("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${p}" on the wire at "${i.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const y=i.resolve(l);return ft(n,y,{...i,path:`${i.path}[${p}]`})}}}const pt="x-apigen-instances";class j extends Error{constructor(t,r){super(r),this.name="NominalCodecError",this.code=t}}function Q(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function dt(e){const t=e.required;return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}function X(e,t,r){if(t){const n=r.registry.resolve(t);if(n)return n.encode(e,t,r)}return e}function lt(e,t,r){if(t){const n=r.registry.resolve(t);if(n)return n.decode(e,t,r)}return e}function yt(e){const{id:t,schema:r,ctor:n}=e;return{id:t,kind:"nominal",schema:r,matches(o){return o[U]==="nominal"?!0:o[L]===t},encode(o,i,s){if(o===null||typeof o!="object")return o;if(s.seen.has(o)){if(s.mode==="strict")throw new j("E_NOMINAL_CYCLE",`[${t}] cycle detected at "${s.path}": a nominal instance references itself. Strict mode rejects cycles (DESIGN ยง8.3); break the cycle or use 'lossy' mode.`);return null}s.seen.add(o);try{const a=Q(i),f=typeof i[C]=="string"?i[C]:"toJSON",c=o[f];if(typeof c=="function"){const d=c.call(o);if(d!==null&&typeof d=="object"&&!Array.isArray(d)){const h={};for(const[m,b]of Object.entries(d))h[m]=X(b,a[m],{...s,path:`${s.path}/${m}`});return h}return d}const u={},p=Object.keys(a),l=o,y=p.length>0?p:Object.keys(l);for(const d of y){const h=l[d];h!==void 0&&(u[d]=X(h,a[d],{...s,path:`${s.path}/${d}`}))}return u}finally{s.seen.delete(o)}},decode(o,i,s){if(o===null||typeof o!="object"||Array.isArray(o)){let u;throw o===null?u="null":Array.isArray(o)?u="array":u=typeof o,new j("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${u}.`)}const a=o;for(const u of dt(i))if(!(u in a))throw new j("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${u}" missing on the wire at "${s.path}".`);if(i[pt]===!1)throw new j("E_NOMINAL_NONRECONSTRUCTABLE",`[${t}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);const f=Q(i),c={};for(const[u,p]of Object.entries(a))c[u]=lt(p,f[u],{...s,path:`${s.path}/${u}`});if(n){const u=typeof i[I]=="string"?i[I]:"fromJSON",p=n[u];if(typeof p=="function")return p.call(n,c);const l=n;return new l(c)}return c}}}const Ae=[D,F,R,q,K,B],ht={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},Z=yt({id:"ts.NominalSentinel",schema:ht}),mt={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},ee=je({id:"ts.UnionSentinel",schema:mt});function gt(){const e=[...Ae.map(t=>[t.id,t]),[Z.id,Z],[ee.id,ee]];return Object.freeze(new Map(e))}const wt=Object.freeze({host:"ts",logicalTypeVersion:xe,codecs:gt()});function bt(e,t,r){var i;const n=typeof((i=t==null?void 0:t.input)==null?void 0:i.description)=="string"?t.input.description:void 0,o=[r,n].filter(s=>typeof s=="string"&&s.length>0);return o.length>0?o.join(" โ€” "):e}function vt(e){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0)return{outputSchema:void 0,wrapped:!1};const t=e;return t.type==="object"?{outputSchema:t,wrapped:!1}:{outputSchema:{type:"object",properties:{result:t},required:["result"]},wrapped:!0}}function $t(e,t){return e?{result:t}:t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function te(e){return e.words.join("-")}function re(e){return e.words.map(_t).join("")}function ne(e){return e.words.join("_")}function Nt(e,t={}){var l,y;const r=[e.namespace,...e.path],n=e.safe||me(e.input)?"GET":"POST",o=((y=(l=t.http)==null?void 0:l.verb)==null?void 0:y[e.id])??n,i="/"+r.map(d=>te(d)).join("/"),s=r.map(d=>ne(d)).join("_"),f=r.map(d=>ne(d)).slice(0,-1).join("."),c=re(r[r.length-2]??r[0]),u=re(r[r.length-1]),p=r.map(d=>te(d));return{http:{verb:o,route:i},mcp:{name:s},grpc:{package:f,service:c,method:u},cli:{path:p}}}function Ot(e,t){return`x-${e}-${t}`}function jt(e,t){return`--${e}-${t}`}function At(e,t){const r=n=>n.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${r(t)}`:`APIGEN_${r(e)}_${r(t)}`}function _t(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function _e(e){return e.anyOf??e.oneOf}function Et(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=_e(e);if(t){const r=t.filter(n=>n.type!=="null");return r.length>0&&r.every(n=>n.type==="array"||n.type==="object")}return!1}function St(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=_e(e);if(t){const r=t.filter(n=>n.type!=="null");return r.length>0&&r.every(n=>n.type==="boolean")}return!1}function kt(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function It(e){var o,i;const t=(i=(o=e.input)==null?void 0:o.properties)==null?void 0:i.data,r=(t==null?void 0:t.properties)??{},n=(t==null?void 0:t.required)??[];return{props:r,required:n}}function oe(e){return typeof e.handler=="function"}function Ct(e){var o;const t=((o=e.input)==null?void 0:o.properties)??{},r=e["x-apigen-envelope"],n=[];for(const i of Object.keys(t)){if(i==="data")continue;const s=(r==null?void 0:r[i])??"adhd",a=Ot(s,i);n.push({field:i,pluginId:s,httpHeader:a,mcpMetaKey:a,cliFlag:jt(s,i),envVar:At(s,i)})}return n}function xt(e,t){const r=new Map,{props:n}=It(e);for(const[o,i]of Object.entries(n)){let s="string";St(i)?s="boolean":Et(i)&&(s="json"),r.set(kt(o),{camelKey:o,kind:"domain",valueKind:s})}for(const o of t){const i=o.cliFlag.replace(/^--/,"");r.set(i,{camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar})}return r}function Mt(e){const{op:t,schema:r,transport:n,projection:o}=e,i=Nt(t,o),s=r?Ct(r):[],a=r?xt(r,s):new Map,f=r?be(r).params:void 0,c={op:t,transport:n,http:i.http,mcp:i.mcp,cli:i.cli,grpc:i.grpc,params:f,envelope:s,cliFlags:a,streaming:t.streaming,isMount:oe(t)};if(oe(t)){const u=t.handler;c.mountHandler=async p=>u(p)}return c}function Tt(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function Pt(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function Ee(e){return async function(r,n){const o=Object.assign(r,{data:r.domainArgs});return await e.layer(o,n)}}function Ut(e,t){var n;const r=[];for(const o of t){const i=(n=o.capabilities)==null?void 0:n.layer;i&&r.push(Ee(i))}return r.push(Ne(e)),de(r)}function Lt(){const e=new Map;return{get:t=>e.get(t),set:(t,r)=>{e.set(t,r)}}}const Dt={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function Ft(e,t,r,n){const o={...r,operation:{id:e.op.id},ctx:new pe};if(e.isMount){const i=e.mountHandler;if(!i)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${e.op.id}" has isMount=true but no mountHandler`);const s={operation:e.op,data:r.domainArgs,envelope:r.envelope,ctx:Lt(),transport:e.transport,signal:r.signal??new AbortController().signal},a={...n,fns:{[e.op.id]:()=>i(s)},schemas:{[e.op.id]:Dt}};return t(e.op.id,o,a)}return t(e.op.id,o,n)}exports.EventBus=le;exports.InstanceRegistry=ot;exports.LayerContext=pe;exports.UnionCodecError=g;exports.ValidateSchemasToken=$e;exports.WELL_KNOWN_TS_CODECS=Ae;exports.adaptCoreLayer=Ee;exports.assertNoSelfSubscription=ge;exports.buildContext=he;exports.buildFnTable=Ze;exports.buildMcpOutputSchema=vt;exports.buildOpPlan=Mt;exports.buildToolDescription=bt;exports.coerceQueryParams=Xe;exports.collectWithPhase=at;exports.createApiPackage=Je;exports.createInvoker=de;exports.createLogger=Ye;exports.createPackageInvoker=Ut;exports.createStream=it;exports.createUnionCodec=je;exports.dataParamNames=ue;exports.defineMiddleware=qe;exports.describeParams=be;exports.dispatch=fe;exports.dispatchForPlan=Ft;exports.drainStream=st;exports.isApiStream=ct;exports.makeValidateLayer=Ne;exports.needsEnvelopeField=ce;exports.readUseOptions=Pt;exports.readUsePlugins=Tt;exports.tsHostBinding=wt;exports.validateLayer=rt;exports.wireObservers=ye;exports.wrapMcpStructuredContent=$t;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("ts-morph");require("node:fs");require("node:path");require("ts-json-schema-generator");const N=require("pino"),ke=require("ajv"),Ie=require("ajv-formats"),k="$apigen";class H extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}}function Ce(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new H(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);t.set(n.id,n)},resolve(n){for(const r of t.values())if(r.matches(n))return r},get(n){return t.get(n)},ids(){return[...t.keys()]},freeze(){const n=new Map(t),r={register(){throw new H("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(o){for(const i of n.values())if(i.matches(o))return i},get(o){return n.get(o)},ids(){return[...n.keys()]},freeze(){return r}};return r}}}const U="x-apigen-logical",D="x-apigen-codec",I="x-apigen-ctor",C="x-apigen-tojson",xe="0.1.0";function V(e,t){return{registry:e,resolve:n=>{throw new Error(`[apigen-logical] $ref "${n}" cannot be resolved in run-mode without a descriptor root. Supply a resolve() in the ctx override to handle $ref.`)},seen:new WeakSet,path:"",mode:"strict",...t}}function v(e,t,n){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return v(e,a,n)}const i=t.oneOf;if(Array.isArray(i)){const a=se(e,i,t);return v(e,a,n)}const s=t.type;if(s==="array"){if(!Array.isArray(e))return A(e,t,n);const a=t.items;if(!a)return e.map(c=>w(c));const f=n.path;return Array.isArray(a)?e.map((c,u)=>{const p=a[u];return p===void 0?w(c):v(c,p,{...n,path:`${f}/${u}`})}):e.map((c,u)=>v(c,a,{...n,path:`${f}/${u}`}))}if(s==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return A(e,t,n);const a=t.properties;if(!a)return w(e);const f=n.path,c={};for(const[u,p]of Object.entries(a)){const d=e[u];d!==void 0&&(c[u]=v(d,p,{...n,path:`${f}/${u}`}))}return c}return s==null?A(e,t,n):w(e)}function $(e,t,n){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return $(e,a,n)}const i=t.oneOf;if(Array.isArray(i)){const a=se(e,i,t);return $(e,a,n)}const s=t.type;if(s==="array"){if(!Array.isArray(e))return e;const a=t.items;if(!a)return e;const f=n.path;return Array.isArray(a)?e.map((c,u)=>{const p=a[u];return p===void 0?c:$(c,p,{...n,path:`${f}/${u}`})}):e.map((c,u)=>$(c,a,{...n,path:`${f}/${u}`}))}if(s==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const f=n.path,c={};for(const[u,p]of Object.entries(a)){const d=e[u];d!==void 0&&(c[u]=$(d,p,{...n,path:`${f}/${u}`}))}return c}return s==null?Me(e,n):e}function se(e,t,n,r){const o=n.discriminator;if(o!=null&&o.propertyName){const i=e!==null&&typeof e=="object"?e[o.propertyName]:void 0;if(typeof i=="string"&&o.mapping){const s=o.mapping[i];if(s){const a=t.find(f=>f.$ref===s);if(a)return a}}}return t[0]??{}}function A(e,t,n){for(const r of n.registry.ids()){const o=n.registry.get(r);if(o)try{const i=o.encode(e,o.schema,n);return{[k]:r,v:i}}catch{}}return w(e)}function Me(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&k in e){const n=e,r=n[k],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}return e}function w(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(w);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=w(r));return t}return null}function Te(e){return{encode(t,n,r){const o=V(e,r);return v(t,n,o)},decode(t,n,r){const o=V(e,r);return $(t,n,o)}}}const L={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},encode(e,t,n){return e.toISOString()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${n.path}", got ${typeof e}`);return new Date(String(e))}if(n.mode==="strict"&&Number.isNaN(new Date(e).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${n.path}": ${JSON.stringify(e)}`);return new Date(e)}},R={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},encode(e,t,n){return String(e)},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${n.path}", got ${typeof e}`);try{return BigInt(Math.trunc(Number(e)))}catch{return BigInt(0)}}if(n.mode==="strict")return BigInt(e);if(/^-?\d+$/.test(e))try{return BigInt(e)}catch{return BigInt(0)}return BigInt(0)}},F={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(e){return e.type==="string"&&e.format==="decimal"},encode(e,t,n){return e},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e)}if(n.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(e))throw new TypeError(`[decimal] wire value "${e}" at "${n.path}" is not a valid decimal string`);return e}},q={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},encode(e,t,n){return Buffer.from(e).toString("base64")},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${n.path}", got ${typeof e}`);return new Uint8Array(0)}if(n.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(e))throw new TypeError(`[byte] wire value at "${n.path}" is not standard base64 (format:byte): "${e}"`);return new Uint8Array(Buffer.from(e,"base64"))}},Pe=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,K={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(e){return e.type==="string"&&e.format==="uuid"},encode(e,t,n){return e.toLowerCase()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e).toLowerCase()}if(n.mode==="strict"&&!Pe.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},x="NaN",M="Infinity",T="-Infinity",Ue=new Set([x,M,T]),B={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},encode(e,t,n){return Number.isNaN(e)?x:e===1/0?M:e===-1/0?T:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===x)return NaN;if(e===M)return 1/0;if(e===T)return-1/0;const r=Number(e);if(!Number.isNaN(r))return r}if(n.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(e)}. Expected a number or one of ${[...Ue].join(", ")}.`);return NaN}},De=[L,R,F,q,K,B];function Le(e,t={}){for(const n of De)e.register(n,{override:t.override??!1})}L.id,R.id,F.id,q.id,K.id,B.id;const ae=Ce();Le(ae);const ce=Te(ae.freeze());function ue(e,t){var r;const n=((r=e.input)==null?void 0:r.properties)??{};return t in n}function fe(e){var n,r;const t=(r=(n=e.input)==null?void 0:n.properties)==null?void 0:r.data;return Object.keys((t==null?void 0:t.properties)??{})}function Re(e,t){var o,i,s;const n=(s=(i=(o=e.input)==null?void 0:o.properties)==null?void 0:i.data)==null?void 0:s.properties,r=n==null?void 0:n[t];return r!==void 0?r:void 0}function Fe(e,t){return t===void 0||e===void 0?e:ce.decode(e,t)}function _(e,t){const n=t.output;return!n||Object.keys(n).length===0?e:ce.encode(e,n)}async function pe(e,t,n,r,o,i){const a=fe(n).map(c=>Fe(i[c],Re(n,c)));if(ue(n,"session")&&t){const c=await t({session:o.session}),u=await e[r](c,...a);return _(u,n)}if(n.hasCtx){const c=t?await t(o):void 0,u=await e[r](c,...a);return _(u,n)}const f=await e[r](...a);return _(f,n)}class de{constructor(){this._map=new Map}set(t,n){this._map.set(t,n)}get(t){return this._map.get(t)}has(t){return this._map.has(t)}}function le(e=[]){return async function(n,r,o){const i=o.schemas[n];if(!i)throw new Error(`apigen/invoke: no schema found for operation "${n}"`);const s=()=>pe(o.fns,o.createClient,i,n,r.envelope,r.domainArgs);return e.reduceRight((f,c)=>()=>c(r,f),s)()}}function qe(e){return e}class ye{constructor(){this.handlers=new Map}on(t,n){const r=this.handlers.get(t)??[];return this.handlers.set(t,[...r,n]),()=>this.off(t,n)}off(t,n){const r=this.handlers.get(t);if(!r)return;const o=r.filter(i=>i!==n);o.length===0?this.handlers.delete(t):this.handlers.set(t,o)}clear(){this.handlers.clear()}async emit(t){for(const[n,r]of this.handlers)if(Ke(n,t))for(const o of r)await o(t)}}function Ke(e,t){const[n,r,o]=e.split(":");return!(n!=="*"&&n!==t.module||r&&r!=="*"&&r!==t.method||o&&o!=="*"&&o!==t.lifecycle)}function me(e,t){for(const n of e)if(n.eventMapping)for(const[r,o]of Object.entries(n.eventMapping))t.on(r,o)}async function he(e,t,n){let r={...t};for(const o of e)if(o.createContext){await n.emit({module:o.id,method:"createContext",lifecycle:"start",ctx:r});try{const i=await o.createContext(r);r={...r,...i},await n.emit({module:o.id,method:"createContext",lifecycle:"complete",ctx:r})}catch(i){throw await n.emit({module:o.id,method:"createContext",lifecycle:"error",ctx:r,error:i}),i}}return r}function z(e,t){const n=new Set,r=[e];for(;r.length>0;){const o=r.pop();if(!o||n.has(o))continue;n.add(o);const i=o.$ref;if(typeof i=="string"){if(t){const p=t[i];if(!p){const d=Object.keys(t).join(", ")||"(none)";throw new Error(`[apigen-logical] $ref "${i}" cannot be resolved. Available $defs: ${d}`)}r.push(p)}continue}const s=o.oneOf;if(Array.isArray(s))for(const p of s)typeof p=="object"&&p!==null&&r.push(p);const a=o.properties;if(a)for(const p of Object.values(a))r.push(p);const f=o.items;if(Array.isArray(f))for(const p of f)typeof p=="object"&&p!==null&&r.push(p);else typeof f=="object"&&f!==null&&r.push(f);const c=o.additionalProperties;typeof c=="object"&&c!==null&&r.push(c);const u=o.propertyNames;typeof u=="object"&&u!==null&&r.push(u)}}const G=new Set(["string","number","boolean","integer"]);function Be(e){if(typeof e!="object"||e===null)return!1;const t=e;if(t.$ref!==void 0||t.oneOf||t.anyOf||t.allOf)return!1;const{type:n}=t;return typeof n=="string"?G.has(n):Array.isArray(n)?n.every(r=>G.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function We(e){if(!e||typeof e!="object")return!1;const t=e.properties;return t===void 0||typeof t!="object"||t===null?!1:Object.values(t).every(Be)}function He(e){const t={},n=r=>{for(const o of["definitions","$defs"]){const i=r[o];if(i)for(const[s,a]of Object.entries(i)){const f=s.startsWith("#/")?s:`#/${o}/${s}`;t[f]=a}}};for(const r of Object.values(e.schemas))n(r.input),n(r.output);if(Object.keys(t).length!==0)for(const[r,o]of Object.entries(e.schemas))try{z(o.input,t),z(o.output,t)}catch(i){throw new Error(`[apigen-core-client] Schema validation failed for function "${r}": ${i.message}`)}}function Ve(e,t){const n=['apigen calling convention: all domain parameters go inside a "data" envelope โ€” e.g. { "data": { ... } }'+(t?".":" (an empty object for this zero-parameter tool).")];return e.length>0&&n.push(`Field(s) ${e.map(r=>`"${r}"`).join(", ")} are transport-level envelope metadata, NOT domain data โ€” do not nest them under "data". Over MCP they are read from arguments._meta["x-<pluginId>-<field>"] (default pluginId "adhd"); see @adhd/apigen-engine-naming's envelopeMetaKey/envelopeCliFlag/envelopeEnvVar for the HTTP-header / CLI-flag / env-var equivalents.`),n.join(" ")}function ze(e,t,n){He(e);const r={};for(const[o,i]of Object.entries(e.schemas)){const s=(n==null?void 0:n[o])??{},a=i.input.properties??{},f=i.input.required??[],c={},u=[],p={};for(const h of t)if(h.envelope&&s[h.id]!==!1)for(const[b,Se]of Object.entries(h.envelope))c[b]=Se,p[b]=h.id,u.includes(b)||u.push(b);const d={type:"object",properties:a,additionalProperties:!1,...f.length>0?{required:f}:{}},y=i.safe===!0||We(i.input),l=i.input.definitions,m=i.input.$defs;r[o]={input:{type:"object",properties:{...c,data:d},required:[...u,...f.length>0?["data"]:[]],additionalProperties:!1,description:Ve(Object.keys(c),Object.keys(a).length>0),...l?{definitions:l}:{},...m?{$defs:m}:{}},output:i.output,...i.hasCtx?{hasCtx:!0}:{},"x-apigen-safe":y,...Object.keys(p).length>0?{"x-apigen-envelope":p}:{}}}return r}const Ge={"decimal.js":"Decimal"};function Je(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Ge).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Je(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));class P extends Error{constructor(t){super(t),this.name="ConfigurationError"}}function ge(e){for(const t of e)for(const n of Object.keys(t.eventMapping??{})){const[r]=n.split(":");if(r!=="*"&&r===t.id)throw new P(`Middleware "${t.id}" subscribes to its own events via "${n}". This would cause infinite recursion.`)}}function Ye(e){const{domainSchemas:t,middlewares:n,overrides:r={},strict:o=!1}=e;ge(n);for(const c of Object.keys(r))if(!(c in t.schemas)){const u=`Override key "${c}" not found in domain schemas.`;if(o)throw new P(u);console.warn("[apigen-runtime]",u)}const i=new Set(n.map(c=>c.id));for(const[c,u]of Object.entries(r))for(const p of Object.keys(u??{}))if(!i.has(p)){const d=`Override key "${c}.${p}" does not match any declared middleware id.`;if(o)throw new P(d);console.warn("[apigen-runtime]",d)}const s=ze(t,n,r),a=new ye;return me(n,a),{schemas:s,createClient:async c=>he(n,c,a),dispose:()=>a.clear()}}function Qe(e={}){const t=e.level??"info",n=typeof e.destination=="string"&&e.destination.length>0,r=!n&&!!process.stderr.isTTY,o=e.format??(r?"pretty":"json"),i={level:t};if(o==="pretty")return i.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:e.destination,mkdir:!0}:{destination:2}}},N(i);const s=n?N.destination({dest:e.destination,mkdir:!0,sync:!0}):N.destination(2);return N(i,s)}function we(e){return e?e.type==="array"?`${we(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function be(e){var a;const n=(a=((e==null?void 0:e.input)??{}).properties)==null?void 0:a.data,r=(n==null?void 0:n.properties)??{},o=new Set((n==null?void 0:n.required)??[]),i=Object.entries(r).map(([f,c])=>({name:f,type:we(c),required:o.has(f)})),s=i.map(f=>`${f.name}${f.required?"":"?"}: ${f.type}`).join(", ");return{params:i,text:s}}function Xe(e){let t;return Array.isArray(e)?t=e:e?t=[e]:t=[],t.find(n=>n==="number"||n==="integer"||n==="boolean")}function Ze(e,t){var i,s;const r=((s=(i=((t==null?void 0:t.input)??{}).properties)==null?void 0:i.data)==null?void 0:s.properties)??{},o={...e};for(const[a,f]of Object.entries(r)){const c=o[a];if(typeof c!="string")continue;const u=Xe(f==null?void 0:f.type);if(u==="number"||u==="integer"){const p=Number(c);!Number.isNaN(p)&&c.trim()!==""&&(o[a]=p)}else u==="boolean"&&(c==="true"?o[a]=!0:c==="false"&&(o[a]=!1))}return o}const J=new Set(["default","module.exports","__esModule"]);function et(e){const t={},n=(r,o)=>{for(const[i,s]of Object.entries(r))if(typeof s=="function"){!J.has(i)&&!(i in t)&&(t[i]=s);const a=s.name;a&&!(a in t)&&(t[a]=s)}else s&&typeof s=="object"&&o<2&&J.has(i)&&n(s,o+1)};return n(e,0),t}const tt=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];class W extends Error{constructor(t,n,r){super(n),this.name="ApiError",this.code=t,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const t={code:this.code,message:this.message};return this.details!==void 0&&(t.details=this.details),t}}function nt(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&tt.includes(e.code)&&typeof e.toJSON=="function"}function Y(e,t,n=0){return e==="before-first-chunk"?{phase:e,error:t}:{phase:e,error:t,chunksDelivered:n}}const O=new ke({allErrors:!0});Ie(O);for(const e of[U,D,I,C,"discriminator"])O.addKeyword({keyword:e,valid:!0});O.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function ve(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}const rt=async(e,t)=>{const n=e.ctx.get($e);if(n===void 0)return t();const r=e.operation.id,o=n[r];if(o===void 0)return t();const i={data:e.domainArgs,...e.envelope},s=O.compile(o.input);if(!s(i)){const f=s.errors??[];throw new W("invalid_argument",`Validation failed: ${ve(f)}`,f)}return t()},$e=Symbol("ValidateSchemasToken");function Oe(e){return async function(n,r){const o=n.operation.id,i=e[o];if(i===void 0)return r();const s={data:n.domainArgs,...n.envelope},a=O.compile(i.input);if(!a(s)){const c=a.errors??[];throw new W("invalid_argument",`Validation failed: ${ve(c)}`,c)}return r()}}function ot(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}class it{constructor(t={}){var r,o;this._store=new Map,this._sweeper=null,this._defaultTtlMs=t.defaultTtlMs;let n=null;t.sweepIntervalMs===0?n=null:t.sweepIntervalMs!==void 0?n=t.sweepIntervalMs:this._defaultTtlMs!==void 0?n=Math.max(1e3,Math.floor(this._defaultTtlMs/4)):n=null,n!==null&&n>0&&(this._sweeper=setInterval(()=>this._sweep(),n),(o=(r=this._sweeper).unref)==null||o.call(r))}create(t,n=[],r){const o=new t(...n),i=ot(),s=r??this._defaultTtlMs,a=s!==void 0?Date.now()+s:null;return this._store.set(i,{instance:o,expiresAt:a}),{instanceId:i}}get(t){const n=this._store.get(t);if(!n)throw new Error(`[instance-registry] Unknown instanceId: "${t}"`);if(n.expiresAt!==null&&Date.now()>n.expiresAt)throw this._evict(t,n),new Error(`[instance-registry] Instance "${t}" has expired`);return n.instance}async dispatch(t,n,r=[]){const o=this.get(t),i=o[n];if(typeof i!="function")throw new Error(`[instance-registry] Method "${n}" not found on instance "${t}"`);return i.call(o,...r)}async dispose(t){const n=this._store.get(t);n&&(this._store.delete(t),await E(n.instance))}async disposeAll(){this._sweeper!==null&&(clearInterval(this._sweeper),this._sweeper=null);const t=[...this._store.entries()];this._store.clear(),await Promise.all(t.map(([,n])=>E(n.instance)))}get size(){return this._store.size}_sweep(){const t=Date.now();for(const[n,r]of this._store)r.expiresAt!==null&&t>r.expiresAt&&this._evict(n,r)}_evict(t,n){this._store.delete(t),E(n.instance)}}async function E(e){if(e!==null&&typeof e=="object"&&"dispose"in e){const t=e.dispose;typeof t=="function"&&await t.call(e)}}function st(e){const{produce:t,signal:n}=e,r=n??new AbortController().signal;return{[Symbol.asyncIterator](){const o=t(r);return{async next(){return r.aborted?(await o.return(void 0),{done:!0,value:void 0}):o.next()},async return(i){return await o.return(i),{done:!0,value:void 0}},async throw(i){return await o.throw(i),{done:!0,value:void 0}}}}}}async function at(e){const t=[];for await(const n of e)t.push(n);return t}async function ct(e){const t=[];try{for await(const n of e)t.push(n);return{ok:!0,chunks:t}}catch(n){const r=nt(n)?n:new W("internal",n instanceof Error?n.message:String(n));return t.length===0?{ok:!1,carrier:Y("before-first-chunk",r)}:{ok:!1,carrier:Y("after-first-chunk",r,t.length)}}}function ut(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}class g extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}}function S(e){const t=e.discriminator;if(t===null||typeof t!="object"||Array.isArray(t))return;const n=t;if(typeof n.propertyName!="string")return;const r=n.mapping;if(!(r===null||typeof r!="object"||Array.isArray(r)))return{propertyName:n.propertyName,mapping:r}}function Ne(e,t){const n=e[D];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function ft(e,t,n){const r=Ne(t,n);return r?r.encode(e,t,n):e}function pt(e,t,n){const r=Ne(t,n);return r?r.decode(e,t,n):e}function je(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[U]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:S(r)!==void 0},encode(r,o,i){const s=S(o);if(!s)throw new g("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${i.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:f}=s,c=r[a];if(c==null)throw new g("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${i.path}" is missing the discriminator property "${a}".`);const u=String(c),p=f[u];if(!p)throw new g("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${u}" at "${i.path}" is not in the mapping (known: ${Object.keys(f).join(", ")}).`);const d=i.resolve(p);return ft(r,d,{...i,path:`${i.path}[${u}]`})},decode(r,o,i){if(r===null||typeof r!="object"||Array.isArray(r)){let l;throw r===null?l="null":Array.isArray(r)?l="array":l=typeof r,new g("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const s=r,a=S(o);if(!a)throw new g("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${i.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:f,mapping:c}=a,u=s[f];if(u==null)throw new g("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${i.path}" is missing the discriminator property "${f}".`);const p=String(u),d=c[p];if(!d)throw new g("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${p}" on the wire at "${i.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const y=i.resolve(d);return pt(r,y,{...i,path:`${i.path}[${p}]`})}}}const dt="x-apigen-instances";class j extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}}function Q(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function lt(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function X(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function yt(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function mt(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[U]==="nominal"?!0:o[D]===t},encode(o,i,s){if(o===null||typeof o!="object")return o;if(s.seen.has(o)){if(s.mode==="strict")throw new j("E_NOMINAL_CYCLE",`[${t}] cycle detected at "${s.path}": a nominal instance references itself. Strict mode rejects cycles (DESIGN ยง8.3); break the cycle or use 'lossy' mode.`);return null}s.seen.add(o);try{const a=Q(i),f=typeof i[C]=="string"?i[C]:"toJSON",c=o[f];if(typeof c=="function"){const l=c.call(o);if(l!==null&&typeof l=="object"&&!Array.isArray(l)){const m={};for(const[h,b]of Object.entries(l))m[h]=X(b,a[h],{...s,path:`${s.path}/${h}`});return m}return l}const u={},p=Object.keys(a),d=o,y=p.length>0?p:Object.keys(d);for(const l of y){const m=d[l];m!==void 0&&(u[l]=X(m,a[l],{...s,path:`${s.path}/${l}`}))}return u}finally{s.seen.delete(o)}},decode(o,i,s){if(o===null||typeof o!="object"||Array.isArray(o)){let u;throw o===null?u="null":Array.isArray(o)?u="array":u=typeof o,new j("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${u}.`)}const a=o;for(const u of lt(i))if(!(u in a))throw new j("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${u}" missing on the wire at "${s.path}".`);if(i[dt]===!1)throw new j("E_NOMINAL_NONRECONSTRUCTABLE",`[${t}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);const f=Q(i),c={};for(const[u,p]of Object.entries(a))c[u]=yt(p,f[u],{...s,path:`${s.path}/${u}`});if(r){const u=typeof i[I]=="string"?i[I]:"fromJSON",p=r[u];if(typeof p=="function")return p.call(r,c);const d=r;return new d(c)}return c}}}const Ae=[L,R,F,q,K,B],ht={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},Z=mt({id:"ts.NominalSentinel",schema:ht}),gt={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},ee=je({id:"ts.UnionSentinel",schema:gt});function wt(){const e=[...Ae.map(t=>[t.id,t]),[Z.id,Z],[ee.id,ee]];return Object.freeze(new Map(e))}const bt=Object.freeze({host:"ts",logicalTypeVersion:xe,codecs:wt()});function vt(e,t,n){var i;const r=typeof((i=t==null?void 0:t.input)==null?void 0:i.description)=="string"?t.input.description:void 0,o=[n,r].filter(s=>typeof s=="string"&&s.length>0);return o.length>0?o.join(" โ€” "):e}function $t(e){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0)return{outputSchema:void 0,wrapped:!1};const t=e;return t.type==="object"?{outputSchema:t,wrapped:!1}:{outputSchema:{type:"object",properties:{result:t},required:["result"]},wrapped:!0}}function Ot(e,t){return e?{result:t}:t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}const te=new Set(["string","number","boolean","integer"]);function Nt(e){if(typeof e!="object"||e===null)return!1;const t=e;if(t.$ref!==void 0||t.oneOf||t.anyOf||t.allOf)return!1;const{type:n}=t;return typeof n=="string"?te.has(n):Array.isArray(n)?n.every(r=>te.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function jt(e){if(!e||typeof e!="object")return!1;const t=e.properties;return t===void 0||typeof t!="object"||t===null?!1:Object.values(t).every(Nt)}const At={"decimal.js":"Decimal"};function _t(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(At).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${_t(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function ne(e){return e.words.join("-")}function re(e){return e.words.map(Ct).join("")}function oe(e){return e.words.join("_")}function Et(e,t={}){var n,r;const o=[e.namespace,...e.path],i=e.safe||jt(e.input)?"GET":"POST",s=((r=(n=t.http)==null?void 0:n.verb)==null?void 0:r[e.id])??i,a="/"+o.map(y=>ne(y)).join("/"),f=o.map(y=>oe(y)).join("_"),c=o.map(y=>oe(y)).slice(0,-1).join("."),u=re(o[o.length-2]??o[0]),p=re(o[o.length-1]),d=o.map(y=>ne(y));return{http:{verb:s,route:a},mcp:{name:f},grpc:{package:c,service:u,method:p},cli:{path:d}}}function St(e,t){return`x-${e}-${t}`}function kt(e,t){return`--${e}-${t}`}function It(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function Ct(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function _e(e){return e.anyOf??e.oneOf}function xt(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=_e(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="array"||r.type==="object")}return!1}function Mt(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=_e(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function Tt(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function Pt(e){var o,i;const t=(i=(o=e.input)==null?void 0:o.properties)==null?void 0:i.data,n=(t==null?void 0:t.properties)??{},r=(t==null?void 0:t.required)??[];return{props:n,required:r}}function ie(e){return typeof e.handler=="function"}function Ut(e){var o;const t=((o=e.input)==null?void 0:o.properties)??{},n=e["x-apigen-envelope"],r=[];for(const i of Object.keys(t)){if(i==="data")continue;const s=(n==null?void 0:n[i])??"adhd",a=St(s,i);r.push({field:i,pluginId:s,httpHeader:a,mcpMetaKey:a,cliFlag:kt(s,i),envVar:It(s,i)})}return r}function Dt(e,t){const n=new Map,{props:r}=Pt(e);for(const[o,i]of Object.entries(r)){let s="string";Mt(i)?s="boolean":xt(i)&&(s="json"),n.set(Tt(o),{camelKey:o,kind:"domain",valueKind:s})}for(const o of t){const i=o.cliFlag.replace(/^--/,"");n.set(i,{camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar})}return n}function Lt(e){const{op:t,schema:n,transport:r,projection:o}=e,i=Et(t,o),s=n?Ut(n):[],a=n?Dt(n,s):new Map,f=n?be(n).params:void 0,c={op:t,transport:r,http:i.http,mcp:i.mcp,cli:i.cli,grpc:i.grpc,params:f,envelope:s,cliFlags:a,streaming:t.streaming,isMount:ie(t)};if(ie(t)){const u=t.handler;c.mountHandler=async p=>u(p)}return c}function Rt(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function Ft(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function Ee(e){return async function(n,r){const o=Object.assign(n,{data:n.domainArgs});return await e.layer(o,r)}}function qt(e,t){var r;const n=[];for(const o of t){const i=(r=o.capabilities)==null?void 0:r.layer;i&&n.push(Ee(i))}return n.push(Oe(e)),le(n)}function Kt(){const e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}const Bt={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function Wt(e,t,n,r){const o={...n,operation:{id:e.op.id},ctx:new de};if(e.isMount){const i=e.mountHandler;if(!i)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${e.op.id}" has isMount=true but no mountHandler`);const s={operation:e.op,data:n.domainArgs,envelope:n.envelope,ctx:Kt(),transport:e.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[e.op.id]:()=>i(s)},schemas:{[e.op.id]:Bt}};return t(e.op.id,o,a)}return t(e.op.id,o,r)}exports.EventBus=ye;exports.InstanceRegistry=it;exports.LayerContext=de;exports.UnionCodecError=g;exports.ValidateSchemasToken=$e;exports.WELL_KNOWN_TS_CODECS=Ae;exports.adaptCoreLayer=Ee;exports.assertNoSelfSubscription=ge;exports.buildContext=he;exports.buildFnTable=et;exports.buildMcpOutputSchema=$t;exports.buildOpPlan=Lt;exports.buildToolDescription=vt;exports.coerceQueryParams=Ze;exports.collectWithPhase=ct;exports.createApiPackage=Ye;exports.createInvoker=le;exports.createLogger=Qe;exports.createPackageInvoker=qt;exports.createStream=st;exports.createUnionCodec=je;exports.dataParamNames=fe;exports.defineMiddleware=qe;exports.describeParams=be;exports.dispatch=pe;exports.dispatchForPlan=Wt;exports.drainStream=at;exports.isApiStream=ut;exports.makeValidateLayer=Oe;exports.needsEnvelopeField=ue;exports.readUseOptions=Ft;exports.readUsePlugins=Rt;exports.tsHostBinding=bt;exports.validateLayer=rt;exports.wireObservers=me;exports.wrapMcpStructuredContent=Ot;
package/index.mjs CHANGED
@@ -2,11 +2,11 @@ import "ts-morph";
2
2
  import "node:fs";
3
3
  import "node:path";
4
4
  import "ts-json-schema-generator";
5
- import j from "pino";
5
+ import N from "pino";
6
6
  import ye from "ajv";
7
7
  import me from "ajv-formats";
8
- const k = "$apigen";
9
- class z extends Error {
8
+ const I = "$apigen";
9
+ class H extends Error {
10
10
  constructor(t) {
11
11
  super(t), this.code = "E_DUP_CODEC", this.name = "CodecRegistryError";
12
12
  }
@@ -16,7 +16,7 @@ function he(e) {
16
16
  return {
17
17
  register(n, r) {
18
18
  if (t.has(n.id) && !(r != null && r.override))
19
- throw new z(
19
+ throw new H(
20
20
  `E_DUP_CODEC: a codec is already registered for id "${n.id}"`
21
21
  );
22
22
  t.set(n.id, n);
@@ -35,7 +35,7 @@ function he(e) {
35
35
  freeze() {
36
36
  const n = new Map(t), r = {
37
37
  register() {
38
- throw new z(
38
+ throw new H(
39
39
  "E_DUP_CODEC: registry is frozen and cannot accept new codecs"
40
40
  );
41
41
  },
@@ -58,8 +58,8 @@ function he(e) {
58
58
  }
59
59
  };
60
60
  }
61
- const U = "x-apigen-logical", D = "x-apigen-codec", I = "x-apigen-ctor", x = "x-apigen-tojson", ge = "0.1.0";
62
- function H(e, t) {
61
+ const U = "x-apigen-logical", D = "x-apigen-codec", k = "x-apigen-ctor", x = "x-apigen-tojson", ge = "0.1.0";
62
+ function V(e, t) {
63
63
  return {
64
64
  registry: e,
65
65
  resolve: (n) => {
@@ -84,7 +84,7 @@ function v(e, t, n) {
84
84
  }
85
85
  const i = t.oneOf;
86
86
  if (Array.isArray(i)) {
87
- const a = ie(e, i, t);
87
+ const a = se(e, i, t);
88
88
  return v(e, a, n);
89
89
  }
90
90
  const s = t.type;
@@ -131,7 +131,7 @@ function $(e, t, n) {
131
131
  }
132
132
  const i = t.oneOf;
133
133
  if (Array.isArray(i)) {
134
- const a = ie(e, i, t);
134
+ const a = se(e, i, t);
135
135
  return $(e, a, n);
136
136
  }
137
137
  const s = t.type;
@@ -167,7 +167,7 @@ function $(e, t, n) {
167
167
  }
168
168
  return s == null ? we(e, n) : e;
169
169
  }
170
- function ie(e, t, n, r) {
170
+ function se(e, t, n, r) {
171
171
  const o = n.discriminator;
172
172
  if (o != null && o.propertyName) {
173
173
  const i = e !== null && typeof e == "object" ? e[o.propertyName] : void 0;
@@ -188,15 +188,15 @@ function A(e, t, n) {
188
188
  if (o)
189
189
  try {
190
190
  const i = o.encode(e, o.schema, n);
191
- return { [k]: r, v: i };
191
+ return { [I]: r, v: i };
192
192
  } catch {
193
193
  }
194
194
  }
195
195
  return w(e);
196
196
  }
197
197
  function we(e, t) {
198
- if (e !== null && typeof e == "object" && !Array.isArray(e) && k in e) {
199
- const n = e, r = n[k], o = t.registry.get(r);
198
+ if (e !== null && typeof e == "object" && !Array.isArray(e) && I in e) {
199
+ const n = e, r = n[I], o = t.registry.get(r);
200
200
  if (o)
201
201
  return o.decode(n.v, o.schema, t);
202
202
  }
@@ -218,11 +218,11 @@ function w(e) {
218
218
  function be(e) {
219
219
  return {
220
220
  encode(t, n, r) {
221
- const o = H(e, r);
221
+ const o = V(e, r);
222
222
  return v(t, n, o);
223
223
  },
224
224
  decode(t, n, r) {
225
- const o = H(e, r);
225
+ const o = V(e, r);
226
226
  return $(t, n, o);
227
227
  }
228
228
  };
@@ -389,7 +389,7 @@ const L = {
389
389
  );
390
390
  return NaN;
391
391
  }
392
- }, Ne = [
392
+ }, je = [
393
393
  L,
394
394
  R,
395
395
  F,
@@ -397,8 +397,8 @@ const L = {
397
397
  B,
398
398
  q
399
399
  ];
400
- function je(e, t = {}) {
401
- for (const n of Ne)
400
+ function Ne(e, t = {}) {
401
+ for (const n of je)
402
402
  e.register(n, { override: t.override ?? !1 });
403
403
  }
404
404
  L.id, // 'date-time'
@@ -407,9 +407,9 @@ F.id, // 'decimal'
407
407
  K.id, // 'byte'
408
408
  B.id, // 'uuid'
409
409
  q.id;
410
- const se = he();
411
- je(se);
412
- const ae = be(se.freeze());
410
+ const ae = he();
411
+ Ne(ae);
412
+ const ce = be(ae.freeze());
413
413
  function Oe(e, t) {
414
414
  var r;
415
415
  const n = ((r = e.input) == null ? void 0 : r.properties) ?? {};
@@ -426,11 +426,11 @@ function _e(e, t) {
426
426
  return r !== void 0 ? r : void 0;
427
427
  }
428
428
  function Ee(e, t) {
429
- return t === void 0 || e === void 0 ? e : ae.decode(e, t);
429
+ return t === void 0 || e === void 0 ? e : ce.decode(e, t);
430
430
  }
431
431
  function _(e, t) {
432
432
  const n = t.output;
433
- return !n || Object.keys(n).length === 0 ? e : ae.encode(e, n);
433
+ return !n || Object.keys(n).length === 0 ? e : ce.encode(e, n);
434
434
  }
435
435
  async function Se(e, t, n, r, o, i) {
436
436
  const a = Ae(n).map(
@@ -447,7 +447,7 @@ async function Se(e, t, n, r, o, i) {
447
447
  const f = await e[r](...a);
448
448
  return _(f, n);
449
449
  }
450
- class ke {
450
+ class Ie {
451
451
  constructor() {
452
452
  this._map = /* @__PURE__ */ new Map();
453
453
  }
@@ -462,7 +462,7 @@ class ke {
462
462
  return this._map.has(t);
463
463
  }
464
464
  }
465
- function Ie(e = []) {
465
+ function ke(e = []) {
466
466
  return async function(n, r, o) {
467
467
  const i = o.schemas[n];
468
468
  if (!i)
@@ -483,7 +483,7 @@ function Ie(e = []) {
483
483
  )();
484
484
  };
485
485
  }
486
- function Et(e) {
486
+ function Ct(e) {
487
487
  return e;
488
488
  }
489
489
  class xe {
@@ -609,7 +609,7 @@ function Pe(e) {
609
609
  const { type: n } = t;
610
610
  return typeof n == "string" ? G.has(n) : Array.isArray(n) ? n.every((r) => G.has(r) || r === "null") : Array.isArray(t.enum) && t.enum.length > 0 ? t.enum.every((r) => ["string", "number", "boolean"].includes(typeof r)) : !1;
611
611
  }
612
- function ce(e) {
612
+ function Ue(e) {
613
613
  if (!e || typeof e != "object")
614
614
  return !1;
615
615
  const t = e.properties;
@@ -617,7 +617,7 @@ function ce(e) {
617
617
  Pe
618
618
  );
619
619
  }
620
- function Ue(e) {
620
+ function De(e) {
621
621
  const t = {}, n = (r) => {
622
622
  for (const o of ["definitions", "$defs"]) {
623
623
  const i = r[o];
@@ -640,7 +640,7 @@ function Ue(e) {
640
640
  );
641
641
  }
642
642
  }
643
- function De(e, t) {
643
+ function Le(e, t) {
644
644
  const n = [
645
645
  'apigen calling convention: all domain parameters go inside a "data" envelope โ€” e.g. { "data": { ... } }' + (t ? "." : " (an empty object for this zero-parameter tool).")
646
646
  ];
@@ -648,21 +648,21 @@ function De(e, t) {
648
648
  `Field(s) ${e.map((r) => `"${r}"`).join(", ")} are transport-level envelope metadata, NOT domain data โ€” do not nest them under "data". Over MCP they are read from arguments._meta["x-<pluginId>-<field>"] (default pluginId "adhd"); see @adhd/apigen-engine-naming's envelopeMetaKey/envelopeCliFlag/envelopeEnvVar for the HTTP-header / CLI-flag / env-var equivalents.`
649
649
  ), n.join(" ");
650
650
  }
651
- function Le(e, t, n) {
652
- Ue(e);
651
+ function Re(e, t, n) {
652
+ De(e);
653
653
  const r = {};
654
654
  for (const [o, i] of Object.entries(e.schemas)) {
655
655
  const s = (n == null ? void 0 : n[o]) ?? {}, a = i.input.properties ?? {}, f = i.input.required ?? [], c = {}, u = [], p = {};
656
656
  for (const h of t)
657
657
  if (h.envelope && s[h.id] !== !1)
658
- for (const [b, le] of Object.entries(h.envelope))
659
- c[b] = le, p[b] = h.id, u.includes(b) || u.push(b);
658
+ for (const [b, de] of Object.entries(h.envelope))
659
+ c[b] = de, p[b] = h.id, u.includes(b) || u.push(b);
660
660
  const l = {
661
661
  type: "object",
662
662
  properties: a,
663
663
  additionalProperties: !1,
664
664
  ...f.length > 0 ? { required: f } : {}
665
- }, y = i.safe === !0 || ce(i.input), d = i.input.definitions, m = i.input.$defs;
665
+ }, y = i.safe === !0 || Ue(i.input), d = i.input.definitions, m = i.input.$defs;
666
666
  r[o] = {
667
667
  input: {
668
668
  type: "object",
@@ -675,7 +675,7 @@ function Le(e, t, n) {
675
675
  // field or the "data" wrapper โ€” no silently-ignored junk params.
676
676
  additionalProperties: !1,
677
677
  // BUG-APIGEN-020: document the envelope/data calling convention inline.
678
- description: De(
678
+ description: Le(
679
679
  Object.keys(c),
680
680
  Object.keys(a).length > 0
681
681
  ),
@@ -695,13 +695,13 @@ function Le(e, t, n) {
695
695
  }
696
696
  return r;
697
697
  }
698
- const Re = {
698
+ const Fe = {
699
699
  "decimal.js": "Decimal"
700
700
  };
701
- function Fe(e) {
701
+ function Ke(e) {
702
702
  return e.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
703
703
  }
704
- Object.entries(Re).map(([e, t]) => ({
704
+ Object.entries(Fe).map(([e, t]) => ({
705
705
  // Matches: import("...{modSpec}...").<anyMemberName> (single or double quotes)
706
706
  // The module specifier appears inside an absolute path, so we allow any
707
707
  // characters between the quote and the specifier, and between the specifier
@@ -709,7 +709,7 @@ Object.entries(Re).map(([e, t]) => ({
709
709
  // โ€ฆ) is matched generically (`\w+`) rather than anchored to one spelling โ€”
710
710
  // see the doc comment above for why.
711
711
  pattern: new RegExp(
712
- `import\\(["'][^"']*${Fe(e)}[^"']*["']\\)\\.\\w+`,
712
+ `import\\(["'][^"']*${Ke(e)}[^"']*["']\\)\\.\\w+`,
713
713
  "g"
714
714
  ),
715
715
  key: t
@@ -719,7 +719,7 @@ class P extends Error {
719
719
  super(t), this.name = "ConfigurationError";
720
720
  }
721
721
  }
722
- function Ke(e) {
722
+ function Be(e) {
723
723
  for (const t of e)
724
724
  for (const n of Object.keys(t.eventMapping ?? {})) {
725
725
  const [r] = n.split(":");
@@ -729,14 +729,14 @@ function Ke(e) {
729
729
  );
730
730
  }
731
731
  }
732
- function St(e) {
732
+ function Mt(e) {
733
733
  const {
734
734
  domainSchemas: t,
735
735
  middlewares: n,
736
736
  overrides: r = {},
737
737
  strict: o = !1
738
738
  } = e;
739
- Ke(n);
739
+ Be(n);
740
740
  for (const c of Object.keys(r))
741
741
  if (!(c in t.schemas)) {
742
742
  const u = `Override key "${c}" not found in domain schemas.`;
@@ -753,14 +753,14 @@ function St(e) {
753
753
  throw new P(l);
754
754
  console.warn("[apigen-runtime]", l);
755
755
  }
756
- const s = Le(
756
+ const s = Re(
757
757
  t,
758
758
  n,
759
759
  r
760
760
  ), a = new xe();
761
761
  return Me(n, a), { schemas: s, createClient: async (c) => Te(n, c, a), dispose: () => a.clear() };
762
762
  }
763
- function kt(e = {}) {
763
+ function Tt(e = {}) {
764
764
  const t = e.level ?? "info", n = typeof e.destination == "string" && e.destination.length > 0, r = !n && !!process.stderr.isTTY, o = e.format ?? (r ? "pretty" : "json"), i = { level: t };
765
765
  if (o === "pretty")
766
766
  return i.transport = {
@@ -771,14 +771,14 @@ function kt(e = {}) {
771
771
  ignore: "pid,hostname",
772
772
  ...n ? { destination: e.destination, mkdir: !0 } : { destination: 2 }
773
773
  }
774
- }, j(i);
775
- const s = n ? j.destination({ dest: e.destination, mkdir: !0, sync: !0 }) : j.destination(2);
776
- return j(i, s);
774
+ }, N(i);
775
+ const s = n ? N.destination({ dest: e.destination, mkdir: !0, sync: !0 }) : N.destination(2);
776
+ return N(i, s);
777
777
  }
778
778
  function ue(e) {
779
779
  return e ? e.type === "array" ? `${ue(e.items)}[]` : e.enum ? "enum" : e.$ref ? String(e.$ref).split("/").pop() || "object" : e.anyOf || e.oneOf ? "union" : e.type ?? "object" : "unknown";
780
780
  }
781
- function Be(e) {
781
+ function qe(e) {
782
782
  var a;
783
783
  const n = (a = ((e == null ? void 0 : e.input) ?? {}).properties) == null ? void 0 : a.data, r = (n == null ? void 0 : n.properties) ?? {}, o = new Set((n == null ? void 0 : n.required) ?? []), i = Object.entries(r).map(([f, c]) => ({
784
784
  name: f,
@@ -787,18 +787,18 @@ function Be(e) {
787
787
  })), s = i.map((f) => `${f.name}${f.required ? "" : "?"}: ${f.type}`).join(", ");
788
788
  return { params: i, text: s };
789
789
  }
790
- function qe(e) {
790
+ function ze(e) {
791
791
  let t;
792
792
  return Array.isArray(e) ? t = e : e ? t = [e] : t = [], t.find((n) => n === "number" || n === "integer" || n === "boolean");
793
793
  }
794
- function It(e, t) {
794
+ function Pt(e, t) {
795
795
  var i, s;
796
796
  const r = ((s = (i = ((t == null ? void 0 : t.input) ?? {}).properties) == null ? void 0 : i.data) == null ? void 0 : s.properties) ?? {}, o = { ...e };
797
797
  for (const [a, f] of Object.entries(r)) {
798
798
  const c = o[a];
799
799
  if (typeof c != "string")
800
800
  continue;
801
- const u = qe(f == null ? void 0 : f.type);
801
+ const u = ze(f == null ? void 0 : f.type);
802
802
  if (u === "number" || u === "integer") {
803
803
  const p = Number(c);
804
804
  !Number.isNaN(p) && c.trim() !== "" && (o[a] = p);
@@ -808,7 +808,7 @@ function It(e, t) {
808
808
  return o;
809
809
  }
810
810
  const J = /* @__PURE__ */ new Set(["default", "module.exports", "__esModule"]);
811
- function xt(e) {
811
+ function Ut(e) {
812
812
  const t = {}, n = (r, o) => {
813
813
  for (const [i, s] of Object.entries(r))
814
814
  if (typeof s == "function") {
@@ -820,14 +820,14 @@ function xt(e) {
820
820
  };
821
821
  return n(e, 0), t;
822
822
  }
823
- const Ve = [
823
+ const He = [
824
824
  "invalid_argument",
825
825
  "unauthenticated",
826
826
  "permission_denied",
827
827
  "not_found",
828
828
  "internal"
829
829
  ];
830
- class V extends Error {
830
+ class z extends Error {
831
831
  constructor(t, n, r) {
832
832
  super(n), this.name = "ApiError", this.code = t, this.details = r, Object.setPrototypeOf(this, new.target.prototype);
833
833
  }
@@ -840,30 +840,30 @@ class V extends Error {
840
840
  return this.details !== void 0 && (t.details = this.details), t;
841
841
  }
842
842
  }
843
- function ze(e) {
844
- return typeof e == "object" && e !== null && e.name === "ApiError" && Ve.includes(e.code) && typeof e.toJSON == "function";
843
+ function Ve(e) {
844
+ return typeof e == "object" && e !== null && e.name === "ApiError" && He.includes(e.code) && typeof e.toJSON == "function";
845
845
  }
846
846
  function Y(e, t, n = 0) {
847
847
  return e === "before-first-chunk" ? { phase: e, error: t } : { phase: e, error: t, chunksDelivered: n };
848
848
  }
849
- const N = new ye({ allErrors: !0 });
850
- me(N);
849
+ const j = new ye({ allErrors: !0 });
850
+ me(j);
851
851
  for (const e of [
852
852
  U,
853
853
  D,
854
- I,
854
+ k,
855
855
  x,
856
856
  "discriminator"
857
857
  ])
858
- N.addKeyword({ keyword: e, valid: !0 });
859
- N.addFormat("decimal", /^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);
858
+ j.addKeyword({ keyword: e, valid: !0 });
859
+ j.addFormat("decimal", /^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);
860
860
  function fe(e) {
861
861
  return e.map(
862
862
  (t) => `${t.instancePath || "(root)"} ${t.message ?? "failed schema check"}`
863
863
  ).join("; ");
864
864
  }
865
- const Ct = async (e, t) => {
866
- const n = e.ctx.get(He);
865
+ const Dt = async (e, t) => {
866
+ const n = e.ctx.get(We);
867
867
  if (n === void 0)
868
868
  return t();
869
869
  const r = e.operation.id, o = n[r];
@@ -872,18 +872,18 @@ const Ct = async (e, t) => {
872
872
  const i = {
873
873
  data: e.domainArgs,
874
874
  ...e.envelope
875
- }, s = N.compile(o.input);
875
+ }, s = j.compile(o.input);
876
876
  if (!s(i)) {
877
877
  const f = s.errors ?? [];
878
- throw new V(
878
+ throw new z(
879
879
  "invalid_argument",
880
880
  `Validation failed: ${fe(f)}`,
881
881
  f
882
882
  );
883
883
  }
884
884
  return t();
885
- }, He = Symbol("ValidateSchemasToken");
886
- function We(e) {
885
+ }, We = Symbol("ValidateSchemasToken");
886
+ function Ge(e) {
887
887
  return async function(n, r) {
888
888
  const o = n.operation.id, i = e[o];
889
889
  if (i === void 0)
@@ -891,10 +891,10 @@ function We(e) {
891
891
  const s = {
892
892
  data: n.domainArgs,
893
893
  ...n.envelope
894
- }, a = N.compile(i.input);
894
+ }, a = j.compile(i.input);
895
895
  if (!a(s)) {
896
896
  const c = a.errors ?? [];
897
- throw new V(
897
+ throw new z(
898
898
  "invalid_argument",
899
899
  `Validation failed: ${fe(c)}`,
900
900
  c
@@ -903,13 +903,13 @@ function We(e) {
903
903
  return r();
904
904
  };
905
905
  }
906
- function Ge() {
906
+ function Je() {
907
907
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (e) => {
908
908
  const t = Math.random() * 16 | 0;
909
909
  return (e === "x" ? t : t & 3 | 8).toString(16);
910
910
  });
911
911
  }
912
- class Mt {
912
+ class Lt {
913
913
  constructor(t = {}) {
914
914
  var r, o;
915
915
  this._store = /* @__PURE__ */ new Map(), this._sweeper = null, this._defaultTtlMs = t.defaultTtlMs;
@@ -928,7 +928,7 @@ class Mt {
928
928
  * @returns `{ instanceId }` โ€” pass this to `dispatch()` / `get()`.
929
929
  */
930
930
  create(t, n = [], r) {
931
- const o = new t(...n), i = Ge(), s = r ?? this._defaultTtlMs, a = s !== void 0 ? Date.now() + s : null;
931
+ const o = new t(...n), i = Je(), s = r ?? this._defaultTtlMs, a = s !== void 0 ? Date.now() + s : null;
932
932
  return this._store.set(i, { instance: o, expiresAt: a }), { instanceId: i };
933
933
  }
934
934
  // ---------------------------------------------------------------------------
@@ -1016,7 +1016,7 @@ async function E(e) {
1016
1016
  typeof t == "function" && await t.call(e);
1017
1017
  }
1018
1018
  }
1019
- function Tt(e) {
1019
+ function Rt(e) {
1020
1020
  const { produce: t, signal: n } = e, r = n ?? new AbortController().signal;
1021
1021
  return {
1022
1022
  [Symbol.asyncIterator]() {
@@ -1035,20 +1035,20 @@ function Tt(e) {
1035
1035
  }
1036
1036
  };
1037
1037
  }
1038
- async function Pt(e) {
1038
+ async function Ft(e) {
1039
1039
  const t = [];
1040
1040
  for await (const n of e)
1041
1041
  t.push(n);
1042
1042
  return t;
1043
1043
  }
1044
- async function Ut(e) {
1044
+ async function Kt(e) {
1045
1045
  const t = [];
1046
1046
  try {
1047
1047
  for await (const n of e)
1048
1048
  t.push(n);
1049
1049
  return { ok: !0, chunks: t };
1050
1050
  } catch (n) {
1051
- const r = ze(n) ? n : new V(
1051
+ const r = Ve(n) ? n : new z(
1052
1052
  "internal",
1053
1053
  n instanceof Error ? n.message : String(n)
1054
1054
  );
@@ -1061,7 +1061,7 @@ async function Ut(e) {
1061
1061
  };
1062
1062
  }
1063
1063
  }
1064
- function Dt(e) {
1064
+ function Bt(e) {
1065
1065
  return e !== null && typeof e == "object" && Symbol.asyncIterator in e;
1066
1066
  }
1067
1067
  class g extends Error {
@@ -1092,15 +1092,15 @@ function pe(e, t) {
1092
1092
  }
1093
1093
  return t.registry.resolve(e);
1094
1094
  }
1095
- function Je(e, t, n) {
1095
+ function Ye(e, t, n) {
1096
1096
  const r = pe(t, n);
1097
1097
  return r ? r.encode(e, t, n) : e;
1098
1098
  }
1099
- function Ye(e, t, n) {
1099
+ function Qe(e, t, n) {
1100
1100
  const r = pe(t, n);
1101
1101
  return r ? r.decode(e, t, n) : e;
1102
1102
  }
1103
- function Qe(e) {
1103
+ function Xe(e) {
1104
1104
  const { id: t, schema: n } = e;
1105
1105
  return {
1106
1106
  id: t,
@@ -1137,7 +1137,7 @@ function Qe(e) {
1137
1137
  `[${t}] discriminator tag "${u}" at "${i.path}" is not in the mapping (known: ${Object.keys(f).join(", ")}).`
1138
1138
  );
1139
1139
  const l = i.resolve(p);
1140
- return Je(r, l, {
1140
+ return Ye(r, l, {
1141
1141
  ...i,
1142
1142
  path: `${i.path}[${u}]`
1143
1143
  });
@@ -1169,14 +1169,14 @@ function Qe(e) {
1169
1169
  `[${t}] discriminator tag "${p}" on the wire at "${i.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`
1170
1170
  );
1171
1171
  const y = i.resolve(l);
1172
- return Ye(r, y, {
1172
+ return Qe(r, y, {
1173
1173
  ...i,
1174
1174
  path: `${i.path}[${p}]`
1175
1175
  });
1176
1176
  }
1177
1177
  };
1178
1178
  }
1179
- const Xe = "x-apigen-instances";
1179
+ const Ze = "x-apigen-instances";
1180
1180
  class O extends Error {
1181
1181
  constructor(t, n) {
1182
1182
  super(n), this.name = "NominalCodecError", this.code = t;
@@ -1186,7 +1186,7 @@ function Q(e) {
1186
1186
  const t = e.properties;
1187
1187
  return t && typeof t == "object" && !Array.isArray(t) ? t : {};
1188
1188
  }
1189
- function Ze(e) {
1189
+ function et(e) {
1190
1190
  const t = e.required;
1191
1191
  return Array.isArray(t) ? t.filter((n) => typeof n == "string") : [];
1192
1192
  }
@@ -1198,7 +1198,7 @@ function X(e, t, n) {
1198
1198
  }
1199
1199
  return e;
1200
1200
  }
1201
- function et(e, t, n) {
1201
+ function tt(e, t, n) {
1202
1202
  if (t) {
1203
1203
  const r = n.registry.resolve(t);
1204
1204
  if (r)
@@ -1206,7 +1206,7 @@ function et(e, t, n) {
1206
1206
  }
1207
1207
  return e;
1208
1208
  }
1209
- function tt(e) {
1209
+ function nt(e) {
1210
1210
  const { id: t, schema: n, ctor: r } = e;
1211
1211
  return {
1212
1212
  id: t,
@@ -1273,25 +1273,25 @@ function tt(e) {
1273
1273
  );
1274
1274
  }
1275
1275
  const a = o;
1276
- for (const u of Ze(i))
1276
+ for (const u of et(i))
1277
1277
  if (!(u in a))
1278
1278
  throw new O(
1279
1279
  "E_NOMINAL_INVALID_WIRE",
1280
1280
  `[${t}] required field "${u}" missing on the wire at "${s.path}".`
1281
1281
  );
1282
- if (i[Xe] === !1)
1282
+ if (i[Ze] === !1)
1283
1283
  throw new O(
1284
1284
  "E_NOMINAL_NONRECONSTRUCTABLE",
1285
1285
  `[${t}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`
1286
1286
  );
1287
1287
  const f = Q(i), c = {};
1288
1288
  for (const [u, p] of Object.entries(a))
1289
- c[u] = et(p, f[u], {
1289
+ c[u] = tt(p, f[u], {
1290
1290
  ...s,
1291
1291
  path: `${s.path}/${u}`
1292
1292
  });
1293
1293
  if (r) {
1294
- const u = typeof i[I] == "string" ? i[I] : "fromJSON", p = r[u];
1294
+ const u = typeof i[k] == "string" ? i[k] : "fromJSON", p = r[u];
1295
1295
  if (typeof p == "function")
1296
1296
  return p.call(
1297
1297
  r,
@@ -1304,33 +1304,33 @@ function tt(e) {
1304
1304
  }
1305
1305
  };
1306
1306
  }
1307
- const nt = [
1307
+ const rt = [
1308
1308
  L,
1309
1309
  R,
1310
1310
  F,
1311
1311
  K,
1312
1312
  B,
1313
1313
  q
1314
- ], rt = {
1314
+ ], ot = {
1315
1315
  type: "object",
1316
1316
  "x-apigen-logical": "nominal",
1317
1317
  "x-apigen-codec": "ts.NominalSentinel"
1318
- }, Z = tt({
1318
+ }, Z = nt({
1319
1319
  id: "ts.NominalSentinel",
1320
- schema: rt
1321
- }), ot = {
1320
+ schema: ot
1321
+ }), it = {
1322
1322
  oneOf: [],
1323
1323
  discriminator: { propertyName: "kind", mapping: {} },
1324
1324
  "x-apigen-logical": "union",
1325
1325
  "x-apigen-codec": "ts.UnionSentinel"
1326
- }, ee = Qe({
1326
+ }, ee = Xe({
1327
1327
  id: "ts.UnionSentinel",
1328
- schema: ot
1328
+ schema: it
1329
1329
  });
1330
- function it() {
1330
+ function st() {
1331
1331
  const e = [
1332
1332
  // 6 well-known scalars
1333
- ...nt.map((t) => [
1333
+ ...rt.map((t) => [
1334
1334
  t.id,
1335
1335
  t
1336
1336
  ]),
@@ -1341,19 +1341,19 @@ function it() {
1341
1341
  ];
1342
1342
  return Object.freeze(new Map(e));
1343
1343
  }
1344
- const Lt = Object.freeze({
1344
+ const qt = Object.freeze({
1345
1345
  host: "ts",
1346
1346
  logicalTypeVersion: ge,
1347
- codecs: it()
1347
+ codecs: st()
1348
1348
  });
1349
- function Rt(e, t, n) {
1349
+ function zt(e, t, n) {
1350
1350
  var i;
1351
1351
  const r = typeof ((i = t == null ? void 0 : t.input) == null ? void 0 : i.description) == "string" ? t.input.description : void 0, o = [n, r].filter(
1352
1352
  (s) => typeof s == "string" && s.length > 0
1353
1353
  );
1354
1354
  return o.length > 0 ? o.join(" โ€” ") : e;
1355
1355
  }
1356
- function Ft(e) {
1356
+ function Ht(e) {
1357
1357
  if (!e || typeof e != "object" || Array.isArray(e) || Object.keys(e).length === 0)
1358
1358
  return { outputSchema: void 0, wrapped: !1 };
1359
1359
  const t = e;
@@ -1366,102 +1366,139 @@ function Ft(e) {
1366
1366
  wrapped: !0
1367
1367
  };
1368
1368
  }
1369
- function Kt(e, t) {
1369
+ function Vt(e, t) {
1370
1370
  return e ? { result: t } : t && typeof t == "object" && !Array.isArray(t) ? t : void 0;
1371
1371
  }
1372
- function te(e) {
1373
- return e.words.join("-");
1372
+ const te = /* @__PURE__ */ new Set(["string", "number", "boolean", "integer"]);
1373
+ function at(e) {
1374
+ if (typeof e != "object" || e === null)
1375
+ return !1;
1376
+ const t = e;
1377
+ if (t.$ref !== void 0 || t.oneOf || t.anyOf || t.allOf)
1378
+ return !1;
1379
+ const { type: n } = t;
1380
+ return typeof n == "string" ? te.has(n) : Array.isArray(n) ? n.every((r) => te.has(r) || r === "null") : Array.isArray(t.enum) && t.enum.length > 0 ? t.enum.every((r) => ["string", "number", "boolean"].includes(typeof r)) : !1;
1374
1381
  }
1382
+ function ct(e) {
1383
+ if (!e || typeof e != "object")
1384
+ return !1;
1385
+ const t = e.properties;
1386
+ return t === void 0 || typeof t != "object" || t === null ? !1 : Object.values(t).every(
1387
+ at
1388
+ );
1389
+ }
1390
+ const ut = {
1391
+ "decimal.js": "Decimal"
1392
+ };
1393
+ function ft(e) {
1394
+ return e.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1395
+ }
1396
+ Object.entries(ut).map(([e, t]) => ({
1397
+ // Matches: import("...{modSpec}...").<anyMemberName> (single or double quotes)
1398
+ // The module specifier appears inside an absolute path, so we allow any
1399
+ // characters between the quote and the specifier, and between the specifier
1400
+ // and the closing quote. The trailing member accessor (`.default`, `.Decimal`,
1401
+ // โ€ฆ) is matched generically (`\w+`) rather than anchored to one spelling โ€”
1402
+ // see the doc comment above for why.
1403
+ pattern: new RegExp(
1404
+ `import\\(["'][^"']*${ft(e)}[^"']*["']\\)\\.\\w+`,
1405
+ "g"
1406
+ ),
1407
+ key: t
1408
+ }));
1375
1409
  function ne(e) {
1376
- return e.words.map(ft).join("");
1410
+ return e.words.join("-");
1377
1411
  }
1378
1412
  function re(e) {
1413
+ return e.words.map(mt).join("");
1414
+ }
1415
+ function oe(e) {
1379
1416
  return e.words.join("_");
1380
1417
  }
1381
- function st(e, t = {}) {
1382
- var l, y;
1383
- const n = [e.namespace, ...e.path], r = e.safe || ce(e.input) ? "GET" : "POST", o = ((y = (l = t.http) == null ? void 0 : l.verb) == null ? void 0 : y[e.id]) ?? r, i = "/" + n.map((d) => te(d)).join("/"), s = n.map((d) => re(d)).join("_"), f = n.map((d) => re(d)).slice(0, -1).join("."), c = ne(n[n.length - 2] ?? n[0]), u = ne(n[n.length - 1]), p = n.map((d) => te(d));
1418
+ function pt(e, t = {}) {
1419
+ var n, r;
1420
+ const o = [e.namespace, ...e.path], i = e.safe || ct(e.input) ? "GET" : "POST", s = ((r = (n = t.http) == null ? void 0 : n.verb) == null ? void 0 : r[e.id]) ?? i, a = "/" + o.map((y) => ne(y)).join("/"), f = o.map((y) => oe(y)).join("_"), c = o.map((y) => oe(y)).slice(0, -1).join("."), u = re(o[o.length - 2] ?? o[0]), p = re(o[o.length - 1]), l = o.map((y) => ne(y));
1384
1421
  return {
1385
- http: { verb: o, route: i },
1386
- mcp: { name: s },
1387
- grpc: { package: f, service: c, method: u },
1388
- cli: { path: p }
1422
+ http: { verb: s, route: a },
1423
+ mcp: { name: f },
1424
+ grpc: { package: c, service: u, method: p },
1425
+ cli: { path: l }
1389
1426
  };
1390
1427
  }
1391
- function at(e, t) {
1428
+ function lt(e, t) {
1392
1429
  return `x-${e}-${t}`;
1393
1430
  }
1394
- function ct(e, t) {
1431
+ function dt(e, t) {
1395
1432
  return `--${e}-${t}`;
1396
1433
  }
1397
- function ut(e, t) {
1434
+ function yt(e, t) {
1398
1435
  const n = (r) => r.toUpperCase().replace(/-/g, "_");
1399
1436
  return e === "adhd" ? `APIGEN_${n(t)}` : `APIGEN_${n(e)}_${n(t)}`;
1400
1437
  }
1401
- function ft(e) {
1438
+ function mt(e) {
1402
1439
  return e.length === 0 ? e : e[0].toUpperCase() + e.slice(1);
1403
1440
  }
1404
- function de(e) {
1441
+ function le(e) {
1405
1442
  return e.anyOf ?? e.oneOf;
1406
1443
  }
1407
- function pt(e) {
1444
+ function ht(e) {
1408
1445
  if (!e)
1409
1446
  return !1;
1410
1447
  if (e.type === "array" || e.type === "object")
1411
1448
  return !0;
1412
- const t = de(e);
1449
+ const t = le(e);
1413
1450
  if (t) {
1414
1451
  const n = t.filter((r) => r.type !== "null");
1415
1452
  return n.length > 0 && n.every((r) => r.type === "array" || r.type === "object");
1416
1453
  }
1417
1454
  return !1;
1418
1455
  }
1419
- function dt(e) {
1456
+ function gt(e) {
1420
1457
  if (!e)
1421
1458
  return !1;
1422
1459
  if (e.type === "boolean")
1423
1460
  return !0;
1424
- const t = de(e);
1461
+ const t = le(e);
1425
1462
  if (t) {
1426
1463
  const n = t.filter((r) => r.type !== "null");
1427
1464
  return n.length > 0 && n.every((r) => r.type === "boolean");
1428
1465
  }
1429
1466
  return !1;
1430
1467
  }
1431
- function lt(e) {
1468
+ function wt(e) {
1432
1469
  return e.replace(/[A-Z]/g, (t) => "-" + t.toLowerCase());
1433
1470
  }
1434
- function yt(e) {
1471
+ function bt(e) {
1435
1472
  var o, i;
1436
1473
  const t = (i = (o = e.input) == null ? void 0 : o.properties) == null ? void 0 : i.data, n = (t == null ? void 0 : t.properties) ?? {}, r = (t == null ? void 0 : t.required) ?? [];
1437
1474
  return { props: n, required: r };
1438
1475
  }
1439
- function oe(e) {
1476
+ function ie(e) {
1440
1477
  return typeof e.handler == "function";
1441
1478
  }
1442
- function mt(e) {
1479
+ function vt(e) {
1443
1480
  var o;
1444
1481
  const t = ((o = e.input) == null ? void 0 : o.properties) ?? {}, n = e["x-apigen-envelope"], r = [];
1445
1482
  for (const i of Object.keys(t)) {
1446
1483
  if (i === "data")
1447
1484
  continue;
1448
- const s = (n == null ? void 0 : n[i]) ?? "adhd", a = at(s, i);
1485
+ const s = (n == null ? void 0 : n[i]) ?? "adhd", a = lt(s, i);
1449
1486
  r.push({
1450
1487
  field: i,
1451
1488
  pluginId: s,
1452
1489
  httpHeader: a,
1453
1490
  mcpMetaKey: a,
1454
- cliFlag: ct(s, i),
1455
- envVar: ut(s, i)
1491
+ cliFlag: dt(s, i),
1492
+ envVar: yt(s, i)
1456
1493
  });
1457
1494
  }
1458
1495
  return r;
1459
1496
  }
1460
- function ht(e, t) {
1461
- const n = /* @__PURE__ */ new Map(), { props: r } = yt(e);
1497
+ function $t(e, t) {
1498
+ const n = /* @__PURE__ */ new Map(), { props: r } = bt(e);
1462
1499
  for (const [o, i] of Object.entries(r)) {
1463
1500
  let s = "string";
1464
- dt(i) ? s = "boolean" : pt(i) && (s = "json"), n.set(lt(o), {
1501
+ gt(i) ? s = "boolean" : ht(i) && (s = "json"), n.set(wt(o), {
1465
1502
  camelKey: o,
1466
1503
  kind: "domain",
1467
1504
  valueKind: s
@@ -1478,8 +1515,8 @@ function ht(e, t) {
1478
1515
  }
1479
1516
  return n;
1480
1517
  }
1481
- function Bt(e) {
1482
- const { op: t, schema: n, transport: r, projection: o } = e, i = st(t, o), s = n ? mt(n) : [], a = n ? ht(n, s) : /* @__PURE__ */ new Map(), f = n ? Be(n).params : void 0, c = {
1518
+ function Wt(e) {
1519
+ const { op: t, schema: n, transport: r, projection: o } = e, i = pt(t, o), s = n ? vt(n) : [], a = n ? $t(n, s) : /* @__PURE__ */ new Map(), f = n ? qe(n).params : void 0, c = {
1483
1520
  op: t,
1484
1521
  transport: r,
1485
1522
  http: i.http,
@@ -1490,38 +1527,38 @@ function Bt(e) {
1490
1527
  envelope: s,
1491
1528
  cliFlags: a,
1492
1529
  streaming: t.streaming,
1493
- isMount: oe(t)
1530
+ isMount: ie(t)
1494
1531
  };
1495
- if (oe(t)) {
1532
+ if (ie(t)) {
1496
1533
  const u = t.handler;
1497
1534
  c.mountHandler = async (p) => u(p);
1498
1535
  }
1499
1536
  return c;
1500
1537
  }
1501
- function qt(e) {
1538
+ function Gt(e) {
1502
1539
  const t = e.usePlugins;
1503
1540
  return Array.isArray(t) ? t : [];
1504
1541
  }
1505
- function Vt(e) {
1542
+ function Jt(e) {
1506
1543
  const t = e.useOptions;
1507
1544
  return t && typeof t == "object" ? t : {};
1508
1545
  }
1509
- function gt(e) {
1546
+ function jt(e) {
1510
1547
  return async function(n, r) {
1511
1548
  const o = Object.assign(n, { data: n.domainArgs });
1512
1549
  return await e.layer(o, r);
1513
1550
  };
1514
1551
  }
1515
- function zt(e, t) {
1552
+ function Yt(e, t) {
1516
1553
  var r;
1517
1554
  const n = [];
1518
1555
  for (const o of t) {
1519
1556
  const i = (r = o.capabilities) == null ? void 0 : r.layer;
1520
- i && n.push(gt(i));
1557
+ i && n.push(jt(i));
1521
1558
  }
1522
- return n.push(We(e)), Ie(n);
1559
+ return n.push(Ge(e)), ke(n);
1523
1560
  }
1524
- function wt() {
1561
+ function Nt() {
1525
1562
  const e = /* @__PURE__ */ new Map();
1526
1563
  return {
1527
1564
  get: (t) => e.get(t),
@@ -1530,18 +1567,18 @@ function wt() {
1530
1567
  }
1531
1568
  };
1532
1569
  }
1533
- const bt = {
1570
+ const Ot = {
1534
1571
  input: {
1535
1572
  type: "object",
1536
1573
  properties: { data: { type: "object", properties: {} } }
1537
1574
  },
1538
1575
  output: {}
1539
1576
  };
1540
- async function Ht(e, t, n, r) {
1577
+ async function Qt(e, t, n, r) {
1541
1578
  const o = {
1542
1579
  ...n,
1543
1580
  operation: { id: e.op.id },
1544
- ctx: new ke()
1581
+ ctx: new Ie()
1545
1582
  };
1546
1583
  if (e.isMount) {
1547
1584
  const i = e.mountHandler;
@@ -1553,13 +1590,13 @@ async function Ht(e, t, n, r) {
1553
1590
  operation: e.op,
1554
1591
  data: n.domainArgs,
1555
1592
  envelope: n.envelope,
1556
- ctx: wt(),
1593
+ ctx: Nt(),
1557
1594
  transport: e.transport,
1558
1595
  signal: n.signal ?? new AbortController().signal
1559
1596
  }, a = {
1560
1597
  ...r,
1561
1598
  fns: { [e.op.id]: () => i(s) },
1562
- schemas: { [e.op.id]: bt }
1599
+ schemas: { [e.op.id]: Ot }
1563
1600
  };
1564
1601
  return t(e.op.id, o, a);
1565
1602
  }
@@ -1567,39 +1604,39 @@ async function Ht(e, t, n, r) {
1567
1604
  }
1568
1605
  export {
1569
1606
  xe as EventBus,
1570
- Mt as InstanceRegistry,
1571
- ke as LayerContext,
1607
+ Lt as InstanceRegistry,
1608
+ Ie as LayerContext,
1572
1609
  g as UnionCodecError,
1573
- He as ValidateSchemasToken,
1574
- nt as WELL_KNOWN_TS_CODECS,
1575
- gt as adaptCoreLayer,
1576
- Ke as assertNoSelfSubscription,
1610
+ We as ValidateSchemasToken,
1611
+ rt as WELL_KNOWN_TS_CODECS,
1612
+ jt as adaptCoreLayer,
1613
+ Be as assertNoSelfSubscription,
1577
1614
  Te as buildContext,
1578
- xt as buildFnTable,
1579
- Ft as buildMcpOutputSchema,
1580
- Bt as buildOpPlan,
1581
- Rt as buildToolDescription,
1582
- It as coerceQueryParams,
1583
- Ut as collectWithPhase,
1584
- St as createApiPackage,
1585
- Ie as createInvoker,
1586
- kt as createLogger,
1587
- zt as createPackageInvoker,
1588
- Tt as createStream,
1589
- Qe as createUnionCodec,
1615
+ Ut as buildFnTable,
1616
+ Ht as buildMcpOutputSchema,
1617
+ Wt as buildOpPlan,
1618
+ zt as buildToolDescription,
1619
+ Pt as coerceQueryParams,
1620
+ Kt as collectWithPhase,
1621
+ Mt as createApiPackage,
1622
+ ke as createInvoker,
1623
+ Tt as createLogger,
1624
+ Yt as createPackageInvoker,
1625
+ Rt as createStream,
1626
+ Xe as createUnionCodec,
1590
1627
  Ae as dataParamNames,
1591
- Et as defineMiddleware,
1592
- Be as describeParams,
1628
+ Ct as defineMiddleware,
1629
+ qe as describeParams,
1593
1630
  Se as dispatch,
1594
- Ht as dispatchForPlan,
1595
- Pt as drainStream,
1596
- Dt as isApiStream,
1597
- We as makeValidateLayer,
1631
+ Qt as dispatchForPlan,
1632
+ Ft as drainStream,
1633
+ Bt as isApiStream,
1634
+ Ge as makeValidateLayer,
1598
1635
  Oe as needsEnvelopeField,
1599
- Vt as readUseOptions,
1600
- qt as readUsePlugins,
1601
- Lt as tsHostBinding,
1602
- Ct as validateLayer,
1636
+ Jt as readUseOptions,
1637
+ Gt as readUsePlugins,
1638
+ qt as tsHostBinding,
1639
+ Dt as validateLayer,
1603
1640
  Me as wireObservers,
1604
- Kt as wrapMcpStructuredContent
1641
+ Vt as wrapMcpStructuredContent
1605
1642
  };
package/package.json CHANGED
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "name": "@adhd/apigen-engine-runtime",
3
- "version": "0.1.4",
3
+ "version": "0.2.0",
4
4
  "dependencies": {
5
5
  "ajv": "^8.20.0",
6
6
  "ajv-formats": "2.1.1",
7
7
  "pino": "10.3.1",
8
- "@adhd/apigen-core-client": "^0.1.4",
9
- "@adhd/apigen-base-logical": "^0.0.5",
10
- "@adhd/apigen-base-errors": "^0.1.5",
11
- "@adhd/apigen-engine-naming": "^0.1.4",
8
+ "@adhd/apigen-core-client": "^0.2.0",
9
+ "@adhd/apigen-base-logical": "^0.1.0",
10
+ "@adhd/apigen-base-errors": "^0.2.0",
11
+ "@adhd/apigen-engine-naming": "^0.2.0",
12
12
  "better-sqlite3": "12.10.0"
13
13
  },
14
14
  "main": "./index.js",