@adhd/apigen-engine-runtime 0.2.2 โ 0.2.4
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 +49 -0
- package/README.md +14 -0
- package/index.d.ts +1 -1
- package/index.js +1 -1
- package/index.mjs +1057 -766
- package/lib/describe-params.d.ts +12 -1
- package/lib/op-plan.d.ts +7 -0
- package/lib/package-invoker.d.ts +17 -0
- package/lib/tool-description.d.ts +8 -5
- package/package.json +25 -5
- package/test-support/parity-harness.d.ts +37 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,52 @@
|
|
|
1
|
+
## 0.2.4 (2026-09-24)
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
### ๐ Features
|
|
5
|
+
|
|
6
|
+
- **apigen:** let a CLI host derive its process exit code from the result
|
|
7
|
+
|
|
8
|
+
- **backlog:** INTERFACE_v2 consolidation โ six-verb surface, web UI (search/stats/batch/edit), stats API (citationCount, closedAt, summary scope + window)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
### ๐ฉน Fixes
|
|
12
|
+
|
|
13
|
+
- **apigen:** accept camelCase flag spellings as aliases in the flag table
|
|
14
|
+
|
|
15
|
+
- **apigen-cli:** batch nested-input CLI/HTTP wiring, sandbox isolation leaks, morph-walk index-signature regression
|
|
16
|
+
|
|
17
|
+
- **apigen:** audit fixes โ S-18/S-19/C-20/C-21/S-20, java mvn race, union-encoder envelope, lazy heavy-dep loading
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
### โค๏ธ Thank You
|
|
21
|
+
|
|
22
|
+
- parity-harness-self-test
|
|
23
|
+
- pseudosky
|
|
24
|
+
- Sky
|
|
25
|
+
|
|
26
|
+
## 0.2.3 (2026-08-07)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
### ๐ Features
|
|
30
|
+
|
|
31
|
+
- **apigen:** schema-driven worked examples for MCP tool descriptions + validation errors
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
### ๐ฉน Fixes
|
|
35
|
+
|
|
36
|
+
- **apigen-engine-runtime:** stop parity-harness from mutating the real repo (BUG-APIGEN-052)
|
|
37
|
+
|
|
38
|
+
- **apigen-engine-runtime:** isolated-git.spec.ts's own fixture helper can corrupt the enclosing repo under real hook env (BUG-APIGEN-052 follow-up)
|
|
39
|
+
|
|
40
|
+
- **apigen-cli:** restore 2768 files mass-deleted by 0117eb22 (BUG-APIGEN-052)
|
|
41
|
+
|
|
42
|
+
- **apigen-engine-runtime:** delegate vgit() to runGit() in isolated-git.spec.ts (BUG-APIGEN-054)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
### โค๏ธ Thank You
|
|
46
|
+
|
|
47
|
+
- parity-harness-self-test
|
|
48
|
+
- pseudosky
|
|
49
|
+
|
|
1
50
|
## 0.2.2 (2026-07-30)
|
|
2
51
|
|
|
3
52
|
|
package/README.md
CHANGED
|
@@ -29,6 +29,20 @@ import type { Logger, LogFormat, CreateLoggerOptions, ParamInfo, AnyFn, BatchOpt
|
|
|
29
29
|
See `@adhd/apigen-plugin-batch` for mount wiring.
|
|
30
30
|
- **`defineMiddleware` / `createApiPackage` / `EventBus` / `wireObservers` / `buildContext`**
|
|
31
31
|
โ middleware + observer wiring.
|
|
32
|
+
- **`buildToolDescription(schema, ...)`** โ builds the human-facing description shown for a
|
|
33
|
+
mounted tool/operation, appending a schema-synthesized worked example (via
|
|
34
|
+
`@adhd/apigen-base-logical`'s `renderExampleNote`) after the envelope-convention note. The
|
|
35
|
+
same function backs both `apigen-plugin-cli-output`'s static codegen and
|
|
36
|
+
`apigen-plugin-mcp`'s dynamic server, so every apigen-mounted tool's description carries a
|
|
37
|
+
concrete example of its own real shape, not just a generic convention sentence.
|
|
38
|
+
|
|
39
|
+
## Validation error messages include a worked example
|
|
40
|
+
|
|
41
|
+
The validate-Layer's AJV validation-failure errors append the same schema-synthesized
|
|
42
|
+
example described above (`invalid_argument`, `Validation failed: ... โ Example: {...}`) โ
|
|
43
|
+
so a rejected call comes back with both what was structurally wrong and a shape that would
|
|
44
|
+
actually pass. This closes a real discoverability gap: previously an error only named the
|
|
45
|
+
missing/invalid property, never what a correct call looked like.
|
|
32
46
|
|
|
33
47
|
## Request envelope
|
|
34
48
|
|
package/index.d.ts
CHANGED
|
@@ -31,6 +31,6 @@ export type { BatchOptions, BatchItemResult } from './lib/batch';
|
|
|
31
31
|
export { buildOpPlan } from './lib/op-plan';
|
|
32
32
|
export type { OpPlan, BuildOpPlanInput, OpPlanEnvelopeField, OpPlanCliFlag, } from './lib/op-plan';
|
|
33
33
|
export type { TransportAdapter } from './lib/transport-adapter';
|
|
34
|
-
export { createPackageInvoker, readUsePlugins, readUseOptions, adaptCoreLayer, } from './lib/package-invoker';
|
|
34
|
+
export { createPackageInvoker, readUsePlugins, readExitCodeHook, readUseOptions, adaptCoreLayer, } from './lib/package-invoker';
|
|
35
35
|
export type { UsePlugin, UseOptions } from './lib/package-invoker';
|
|
36
36
|
export { dispatchForPlan } from './lib/dispatch-for-plan';
|
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"),Ue=require("ajv"),De=require("ajv-formats"),I="$apigen";class V 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 V(`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 V("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 G(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=ue(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 l=a[u];return l===void 0?w(c):v(c,l,{...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,l]of Object.entries(a)){const p=e[u];p!==void 0&&(c[u]=v(p,l,{...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=ue(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 l=a[u];return l===void 0?c:$(c,l,{...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,l]of Object.entries(a)){const p=e[u];p!==void 0&&(c[u]=$(p,l,{...r,path:`${f}/${u}`}))}return c}return s==null?Be(e,r):e}function ue(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=G(e,n);return v(t,r,o)},decode(t,r,n){const o=G(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 fe=Le();We(fe);const le=Fe(fe.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:le.decode(e,t)}function E(e,t){const r=t.output;return!r||Object.keys(r).length===0?e:le.encode(e,r)}async function ye(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 me{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 he(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=()=>ye(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 ge{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 we(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 be(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 J(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 l=t[i];if(!l){const p=Object.keys(t).join(", ")||"(none)";throw new Error(`[apigen-logical] $ref "${i}" cannot be resolved. Available $defs: ${p}`)}n.push(l)}continue}const s=o.oneOf;if(Array.isArray(s))for(const l of s)typeof l=="object"&&l!==null&&n.push(l);const a=o.properties;if(a)for(const l of Object.values(a))n.push(l);const f=o.items;if(Array.isArray(f))for(const l of f)typeof l=="object"&&l!==null&&n.push(l);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 Y=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"?Y.has(r):Array.isArray(r)?r.every(n=>Y.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{J(o.input,t),J(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=[],l={};for(const h of t)if(h.envelope&&s[h.id]!==!1)for(const[b,Pe]of Object.entries(h.envelope))c[b]=Pe,l[b]=h.id,u.includes(b)||u.push(b);const p={type:"object",properties:a,additionalProperties:!1,...f.length>0?{required:f}:{}},m=i.safe===!0||Xe(i.input),d=i.input.definitions,y=i.input.$defs;n[o]={input:{type:"object",properties:{...c,data:p},required:[...u,...f.length>0?["data"]:[]],additionalProperties:!1,description:Ze(Object.keys(c),Object.keys(a).length>0),...d?{definitions:d}:{},...y?{$defs:y}:{}},output:i.output,...i.hasCtx?{hasCtx:!0}:{},"x-apigen-safe":m,...Object.keys(l).length>0?{"x-apigen-envelope":l}:{}}}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 ve(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;ve(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 l of Object.keys(u??{}))if(!i.has(l)){const p=`Override key "${c}.${l}" does not match any declared middleware id.`;if(o)throw new U(p);console.warn("[apigen-runtime]",p)}const s=et(t,r,n),a=new ge;return we(r,a),{schemas:s,createClient:async c=>be(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}}},O(i);const s=r?O.destination({dest:e.destination,mkdir:!0,sync:!0}):O.destination(2);return O(i,s)}function $e(e){return e?e.type==="array"?`${$e(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function Ne(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:$e(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 l=Number(c);!Number.isNaN(l)&&c.trim()!==""&&(o[a]=l)}else u==="boolean"&&(c==="true"?o[a]=!0:c==="false"&&(o[a]=!1))}return o}const X=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"){!X.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&&X.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 Q(e,t,r=0){return e==="before-first-chunk"?{phase:e,error:t}:{phase:e,error:t,chunksDelivered:r}}const N=new Ue({allErrors:!0});De(N);for(const e of[L,R,S,x,"discriminator"])N.addKeyword({keyword:e,valid:!0});N.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function je(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}const ut=async(e,t)=>{const r=e.ctx.get(Ae);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 A("invalid_argument",`Validation failed: ${je(f)}`,f)}return t()},Ae=Symbol("ValidateSchemasToken");function _e(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 A("invalid_argument",`Validation failed: ${je(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 lt{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 dt(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 pt(e){const t=[];for await(const r of e)t.push(r);return t}async function Ee(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:Q("before-first-chunk",n)}:{ok:!1,carrier:Q("after-first-chunk",n,t.length)}}}function Ce(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 ke(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=ke(t,r);return n?n.encode(e,t,r):e}function mt(e,t,r){const n=ke(t,r);return n?n.decode(e,t,r):e}function Ie(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),l=f[u];if(!l)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 p=i.resolve(l);return yt(n,p,{...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=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 l=String(u),p=c[l];if(!p)throw new g("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" on the wire at "${i.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const m=i.resolve(p);return mt(n,m,{...i,path:`${i.path}[${l}]`})}}}const ht="x-apigen-instances";class j extends Error{constructor(t,r){super(r),this.name="NominalCodecError",this.code=t}}function Z(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 ee(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=Z(i),f=typeof i[x]=="string"?i[x]:"toJSON",c=o[f];if(typeof c=="function"){const d=c.call(o);if(d!==null&&typeof d=="object"&&!Array.isArray(d)){const y={};for(const[h,b]of Object.entries(d))y[h]=ee(b,a[h],{...s,path:`${s.path}/${h}`});return y}return d}const u={},l=Object.keys(a),p=o,m=l.length>0?l:Object.keys(p);for(const d of m){const y=p[d];y!==void 0&&(u[d]=ee(y,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 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=Z(i),c={};for(const[u,l]of Object.entries(a))c[u]=wt(l,f[u],{...s,path:`${s.path}/${u}`});if(n){const u=typeof i[S]=="string"?i[S]:"fromJSON",l=n[u];if(typeof l=="function")return l.call(n,c);const p=n;return new p(c)}return c}}}const Se=[B,F,q,H,K,W],vt={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},te=bt({id:"ts.NominalSentinel",schema:vt}),$t={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},re=Ie({id:"ts.UnionSentinel",schema:$t});function Nt(){const e=[...Se.map(t=>[t.id,t]),[te.id,te],[re.id,re]];return Object.freeze(new Map(e))}const Ot=Object.freeze({host:"ts",logicalTypeVersion:Re,codecs:Nt()});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 xe=4,Me=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??xe;return!Number.isFinite(r)||r<1?1:Math.min(Math.floor(r),Me)}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 ne(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(Ce(f)){const c=await Ee(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=d=>({index:d,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 d=!1;for(let y=0;y<r.length;y++){if(d){f[y]=c(y);continue}const h=await ne(e,t,y,r[y],n,o.itemTimeoutMs);f[y]=h,h.status==="rejected"&&(i==="chained"||s==="abort")&&(d=!0)}return f}let u=0,l=!1;const p=Math.max(1,Math.min(a,r.length)),m=Array.from({length:p},async()=>{for(;;){const d=u++;if(d>=r.length)return;if(l){f[d]=c(d);continue}const y=await ne(e,t,d,r[d],n,o.itemTimeoutMs);f[d]=y,y.status==="rejected"&&s==="abort"&&(l=!0)}});return await Promise.all(m),f}const oe=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"?oe.has(r):Array.isArray(r)?r.every(n=>oe.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 ie(e){return e.words.join("-")}function se(e){return e.words.map(Rt).join("")}function ae(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=>ie(m)).join("/"),f=o.map(m=>ae(m)).join("_"),c=o.map(m=>ae(m)).slice(0,-1).join("."),u=se(o[o.length-2]??o[0]),l=se(o[o.length-1]),p=o.map(m=>ie(m));return{http:{verb:s,route:a},mcp:{name:f},grpc:{package:c,service:u,method:l},cli:{path:p}}}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 z(e){return e.anyOf??e.oneOf}function Bt(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=z(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=z(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){if(!e)return!1;if(e.type==="number"||e.type==="integer")return!0;const t=z(e);if(t){const r=t.filter(n=>n.type!=="null");return r.length>0&&r.every(n=>n.type==="number"||n.type==="integer")}return!1}function Ht(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function Kt(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 ce(e){return typeof e.handler=="function"}function Wt(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 zt(e,t){const r=new Map,{props:n}=Kt(e);for(const[o,i]of Object.entries(n)){let s="string";Ft(i)?s="boolean":(Bt(i)||qt(i))&&(s="json"),r.set(Ht(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 Vt(e){const{op:t,schema:r,transport:n,projection:o}=e,i=Pt(t,o),s=r?Wt(r):[],a=r?zt(r,s):new Map,f=r?Ne(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:ce(t)};if(ce(t)){const u=t.handler;c.mountHandler=async l=>u(l)}return c}function Gt(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function Jt(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 Yt(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(_e(e)),he(r)}function Xt(){const e=new Map;return{get:t=>e.get(t),set:(t,r)=>{e.set(t,r)}}}const Qt={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function Zt(e,t,r,n){const o={...r,operation:{id:e.op.id},ctx:new me};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:Xt(),transport:e.transport,signal:r.signal??new AbortController().signal},a={...n,fns:{[e.op.id]:()=>i(s)},schemas:{[e.op.id]:Qt}};return t(e.op.id,o,a)}return t(e.op.id,o,n)}exports.BATCH_DEFAULT_CONCURRENCY=xe;exports.BATCH_MAX_CONCURRENCY=Me;exports.EventBus=ge;exports.InstanceRegistry=lt;exports.LayerContext=me;exports.UnionCodecError=g;exports.ValidateSchemasToken=Ae;exports.WELL_KNOWN_TS_CODECS=Se;exports.adaptCoreLayer=Te;exports.assertNoSelfSubscription=ve;exports.buildContext=be;exports.buildFnTable=at;exports.buildMcpOutputSchema=At;exports.buildOpPlan=Vt;exports.buildToolDescription=jt;exports.coerceQueryParams=st;exports.collectWithPhase=Ee;exports.createApiPackage=nt;exports.createInvoker=he;exports.createLogger=ot;exports.createPackageInvoker=Yt;exports.createStream=dt;exports.createUnionCodec=Ie;exports.dataParamNames=pe;exports.defineMiddleware=Ge;exports.describeParams=Ne;exports.dispatch=ye;exports.dispatchForPlan=Zt;exports.drainStream=pt;exports.invokeBatch=It;exports.isApiStream=Ce;exports.makeValidateLayer=_e;exports.needsEnvelopeField=de;exports.readUseOptions=Jt;exports.readUsePlugins=Gt;exports.tsHostBinding=Ot;exports.validateLayer=ut;exports.wireObservers=we;exports.wrapMcpStructuredContent=_t;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("node:fs");const ge=require("node:module");require("node:path");const _=require("pino"),We=require("ajv"),Je=require("ajv-formats");var A=typeof document<"u"?document.currentScript:null;const M="$apigen";let Q=class extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function Ye(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new Q(`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 Q("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 H="x-apigen-logical",V="x-apigen-codec",P="x-apigen-ctor",U="x-apigen-tojson",Ge="0.1.0";function X(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=be(e,i,t,n);return v(e,a,n)}const s=t.type;if(s==="array"){if(!Array.isArray(e))return O(e,t,n);const a=t.items;if(!a)return e.map(u=>b(u));const f=n.path;return Array.isArray(a)?e.map((u,c)=>{const l=a[c];return l===void 0?b(u):v(u,l,{...n,path:`${f}/${c}`})}):e.map((u,c)=>v(u,a,{...n,path:`${f}/${c}`}))}if(s==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return O(e,t,n);const a=t.properties;if(!a)return b(e);const f=n.path,u={};for(const[c,l]of Object.entries(a)){const p=e[c];p!==void 0&&(u[c]=v(p,l,{...n,path:`${f}/${c}`}))}return u}return s==null?O(e,t,n):b(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=be(e,i,t,n);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((u,c)=>{const l=a[c];return l===void 0?u:$(u,l,{...n,path:`${f}/${c}`})}):e.map((u,c)=>$(u,a,{...n,path:`${f}/${c}`}))}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,u={};for(const[c,l]of Object.entries(a)){const p=e[c];p!==void 0&&(u[c]=$(p,l,{...n,path:`${f}/${c}`}))}for(const[c,l]of Object.entries(e))!(c in a)&&l!==void 0&&(u[c]=l);return u}return s==null?R(e,n):e}function be(e,t,n,r){var o;const i=n.discriminator;if(i!=null&&i.propertyName){const u=i.propertyName,c=e!==null&&typeof e=="object"?e[u]:void 0;if(typeof c=="string"){if(i.mapping){const l=i.mapping[c];if(l){const p=t.find(y=>y.$ref===l);if(p)return p}}for(const l of t){const p=(o=C(l,r).properties)==null?void 0:o[u];if(!p)continue;const y=p.enum;if(p.const===c||Array.isArray(y)&&y.includes(c))return l}}}const s=Ze(e,t,r);if(s)return s;let a,f=-1;for(const u of t){const c=C(u,r),l=we(e,c,r);l!==null&&l>f&&(f=l,a=u)}return a!==void 0?a:t[0]??{}}function C(e,t){const n=e.$ref;return typeof n=="string"?t.resolve(n):e}function ee(e){if("const"in e)return e.const;const t=e.enum;if(Array.isArray(t)&&t.length===1)return t[0]}function Ze(e,t,n){if(e===null||typeof e!="object"||Array.isArray(e))return;const r=e,o=t.map(s=>C(s,n)),i=new Set;for(const s of o){const a=s.properties;if(a)for(const[f,u]of Object.entries(a))ee(u)!==void 0&&i.add(f)}for(const s of i){const a=o.map(p=>{const y=p.properties,d=y==null?void 0:y[s];return d?ee(d):void 0}),f=a.filter(p=>p!==void 0),u=new Set(f);if(f.length<2||u.size!==f.length)continue;const c=r[s];if(c===void 0)continue;const l=a.findIndex(p=>p===c);if(l!==-1)return t[l]}}function Qe(e){if(e===null)return"null";if(Array.isArray(e))return"array";const t=typeof e;return t==="number"?Number.isInteger(e)?"integer":"number":t}function we(e,t,n){const r=t.oneOf;if(Array.isArray(r)){let c=null;for(const l of r){const p=we(e,C(l,n),n);p!==null&&(c===null||p>c)&&(c=p)}return c}const o=t.type,i=Qe(e);if(typeof o=="string"){if(!(o===i||o==="number"&&i==="integer"))return null}else if(Array.isArray(o)&&!o.some(c=>c===i||c==="number"&&i==="integer"))return null;if(e===null||typeof e!="object"||Array.isArray(e))return typeof o=="string"?1:0;const s=e,a=t.required;let f=0;if(Array.isArray(a)){for(const c of a)if(typeof c=="string"){if(s[c]===void 0)return null;f+=2}}const u=t.properties;if(u){for(const c of Object.keys(u))s[c]!==void 0&&(f+=1);for(const c of Object.keys(s))u[c]===void 0&&(f-=1)}return f}function O(e,t,n){var r;for(const o of n.registry.ids()){const i=n.registry.get(o);if((r=i==null?void 0:i.ownsValue)!=null&&r.call(i,e))return{[M]:o,v:i.encode(e,i.schema,n)}}if(Array.isArray(e))return e.map(o=>O(o,{},n));if(ve(e)){const o={};for(const[i,s]of Object.entries(e))s!==void 0&&(o[i]=O(s,{},n));return o}return b(e)}function ve(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function R(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&M in e){const n=e,r=n[M],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}if(Array.isArray(e))return e.map(n=>R(n,t));if(ve(e)){const n={};for(const[r,o]of Object.entries(e))n[r]=R(o,t);return n}return e}function b(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(b);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=b(r));return t}return null}function Xe(e){return{encode(t,n,r){const o=X(e,r);return v(t,n,o)},decode(t,n,r){const o=X(e,r);return $(t,n,o)}}}const K={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},ownsValue(e){return e instanceof Date},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)}},z={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},ownsValue(e){return typeof e=="bigint"},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)}},W={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}},J={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},ownsValue(e){return e instanceof Uint8Array},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"))}},et=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Y={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"&&!et.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},L="NaN",D="Infinity",q="-Infinity",tt=new Set([L,D,q]),G={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},ownsValue(e){return typeof e=="number"&&!Number.isFinite(e)},encode(e,t,n){return Number.isNaN(e)?L:e===1/0?D:e===-1/0?q:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===L)return NaN;if(e===D)return 1/0;if(e===q)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 ${[...tt].join(", ")}.`);return NaN}},nt=[K,z,W,J,Y,G];function rt(e,t={}){for(const n of nt)e.register(n,{override:t.override??!1})}const ot=12;function it(e,t){const n=/^#\/(definitions|\$defs)\/(.+)$/.exec(e);if(!n)return;const[,r,o]=n,i=r==="$defs"?t.$defs:t.definitions;return i==null?void 0:i[decodeURIComponent(o)]}function te(e){return Array.isArray(e)&&e.length>0?e[0]:void 0}function st(e){if(Array.isArray(e.type))return e.type.find(t=>t!=="null")??e.type[0];if(typeof e.type=="string")return e.type;if(e.properties)return"object"}function at(e){switch(e.format){case"date-time":return"1970-01-01T00:00:00.000Z";case"date":return"1970-01-01";case"time":return"00:00:00Z";case"uuid":return"00000000-0000-0000-0000-000000000000";case"email":return"user@example.com";case"uri":case"url":case"uri-reference":return"https://example.com";case"hostname":return"example.com";case"ipv4":return"127.0.0.1";case"ipv6":return"::1";case"decimal":return"0";case"int64":return"0";case"byte":return"";default:return"<string>"}}function ne(e,t,n){const r=e.properties??{},o=e.required??[],i={};for(const s of o){const a=r[s];i[s]=a!==void 0?j(a,t,n+1):`<${s}>`}return i}function ct(e,t,n){const r=Array.isArray(e.items)?e.items[0]:e.items;return r?[j(r,t,n+1)]:[]}function j(e,t=e??{},n=0){if(!e||n>ot)return null;if(typeof e.$ref=="string"){const o=it(e.$ref,t);return o!==void 0?j(o,t,n+1):null}if(e.const!==void 0)return e.const;if(Array.isArray(e.enum)&&e.enum.length>0)return e.enum[0];if(Array.isArray(e.allOf)&&e.allOf.length>0){const o={},i=[];for(const s of e.allOf){Object.assign(o,s.properties??{});for(const a of s.required??[])i.includes(a)||i.push(a)}return ne({...e,properties:o,required:i},t,n)}const r=te(e.oneOf)??te(e.anyOf);if(r)return j(r,t,n+1);switch(st(e)){case"object":return ne(e,t,n);case"array":return ct(e,t,n);case"string":return at(e);case"integer":case"number":return 0;case"boolean":return!1;case"null":return null;default:return null}}function $e(e){if(!e)return;const t=j(e);return`Example: ${JSON.stringify(t)}`}K.id,z.id,W.id,J.id,Y.id,G.id;const Ae=Ye();rt(Ae);const Oe=Xe(Ae.freeze());function je(e,t){var r;const n=((r=e.input)==null?void 0:r.properties)??{};return t in n}function Ne(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 ut(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 ft(e,t){return t===void 0||e===void 0?e:Oe.decode(e,t)}function I(e,t){const n=t.output;return!n||Object.keys(n).length===0?e:Oe.encode(e,n)}async function _e(e,t,n,r,o,i){const a=Ne(n).map(u=>ft(i[u],ut(n,u)));if(je(n,"session")&&t){const u=await t({session:o.session}),c=await e[r](u,...a);return I(c,n)}if(n.hasCtx){const u=t?await t(o):void 0,c=await e[r](u,...a);return I(c,n)}const f=await e[r](...a);return I(f,n)}class Ee{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 Ce(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=()=>_e(o.fns,o.createClient,i,n,r.envelope,r.domainArgs);return e.reduceRight((f,u)=>()=>u(r,f),s)()}}function lt(e){return e}class ke{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(pt(n,t))for(const o of r)await o(t)}}function pt(e,t){const[n,r,o]=e.split(":");return!(n!=="*"&&n!==t.module||r&&r!=="*"&&r!==t.method||o&&o!=="*"&&o!==t.lifecycle)}function Se(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 Ie(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}ge.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:A&&A.tagName.toUpperCase()==="SCRIPT"&&A.src||new URL("index.js",document.baseURI).href);function re(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 l=t[i];if(!l){const p=Object.keys(t).join(", ")||"(none)";throw new Error(`[apigen-logical] $ref "${i}" cannot be resolved. Available $defs: ${p}`)}r.push(l)}continue}const s=o.oneOf;if(Array.isArray(s))for(const l of s)typeof l=="object"&&l!==null&&r.push(l);const a=o.properties;if(a)for(const l of Object.values(a))r.push(l);const f=o.items;if(Array.isArray(f))for(const l of f)typeof l=="object"&&l!==null&&r.push(l);else typeof f=="object"&&f!==null&&r.push(f);const u=o.additionalProperties;typeof u=="object"&&u!==null&&r.push(u);const c=o.propertyNames;typeof c=="object"&&c!==null&&r.push(c)}}const oe=new Set(["string","number","boolean","integer"]);function dt(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"?oe.has(n):Array.isArray(n)?n.every(r=>oe.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function yt(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(dt)}function mt(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{re(o.input,t),re(o.output,t)}catch(i){throw new Error(`[apigen-core-client] Schema validation failed for function "${r}": ${i.message}`)}}function ht(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 gt(e,t,n){mt(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??[],u={},c=[],l={};for(const h of t)if(h.envelope&&s[h.id]!==!1)for(const[w,ze]of Object.entries(h.envelope))u[w]=ze,l[w]=h.id,c.includes(w)||c.push(w);const p={type:"object",properties:a,additionalProperties:!1,...f.length>0?{required:f}:{}},y=i.safe===!0||yt(i.input),d=i.input.definitions,m=i.input.$defs;r[o]={input:{type:"object",properties:{...u,data:p},required:[...c,...f.length>0?["data"]:[]],additionalProperties:!1,description:ht(Object.keys(u),Object.keys(a).length>0),...d?{definitions:d}:{},...m?{$defs:m}:{}},output:i.output,...i.hasCtx?{hasCtx:!0}:{},"x-apigen-safe":y,...Object.keys(l).length>0?{"x-apigen-envelope":l}:{}}}return r}const bt={"decimal.js":"Decimal"};function wt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(bt).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${wt(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));class B extends Error{constructor(t){super(t),this.name="ConfigurationError"}}function xe(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 B(`Middleware "${t.id}" subscribes to its own events via "${n}". This would cause infinite recursion.`)}}function vt(e){const{domainSchemas:t,middlewares:n,overrides:r={},strict:o=!1}=e;xe(n);for(const u of Object.keys(r))if(!(u in t.schemas)){const c=`Override key "${u}" not found in domain schemas.`;if(o)throw new B(c);console.warn("[apigen-runtime]",c)}const i=new Set(n.map(u=>u.id));for(const[u,c]of Object.entries(r))for(const l of Object.keys(c??{}))if(!i.has(l)){const p=`Override key "${u}.${l}" does not match any declared middleware id.`;if(o)throw new B(p);console.warn("[apigen-runtime]",p)}const s=gt(t,n,r),a=new ke;return Se(n,a),{schemas:s,createClient:async u=>Ie(n,u,a),dispose:()=>a.clear()}}function $t(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}}},_(i);const s=n?_.destination({dest:e.destination,mkdir:!0,sync:!0}):_.destination(2);return _(i,s)}function At(e){if(!e||e.type!=="object"||!e.properties)return;const t=Object.entries(e.properties);if(t.length===0)return;const n=new Set(e.required??[]);return`{ ${t.map(([o,i])=>`${o}${n.has(o)?"":"?"}: ${k(i)}`).join(", ")} }`}function Ot(e){return typeof e=="string"?`'${e}'`:JSON.stringify(e)}function jt(e){const t=e.enum??[];return t.length===0?"unknown":t.map(Ot).join("|")}function Nt(e,t){return e.map(n=>k(n,t)).join(" | ")}function k(e,t=0){if(!e)return"unknown";if(e.type==="array")return`${k(e.items,0)}[]`;if(e.enum)return jt(e);if(e.$ref)return String(e.$ref).split("/").pop()||"object";const n=e.anyOf??e.oneOf;return n?n.length===0?"unknown":t>=2?Nt(n,t-1):"union":t>=1&&e.type==="object"?At(e)??"object":e.type??"object"}function Te(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,u])=>({name:f,type:k(u,2),required:o.has(f)})),s=i.map(f=>`${f.name}${f.required?"":"?"}: ${f.type}`).join(", ");return{params:i,text:s}}function _t(e){let t;return Array.isArray(e)?t=e:e?t=[e]:t=[],t.find(n=>n==="number"||n==="integer"||n==="boolean")}function Et(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 u=o[a];if(typeof u!="string")continue;const c=_t(f==null?void 0:f.type);if(c==="number"||c==="integer"){const l=Number(u);!Number.isNaN(l)&&u.trim()!==""&&(o[a]=l)}else c==="boolean"&&(u==="true"?o[a]=!0:u==="false"&&(o[a]=!1))}return o}const ie=new Set(["default","module.exports","__esModule"]);function Ct(e){const t={},n=(r,o)=>{for(const[i,s]of Object.entries(r))if(typeof s=="function"){!ie.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&&ie.has(i)&&n(s,o+1)};return n(e,0),t}const kt=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];class S 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 Me(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&kt.includes(e.code)&&typeof e.toJSON=="function"}function se(e,t,n=0){return e==="before-first-chunk"?{phase:e,error:t}:{phase:e,error:t,chunksDelivered:n}}const N=new We({allErrors:!0});Je(N);for(const e of[H,V,P,U,"discriminator"])N.addKeyword({keyword:e,valid:!0});N.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function St(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function Pe(e,t){const n=$e(t),r=[`Validation failed: ${St(e)}`];return n&&r.push(n),r.join(" โ ")}const It=async(e,t)=>{const n=e.ctx.get(Ue);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=N.compile(o.input);if(!s(i)){const f=s.errors??[];throw new S("invalid_argument",Pe(f,o.input),f)}return t()},Ue=Symbol("ValidateSchemasToken");function Re(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=N.compile(i.input);if(!a(s)){const u=a.errors??[];throw new S("invalid_argument",Pe(u,i.input),u)}return r()}}function xt(){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 Tt{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=xt(),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 x(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])=>x(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),x(n.instance)}}async function x(e){if(e!==null&&typeof e=="object"&&"dispose"in e){const t=e.dispose;typeof t=="function"&&await t.call(e)}}function Mt(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 Pt(e){const t=[];for await(const n of e)t.push(n);return t}async function Le(e){const t=[];try{for await(const n of e)t.push(n);return{ok:!0,chunks:t}}catch(n){const r=Me(n)?n:new S("internal",n instanceof Error?n.message:String(n));return t.length===0?{ok:!1,carrier:se("before-first-chunk",r)}:{ok:!1,carrier:se("after-first-chunk",r,t.length)}}}function De(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 T(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 qe(e,t){const n=e[V];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function Ut(e,t,n){const r=qe(t,n);return r?r.encode(e,t,n):e}function Rt(e,t,n){const r=qe(t,n);return r?r.decode(e,t,n):e}function Be(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[H]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:T(r)!==void 0},encode(r,o,i){const s=T(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,u=r[a];if(u==null)throw new g("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${i.path}" is missing the discriminator property "${a}".`);const c=String(u),l=f[c];if(!l)throw new g("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${c}" at "${i.path}" is not in the mapping (known: ${Object.keys(f).join(", ")}).`);const p=i.resolve(l);return Ut(r,p,{...i,path:`${i.path}[${c}]`})},decode(r,o,i){if(r===null||typeof r!="object"||Array.isArray(r)){let d;throw r===null?d="null":Array.isArray(r)?d="array":d=typeof r,new g("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${d}.`)}const s=r,a=T(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:u}=a,c=s[f];if(c==null)throw new g("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${i.path}" is missing the discriminator property "${f}".`);const l=String(c),p=u[l];if(!p)throw new g("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" on the wire at "${i.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const y=i.resolve(p);return Rt(r,y,{...i,path:`${i.path}[${l}]`})}}}const Lt="x-apigen-instances";class E extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}}function ae(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(n=>typeof n=="string"):[]}function ce(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function qt(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function Bt(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[H]==="nominal"?!0:o[V]===t},encode(o,i,s){if(o===null||typeof o!="object")return o;if(s.seen.has(o)){if(s.mode==="strict")throw new E("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=ae(i),f=typeof i[U]=="string"?i[U]:"toJSON",u=o[f];if(typeof u=="function"){const d=u.call(o);if(d!==null&&typeof d=="object"&&!Array.isArray(d)){const m={};for(const[h,w]of Object.entries(d))m[h]=ce(w,a[h],{...s,path:`${s.path}/${h}`});return m}return d}const c={},l=Object.keys(a),p=o,y=l.length>0?l:Object.keys(p);for(const d of y){const m=p[d];m!==void 0&&(c[d]=ce(m,a[d],{...s,path:`${s.path}/${d}`}))}return c}finally{s.seen.delete(o)}},decode(o,i,s){if(o===null||typeof o!="object"||Array.isArray(o)){let c;throw o===null?c="null":Array.isArray(o)?c="array":c=typeof o,new E("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${c}.`)}const a=o;for(const c of Dt(i))if(!(c in a))throw new E("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${c}" missing on the wire at "${s.path}".`);if(i[Lt]===!1)throw new E("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=ae(i),u={};for(const[c,l]of Object.entries(a))u[c]=qt(l,f[c],{...s,path:`${s.path}/${c}`});if(r){const c=typeof i[P]=="string"?i[P]:"fromJSON",l=r[c];if(typeof l=="function")return l.call(r,u);const p=r;return new p(u)}return u}}}const Fe=[K,z,W,J,Y,G],Ft={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},ue=Bt({id:"ts.NominalSentinel",schema:Ft}),Ht={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},fe=Be({id:"ts.UnionSentinel",schema:Ht});function Vt(){const e=[...Fe.map(t=>[t.id,t]),[ue.id,ue],[fe.id,fe]];return Object.freeze(new Map(e))}const Kt=Object.freeze({host:"ts",logicalTypeVersion:Ge,codecs:Vt()});function zt(e,t,n){var s;const r=typeof((s=t==null?void 0:t.input)==null?void 0:s.description)=="string"?t.input.description:void 0,o=$e(t==null?void 0:t.input),i=[n,r,o].filter(a=>typeof a=="string"&&a.length>0);return i.length>0?i.join(" โ "):e}function Wt(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 Jt(e,t){return e?{result:t}:t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}const He=4,Ve=32;function F(e){return Me(e)?e:e instanceof Error?new S("internal",e.message):e}function Yt(e,t){if(e==="serial"||e==="chained")return 1;const n=t??He;return!Number.isFinite(n)||n<1?1:Math.min(Math.floor(n),Ve)}function Gt(){}function Zt(e,t){var i;if(!e&&!t)return{signal:void 0,dispose:Gt};const n=new AbortController,r=()=>{n.abort(e==null?void 0:e.reason)};e&&(e.aborted?n.abort(e.reason):e.addEventListener("abort",r,{once:!0}));let o;return t!==void 0&&!n.signal.aborted&&(o=setTimeout(()=>{n.abort(new DOMException(`apigen/invokeBatch: item timed out after ${t}ms`,"TimeoutError"))},t),(i=o.unref)==null||i.call(o)),{signal:n.signal,dispose(){e&&e.removeEventListener("abort",r),o&&clearTimeout(o)}}}async function le(e,t,n,r,o,i){const s=Zt(r.signal,i);try{const a=s.signal?{...r,signal:s.signal}:r,f=await e(t,a,o);if(De(f)){const u=await Le(f);if(u.ok)return{index:n,status:"fulfilled",chunks:u.chunks};const c=u.carrier;return{index:n,status:"rejected",reason:F(c.error),...c.phase==="after-first-chunk"?{chunksDelivered:c.chunksDelivered}:{}}}return{index:n,status:"fulfilled",value:f}}catch(a){return{index:n,status:"rejected",reason:F(a)}}finally{s.dispose()}}async function Qt(e,t,n,r,o={}){const i=o.mode??"parallel",s=o.onItemError??"continue",a=Yt(i,o.concurrency),f=new Array(n.length),u=d=>({index:d,status:"rejected",reason:F(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 d=!1;for(let m=0;m<n.length;m++){if(d){f[m]=u(m);continue}const h=await le(e,t,m,n[m],r,o.itemTimeoutMs);f[m]=h,h.status==="rejected"&&(i==="chained"||s==="abort")&&(d=!0)}return f}let c=0,l=!1;const p=Math.max(1,Math.min(a,n.length)),y=Array.from({length:p},async()=>{for(;;){const d=c++;if(d>=n.length)return;if(l){f[d]=u(d);continue}const m=await le(e,t,d,n[d],r,o.itemTimeoutMs);f[d]=m,m.status==="rejected"&&s==="abort"&&(l=!0)}});return await Promise.all(y),f}ge.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:A&&A.tagName.toUpperCase()==="SCRIPT"&&A.src||new URL("index.js",document.baseURI).href);const pe=new Set(["string","number","boolean","integer"]);function Xt(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"?pe.has(n):Array.isArray(n)?n.every(r=>pe.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function en(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(Xt)}const tn={"decimal.js":"Decimal"};function nn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(tn).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${nn(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function de(e){return e.words.join("-")}function ye(e){return e.words.map(cn).join("")}function me(e){return e.words.join("_")}function rn(e,t={}){var n,r;const o=[e.namespace,...e.path],i=e.safe||en(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=>de(y)).join("/"),f=o.map(y=>me(y)).join("_"),u=o.map(y=>me(y)).slice(0,-1).join("."),c=ye(o[o.length-2]??o[0]),l=ye(o[o.length-1]),p=o.map(y=>de(y));return{http:{verb:s,route:a},mcp:{name:f},grpc:{package:u,service:c,method:l},cli:{path:p}}}function on(e,t){return`x-${e}-${t}`}function sn(e,t){return`--${e}-${t}`}function an(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function cn(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function Z(e){return e.anyOf??e.oneOf}function un(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=Z(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 fn(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=Z(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function ln(e){if(!e)return!1;if(e.type==="number"||e.type==="integer")return!0;const t=Z(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="number"||r.type==="integer")}return!1}function pn(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function dn(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 he(e){return typeof e.handler=="function"}function yn(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=on(s,i);r.push({field:i,pluginId:s,httpHeader:a,mcpMetaKey:a,cliFlag:sn(s,i),envVar:an(s,i)})}return r}function mn(e,t,n,r){t===n||e.has(t)||e.set(t,{...r,aliasOf:n})}function hn(e,t){const n=new Map,{props:r}=dn(e);for(const[o,i]of Object.entries(r)){let s="string";fn(i)?s="boolean":(un(i)||ln(i))&&(s="json");const a=pn(o),f={camelKey:o,kind:"domain",valueKind:s};n.set(a,f),mn(n,o,a,f)}for(const o of t){const i=o.cliFlag.replace(/^--/,""),s={camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar};n.set(i,s)}return n}function gn(e){const{op:t,schema:n,transport:r,projection:o}=e,i=rn(t,o),s=n?yn(n):[],a=n?hn(n,s):new Map,f=n?Te(n).params:void 0,u={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:he(t)};if(he(t)){const c=t.handler;u.mountHandler=async l=>c(l)}return u}function bn(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function wn(e){const t=e.exitCode;return typeof t=="function"?t:void 0}function vn(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function Ke(e){return async function(n,r){const o=Object.assign(n,{data:n.domainArgs});return await e.layer(o,r)}}function $n(e,t){var r;const n=[];for(const o of t){const i=(r=o.capabilities)==null?void 0:r.layer;i&&n.push(Ke(i))}return n.push(Re(e)),Ce(n)}function An(){const e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}const On={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function jn(e,t,n,r){const o={...n,operation:{id:e.op.id},ctx:new Ee};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:An(),transport:e.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[e.op.id]:()=>i(s)},schemas:{[e.op.id]:On}};return t(e.op.id,o,a)}return t(e.op.id,o,r)}exports.BATCH_DEFAULT_CONCURRENCY=He;exports.BATCH_MAX_CONCURRENCY=Ve;exports.EventBus=ke;exports.InstanceRegistry=Tt;exports.LayerContext=Ee;exports.UnionCodecError=g;exports.ValidateSchemasToken=Ue;exports.WELL_KNOWN_TS_CODECS=Fe;exports.adaptCoreLayer=Ke;exports.assertNoSelfSubscription=xe;exports.buildContext=Ie;exports.buildFnTable=Ct;exports.buildMcpOutputSchema=Wt;exports.buildOpPlan=gn;exports.buildToolDescription=zt;exports.coerceQueryParams=Et;exports.collectWithPhase=Le;exports.createApiPackage=vt;exports.createInvoker=Ce;exports.createLogger=$t;exports.createPackageInvoker=$n;exports.createStream=Mt;exports.createUnionCodec=Be;exports.dataParamNames=Ne;exports.defineMiddleware=lt;exports.describeParams=Te;exports.dispatch=_e;exports.dispatchForPlan=jn;exports.drainStream=Pt;exports.invokeBatch=Qt;exports.isApiStream=De;exports.makeValidateLayer=Re;exports.needsEnvelopeField=je;exports.readExitCodeHook=wn;exports.readUseOptions=vn;exports.readUsePlugins=bn;exports.tsHostBinding=Kt;exports.validateLayer=It;exports.wireObservers=Se;exports.wrapMcpStructuredContent=Jt;
|