@adhd/apigen-engine-runtime 0.1.5 โ†’ 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,19 @@
1
+ ## 0.2.1 (2026-07-28)
2
+
3
+ This was a version bump only for apigen-engine-runtime to align it with other projects, there were no code changes.
4
+
5
+ ## 0.1.6 (2026-07-27)
6
+
7
+
8
+ ### ๐Ÿš€ Features
9
+
10
+ - **apigen-engine-runtime:** batch/bulk fan-out execution โ€” `invokeBatch()` with concurrency control, per-item timeouts, and error semantics
11
+
12
+
13
+ ### โค๏ธ Thank You
14
+
15
+ - pseudosky
16
+
1
17
  ## 0.1.5 (2026-07-25)
2
18
 
3
19
 
package/README.md CHANGED
@@ -9,8 +9,8 @@ Part of [apigen](../README.md). For end-to-end usage see [`../cli`](../cli).
9
9
  ## Public API
10
10
 
11
11
  ```ts
12
- import { dispatch, buildFnTable, describeParams, needsEnvelopeField, dataParamNames, createLogger, defineMiddleware, createApiPackage, EventBus, wireObservers, buildContext } from '@adhd/apigen-engine-runtime';
13
- import type { Logger, LogFormat, CreateLoggerOptions, ParamInfo, AnyFn } from '@adhd/apigen-engine-runtime';
12
+ import { dispatch, buildFnTable, describeParams, needsEnvelopeField, dataParamNames, createLogger, defineMiddleware, createApiPackage, EventBus, wireObservers, buildContext, invokeBatch } from '@adhd/apigen-engine-runtime';
13
+ import type { Logger, LogFormat, CreateLoggerOptions, ParamInfo, AnyFn, BatchOptions, BatchItemResult } from '@adhd/apigen-engine-runtime';
14
14
  ```
15
15
 
16
16
  - **`dispatch(fns, ctx, schema, fnName, envelope, data)`** โ€” the one dispatch path. No plugin
@@ -23,6 +23,10 @@ import type { Logger, LogFormat, CreateLoggerOptions, ParamInfo, AnyFn } from '@
23
23
  - **`needsEnvelopeField` / `dataParamNames`** โ€” envelope + param helpers (single source).
24
24
  - **`createLogger({ level, format, destination })`** โ€” pino-based logger; defaults to
25
25
  **stderr** so MCP stdio stdout stays protocol-clean. `format: 'json' | 'pretty'`.
26
+ - **`invokeBatch(invoke, operationId, items, opts, batchOpts)`** โ€” fan out N calls through
27
+ the real `invoke` path (via `createInvoker`'s composed Layer stack) with controlled
28
+ concurrency, error handling, and per-item timeouts. Returns `Promise<BatchItemResult[]>`.
29
+ See `@adhd/apigen-plugin-batch` for mount wiring.
26
30
  - **`defineMiddleware` / `createApiPackage` / `EventBus` / `wireObservers` / `buildContext`**
27
31
  โ€” middleware + observer wiring.
28
32
 
package/index.d.ts CHANGED
@@ -26,6 +26,8 @@ export { buildToolDescription } from './lib/tool-description';
26
26
  export type { ToolDescriptionSchema } from './lib/tool-description';
27
27
  export { buildMcpOutputSchema, wrapMcpStructuredContent, } from './lib/mcp-output-schema';
28
28
  export type { McpOutputAdapter } from './lib/mcp-output-schema';
29
+ export { invokeBatch, BATCH_DEFAULT_CONCURRENCY, BATCH_MAX_CONCURRENCY, } from './lib/batch';
30
+ export type { BatchOptions, BatchItemResult } from './lib/batch';
29
31
  export { buildOpPlan } from './lib/op-plan';
30
32
  export type { OpPlan, BuildOpPlanInput, OpPlanEnvelopeField, OpPlanCliFlag, } from './lib/op-plan';
31
33
  export type { TransportAdapter } from './lib/transport-adapter';
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 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;
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"),Ue=require("ajv"),De=require("ajv-formats"),I="$apigen";class z extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}}function Le(e){const t=new Map;return{register(r,n){if(t.has(r.id)&&!(n!=null&&n.override))throw new z(`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 z("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 L="x-apigen-logical",R="x-apigen-codec",S="x-apigen-ctor",x="x-apigen-tojson",Re="0.1.0";function V(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=ce(e,i,t);return v(e,a,r)}const s=t.type;if(s==="array"){if(!Array.isArray(e))return _(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 d=a[u];return d===void 0?w(c):v(c,d,{...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 _(e,t,r);const a=t.properties;if(!a)return w(e);const f=r.path,c={};for(const[u,d]of Object.entries(a)){const l=e[u];l!==void 0&&(c[u]=v(l,d,{...r,path:`${f}/${u}`}))}return c}return s==null?_(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=ce(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 d=a[u];return d===void 0?c:$(c,d,{...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,d]of Object.entries(a)){const l=e[u];l!==void 0&&(c[u]=$(l,d,{...r,path:`${f}/${u}`}))}return c}return s==null?Be(e,r):e}function ce(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 _(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{[I]:n,v:i}}catch{}}return w(e)}function Be(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&I in e){const r=e,n=r[I],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 Fe(e){return{encode(t,r,n){const o=V(e,n);return v(t,r,o)},decode(t,r,n){const o=V(e,n);return $(t,r,o)}}}const B={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)}},q={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}},H={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"))}},qe=/^[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"&&!qe.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${r.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},M="NaN",T="Infinity",P="-Infinity",He=new Set([M,T,P]),W={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)?M:e===1/0?T:e===-1/0?P:e},decode(e,t,r){if(typeof e=="number")return e;if(typeof e=="string"){if(e===M)return NaN;if(e===T)return 1/0;if(e===P)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 ${[...He].join(", ")}.`);return NaN}},Ke=[B,F,q,H,K,W];function We(e,t={}){for(const r of Ke)e.register(r,{override:t.override??!1})}B.id,F.id,q.id,H.id,K.id,W.id;const ue=Le();We(ue);const fe=Fe(ue.freeze());function de(e,t){var n;const r=((n=e.input)==null?void 0:n.properties)??{};return t in r}function pe(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 ze(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 Ve(e,t){return t===void 0||e===void 0?e:fe.decode(e,t)}function E(e,t){const r=t.output;return!r||Object.keys(r).length===0?e:fe.encode(e,r)}async function le(e,t,r,n,o,i){const a=pe(r).map(c=>Ve(i[c],ze(r,c)));if(de(r,"session")&&t){const c=await t({session:o.session}),u=await e[n](c,...a);return E(u,r)}if(r.hasCtx){const c=t?await t(o):void 0,u=await e[n](c,...a);return E(u,r)}const f=await e[n](...a);return E(f,r)}class ye{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 me(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=()=>le(o.fns,o.createClient,i,r,n.envelope,n.domainArgs);return e.reduceRight((f,c)=>()=>c(n,f),s)()}}function Ge(e){return e}class he{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(Je(r,t))for(const o of n)await o(t)}}function Je(e,t){const[r,n,o]=e.split(":");return!(r!=="*"&&r!==t.module||n&&n!=="*"&&n!==t.method||o&&o!=="*"&&o!==t.lifecycle)}function ge(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 we(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 G(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 d=t[i];if(!d){const l=Object.keys(t).join(", ")||"(none)";throw new Error(`[apigen-logical] $ref "${i}" cannot be resolved. Available $defs: ${l}`)}n.push(d)}continue}const s=o.oneOf;if(Array.isArray(s))for(const d of s)typeof d=="object"&&d!==null&&n.push(d);const a=o.properties;if(a)for(const d of Object.values(a))n.push(d);const f=o.items;if(Array.isArray(f))for(const d of f)typeof d=="object"&&d!==null&&n.push(d);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 J=new Set(["string","number","boolean","integer"]);function Ye(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"?J.has(r):Array.isArray(r)?r.every(n=>J.has(n)||n==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(n=>["string","number","boolean"].includes(typeof n)):!1}function Xe(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(Ye)}function Qe(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{G(o.input,t),G(o.output,t)}catch(i){throw new Error(`[apigen-core-client] Schema validation failed for function "${n}": ${i.message}`)}}function Ze(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 et(e,t,r){Qe(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=[],d={};for(const h of t)if(h.envelope&&s[h.id]!==!1)for(const[b,Pe]of Object.entries(h.envelope))c[b]=Pe,d[b]=h.id,u.includes(b)||u.push(b);const l={type:"object",properties:a,additionalProperties:!1,...f.length>0?{required:f}:{}},m=i.safe===!0||Xe(i.input),p=i.input.definitions,y=i.input.$defs;n[o]={input:{type:"object",properties:{...c,data:l},required:[...u,...f.length>0?["data"]:[]],additionalProperties:!1,description:Ze(Object.keys(c),Object.keys(a).length>0),...p?{definitions:p}:{},...y?{$defs:y}:{}},output:i.output,...i.hasCtx?{hasCtx:!0}:{},"x-apigen-safe":m,...Object.keys(d).length>0?{"x-apigen-envelope":d}:{}}}return n}const tt={"decimal.js":"Decimal"};function rt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(tt).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${rt(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));class U extends Error{constructor(t){super(t),this.name="ConfigurationError"}}function be(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 U(`Middleware "${t.id}" subscribes to its own events via "${r}". This would cause infinite recursion.`)}}function nt(e){const{domainSchemas:t,middlewares:r,overrides:n={},strict:o=!1}=e;be(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 U(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 d of Object.keys(u??{}))if(!i.has(d)){const l=`Override key "${c}.${d}" does not match any declared middleware id.`;if(o)throw new U(l);console.warn("[apigen-runtime]",l)}const s=et(t,r,n),a=new he;return ge(r,a),{schemas:s,createClient:async c=>we(r,c,a),dispose:()=>a.clear()}}function ot(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}}},N(i);const s=r?N.destination({dest:e.destination,mkdir:!0,sync:!0}):N.destination(2);return N(i,s)}function ve(e){return e?e.type==="array"?`${ve(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function $e(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:ve(c),required:o.has(f)})),s=i.map(f=>`${f.name}${f.required?"":"?"}: ${f.type}`).join(", ");return{params:i,text:s}}function it(e){let t;return Array.isArray(e)?t=e:e?t=[e]:t=[],t.find(r=>r==="number"||r==="integer"||r==="boolean")}function st(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=it(f==null?void 0:f.type);if(u==="number"||u==="integer"){const d=Number(c);!Number.isNaN(d)&&c.trim()!==""&&(o[a]=d)}else u==="boolean"&&(c==="true"?o[a]=!0:c==="false"&&(o[a]=!1))}return o}const Y=new Set(["default","module.exports","__esModule"]);function at(e){const t={},r=(n,o)=>{for(const[i,s]of Object.entries(n))if(typeof s=="function"){!Y.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&&Y.has(i)&&r(s,o+1)};return r(e,0),t}const ct=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];class A 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 Oe(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&ct.includes(e.code)&&typeof e.toJSON=="function"}function X(e,t,r=0){return e==="before-first-chunk"?{phase:e,error:t}:{phase:e,error:t,chunksDelivered:r}}const O=new Ue({allErrors:!0});De(O);for(const e of[L,R,S,x,"discriminator"])O.addKeyword({keyword:e,valid:!0});O.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function Ne(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}const ut=async(e,t)=>{const r=e.ctx.get(je);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=O.compile(o.input);if(!s(i)){const f=s.errors??[];throw new A("invalid_argument",`Validation failed: ${Ne(f)}`,f)}return t()},je=Symbol("ValidateSchemasToken");function Ae(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=O.compile(i.input);if(!a(s)){const c=a.errors??[];throw new A("invalid_argument",`Validation failed: ${Ne(c)}`,c)}return n()}}function ft(){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 dt{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=ft(),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 C(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])=>C(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),C(r.instance)}}async function C(e){if(e!==null&&typeof e=="object"&&"dispose"in e){const t=e.dispose;typeof t=="function"&&await t.call(e)}}function pt(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 lt(e){const t=[];for await(const r of e)t.push(r);return t}async function _e(e){const t=[];try{for await(const r of e)t.push(r);return{ok:!0,chunks:t}}catch(r){const n=Oe(r)?r:new A("internal",r instanceof Error?r.message:String(r));return t.length===0?{ok:!1,carrier:X("before-first-chunk",n)}:{ok:!1,carrier:X("after-first-chunk",n,t.length)}}}function Ee(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 k(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 Ce(e,t){const r=e[R];if(typeof r=="string"){const n=t.registry.get(r);if(n)return n}return t.registry.resolve(e)}function yt(e,t,r){const n=Ce(t,r);return n?n.encode(e,t,r):e}function mt(e,t,r){const n=Ce(t,r);return n?n.decode(e,t,r):e}function ke(e){const{id:t,schema:r}=e;return{id:t,kind:"union",schema:r,matches(n){if(n[L]==="union")return!0;const o=n.oneOf;return!Array.isArray(o)||o.length===0?!1:k(n)!==void 0},encode(n,o,i){const s=k(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),d=f[u];if(!d)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(d);return yt(n,l,{...i,path:`${i.path}[${u}]`})},decode(n,o,i){if(n===null||typeof n!="object"||Array.isArray(n)){let p;throw n===null?p="null":Array.isArray(n)?p="array":p=typeof n,new g("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${p}.`)}const s=n,a=k(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 d=String(u),l=c[d];if(!l)throw new g("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${d}" on the wire at "${i.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const m=i.resolve(l);return mt(n,m,{...i,path:`${i.path}[${d}]`})}}}const ht="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 gt(e){const t=e.required;return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}function Z(e,t,r){if(t){const n=r.registry.resolve(t);if(n)return n.encode(e,t,r)}return e}function wt(e,t,r){if(t){const n=r.registry.resolve(t);if(n)return n.decode(e,t,r)}return e}function bt(e){const{id:t,schema:r,ctor:n}=e;return{id:t,kind:"nominal",schema:r,matches(o){return o[L]==="nominal"?!0:o[R]===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[x]=="string"?i[x]:"toJSON",c=o[f];if(typeof c=="function"){const p=c.call(o);if(p!==null&&typeof p=="object"&&!Array.isArray(p)){const y={};for(const[h,b]of Object.entries(p))y[h]=Z(b,a[h],{...s,path:`${s.path}/${h}`});return y}return p}const u={},d=Object.keys(a),l=o,m=d.length>0?d:Object.keys(l);for(const p of m){const y=l[p];y!==void 0&&(u[p]=Z(y,a[p],{...s,path:`${s.path}/${p}`}))}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 gt(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[ht]===!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,d]of Object.entries(a))c[u]=wt(d,f[u],{...s,path:`${s.path}/${u}`});if(n){const u=typeof i[S]=="string"?i[S]:"fromJSON",d=n[u];if(typeof d=="function")return d.call(n,c);const l=n;return new l(c)}return c}}}const Ie=[B,F,q,H,K,W],vt={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},ee=bt({id:"ts.NominalSentinel",schema:vt}),$t={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},te=ke({id:"ts.UnionSentinel",schema:$t});function Ot(){const e=[...Ie.map(t=>[t.id,t]),[ee.id,ee],[te.id,te]];return Object.freeze(new Map(e))}const Nt=Object.freeze({host:"ts",logicalTypeVersion:Re,codecs:Ot()});function jt(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 At(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}const Se=4,xe=32;function D(e){return Oe(e)?e:e instanceof Error?new A("internal",e.message):e}function Et(e,t){if(e==="serial"||e==="chained")return 1;const r=t??Se;return!Number.isFinite(r)||r<1?1:Math.min(Math.floor(r),xe)}function Ct(){}function kt(e,t){var i;if(!e&&!t)return{signal:void 0,dispose:Ct};const r=new AbortController,n=()=>{r.abort(e==null?void 0:e.reason)};e&&(e.aborted?r.abort(e.reason):e.addEventListener("abort",n,{once:!0}));let o;return t!==void 0&&!r.signal.aborted&&(o=setTimeout(()=>{r.abort(new DOMException(`apigen/invokeBatch: item timed out after ${t}ms`,"TimeoutError"))},t),(i=o.unref)==null||i.call(o)),{signal:r.signal,dispose(){e&&e.removeEventListener("abort",n),o&&clearTimeout(o)}}}async function re(e,t,r,n,o,i){const s=kt(n.signal,i);try{const a=s.signal?{...n,signal:s.signal}:n,f=await e(t,a,o);if(Ee(f)){const c=await _e(f);if(c.ok)return{index:r,status:"fulfilled",chunks:c.chunks};const u=c.carrier;return{index:r,status:"rejected",reason:D(u.error),...u.phase==="after-first-chunk"?{chunksDelivered:u.chunksDelivered}:{}}}return{index:r,status:"fulfilled",value:f}}catch(a){return{index:r,status:"rejected",reason:D(a)}}finally{s.dispose()}}async function It(e,t,r,n,o={}){const i=o.mode??"parallel",s=o.onItemError??"continue",a=Et(i,o.concurrency),f=new Array(r.length),c=p=>({index:p,status:"rejected",reason:D(new Error("apigen/invokeBatch: not attempted โ€” an earlier item failed and "+(i==="chained"?'mode is "chained"':'onItemError is "abort"')))});if(i==="serial"||i==="chained"){let p=!1;for(let y=0;y<r.length;y++){if(p){f[y]=c(y);continue}const h=await re(e,t,y,r[y],n,o.itemTimeoutMs);f[y]=h,h.status==="rejected"&&(i==="chained"||s==="abort")&&(p=!0)}return f}let u=0,d=!1;const l=Math.max(1,Math.min(a,r.length)),m=Array.from({length:l},async()=>{for(;;){const p=u++;if(p>=r.length)return;if(d){f[p]=c(p);continue}const y=await re(e,t,p,r[p],n,o.itemTimeoutMs);f[p]=y,y.status==="rejected"&&s==="abort"&&(d=!0)}});return await Promise.all(m),f}const ne=new Set(["string","number","boolean","integer"]);function St(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"?ne.has(r):Array.isArray(r)?r.every(n=>ne.has(n)||n==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(n=>["string","number","boolean"].includes(typeof n)):!1}function xt(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(St)}const Mt={"decimal.js":"Decimal"};function Tt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Mt).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Tt(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function oe(e){return e.words.join("-")}function ie(e){return e.words.map(Rt).join("")}function se(e){return e.words.join("_")}function Pt(e,t={}){var r,n;const o=[e.namespace,...e.path],i=e.safe||xt(e.input)?"GET":"POST",s=((n=(r=t.http)==null?void 0:r.verb)==null?void 0:n[e.id])??i,a="/"+o.map(m=>oe(m)).join("/"),f=o.map(m=>se(m)).join("_"),c=o.map(m=>se(m)).slice(0,-1).join("."),u=ie(o[o.length-2]??o[0]),d=ie(o[o.length-1]),l=o.map(m=>oe(m));return{http:{verb:s,route:a},mcp:{name:f},grpc:{package:c,service:u,method:d},cli:{path:l}}}function Ut(e,t){return`x-${e}-${t}`}function Dt(e,t){return`--${e}-${t}`}function Lt(e,t){const r=n=>n.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${r(t)}`:`APIGEN_${r(e)}_${r(t)}`}function Rt(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function Me(e){return e.anyOf??e.oneOf}function Bt(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=Me(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 Ft(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=Me(e);if(t){const r=t.filter(n=>n.type!=="null");return r.length>0&&r.every(n=>n.type==="boolean")}return!1}function qt(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function Ht(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 ae(e){return typeof e.handler=="function"}function Kt(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=Ut(s,i);n.push({field:i,pluginId:s,httpHeader:a,mcpMetaKey:a,cliFlag:Dt(s,i),envVar:Lt(s,i)})}return n}function Wt(e,t){const r=new Map,{props:n}=Ht(e);for(const[o,i]of Object.entries(n)){let s="string";Ft(i)?s="boolean":Bt(i)&&(s="json"),r.set(qt(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 zt(e){const{op:t,schema:r,transport:n,projection:o}=e,i=Pt(t,o),s=r?Kt(r):[],a=r?Wt(r,s):new Map,f=r?$e(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:ae(t)};if(ae(t)){const u=t.handler;c.mountHandler=async d=>u(d)}return c}function Vt(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function Gt(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function Te(e){return async function(r,n){const o=Object.assign(r,{data:r.domainArgs});return await e.layer(o,n)}}function Jt(e,t){var n;const r=[];for(const o of t){const i=(n=o.capabilities)==null?void 0:n.layer;i&&r.push(Te(i))}return r.push(Ae(e)),me(r)}function Yt(){const e=new Map;return{get:t=>e.get(t),set:(t,r)=>{e.set(t,r)}}}const Xt={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function Qt(e,t,r,n){const o={...r,operation:{id:e.op.id},ctx:new ye};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:Yt(),transport:e.transport,signal:r.signal??new AbortController().signal},a={...n,fns:{[e.op.id]:()=>i(s)},schemas:{[e.op.id]:Xt}};return t(e.op.id,o,a)}return t(e.op.id,o,n)}exports.BATCH_DEFAULT_CONCURRENCY=Se;exports.BATCH_MAX_CONCURRENCY=xe;exports.EventBus=he;exports.InstanceRegistry=dt;exports.LayerContext=ye;exports.UnionCodecError=g;exports.ValidateSchemasToken=je;exports.WELL_KNOWN_TS_CODECS=Ie;exports.adaptCoreLayer=Te;exports.assertNoSelfSubscription=be;exports.buildContext=we;exports.buildFnTable=at;exports.buildMcpOutputSchema=At;exports.buildOpPlan=zt;exports.buildToolDescription=jt;exports.coerceQueryParams=st;exports.collectWithPhase=_e;exports.createApiPackage=nt;exports.createInvoker=me;exports.createLogger=ot;exports.createPackageInvoker=Jt;exports.createStream=pt;exports.createUnionCodec=ke;exports.dataParamNames=pe;exports.defineMiddleware=Ge;exports.describeParams=$e;exports.dispatch=le;exports.dispatchForPlan=Qt;exports.drainStream=lt;exports.invokeBatch=It;exports.isApiStream=Ee;exports.makeValidateLayer=Ae;exports.needsEnvelopeField=de;exports.readUseOptions=Gt;exports.readUsePlugins=Vt;exports.tsHostBinding=Nt;exports.validateLayer=ut;exports.wireObservers=ge;exports.wrapMcpStructuredContent=_t;