@makaio/framework 1.0.0-dev-1789160791094 → 1.0.0-dev-1789168267790

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist/.makaio-build.json +2 -2
  2. package/dist/{artifact-B-PQO_TB.mjs → artifact-BGy1hXuP.mjs} +1 -1
  3. package/dist/bus/index.d.mts +11 -4
  4. package/dist/bus/index.mjs +1 -1
  5. package/dist/bus-KqRHrusX.mjs +9 -0
  6. package/dist/contracts/adapter/index.d.mts +1 -1
  7. package/dist/contracts/artifact/index.d.mts +1 -1
  8. package/dist/contracts/artifact/index.mjs +1 -1
  9. package/dist/contracts/capabilities/index.d.mts +1 -1
  10. package/dist/contracts/client/index.d.mts +1 -1
  11. package/dist/contracts/extension/index.d.mts +2 -2
  12. package/dist/contracts/index.d.mts +34 -34
  13. package/dist/contracts/index.mjs +1 -1
  14. package/dist/contracts/materialization/index.d.mts +1 -1
  15. package/dist/contracts/session/index.d.mts +2 -2
  16. package/dist/contracts/worker/index.d.mts +1 -1
  17. package/dist/contracts/worker/index.mjs +1 -1
  18. package/dist/contracts/workflow/index.d.mts +1 -1
  19. package/dist/contracts/workflow/index.mjs +1 -1
  20. package/dist/{index-Caai1zAG.d.mts → index-BTwMms1p.d.mts} +1 -1
  21. package/dist/{index-KmZLl8Ne.d.mts → index-Bp8ZljrJ.d.mts} +3 -3
  22. package/dist/{index-Bt9YxVg5.d.mts → index-CjOJLtH7.d.mts} +16 -16
  23. package/dist/{index-DhW9WHFS.d.mts → index-Cp9olTr7.d.mts} +6 -6
  24. package/dist/{index-DN2Odrnz.d.mts → index-DOVT8mU7.d.mts} +60 -60
  25. package/dist/{index-CdPWA8co.d.mts → index-DPBh4QNY.d.mts} +48 -48
  26. package/dist/{index-EJFdPYs32.d.mts → index-D__FyAg62.d.mts} +4 -4
  27. package/dist/{index-CK5GEXLB2.d.mts → index-DtlZ4hw62.d.mts} +12 -12
  28. package/dist/{index-CU9xmTkP.d.mts → index-OLGGmjgd.d.mts} +1 -1
  29. package/dist/{index-WhgPewY4.d.mts → index-ZBm6F5_h.d.mts} +10 -10
  30. package/dist/{index-Ddk-kjif.d.mts → index-kC3LKZYJ.d.mts} +1 -1
  31. package/dist/{index-BUoIGZmF2.d.mts → index-qal7TzGP2.d.mts} +37 -37
  32. package/dist/{index-BLhNHkiK.d.mts → index-yapYXeah.d.mts} +8 -8
  33. package/dist/kernel/extension/index.d.mts +1 -1
  34. package/dist/kernel/index.d.mts +2 -2
  35. package/dist/kernel/observability/index.d.mts +1 -1
  36. package/dist/{namespace-DyWNxLt1.d.mts → namespace-BHkEHrUG.d.mts} +6 -6
  37. package/dist/{namespace-TX9DlWiQ.d.mts → namespace-BYBMtQUy.d.mts} +4 -4
  38. package/dist/{namespace--mFdPlbu.d.mts → namespace-CZJQrexB.d.mts} +18 -18
  39. package/dist/{namespace-CQPcYS-Q.d.mts → namespace-CjFT0wBT.d.mts} +2 -2
  40. package/dist/package.json +1 -1
  41. package/dist/{schemas-BGcAiQE0.d.mts → schemas-COQUToGQ.d.mts} +4 -4
  42. package/dist/{schemas-Dt1YwXLN.d.mts → schemas-D0ZZdGmV.d.mts} +10 -10
  43. package/dist/{schemas-D9WJH6We.d.mts → schemas-DNUfTOJ0.d.mts} +1 -1
  44. package/dist/{schemas-Fn-eeay32.d.mts → schemas-DNvDh0eE2.d.mts} +7 -7
  45. package/dist/{schemas-FkLOBJgq.d.mts → schemas-DYtUc2WA.d.mts} +4 -4
  46. package/dist/services/adapter-runtime/index.d.mts +3 -3
  47. package/dist/services/adapter-runtime/namespace.d.mts +1 -1
  48. package/dist/services/adapter-runtime/schemas.d.mts +1 -1
  49. package/dist/services/adapter-subsystem/index.d.mts +2 -2
  50. package/dist/services/adapter-subsystem/namespace.d.mts +1 -1
  51. package/dist/services/context-rules/index.d.mts +3 -3
  52. package/dist/services/filesystem/namespace.d.mts +6 -6
  53. package/dist/services/filesystem/schemas.d.mts +3 -3
  54. package/dist/services/index.d.mts +31 -31
  55. package/dist/services/preferences/index.d.mts +2 -2
  56. package/dist/services/preferences/schemas.d.mts +1 -1
  57. package/dist/services/preferences/storage-namespace.d.mts +2 -2
  58. package/dist/services/provider-context/index.d.mts +1 -1
  59. package/dist/services/session/index.d.mts +4 -4
  60. package/dist/services/session/messages/namespace.d.mts +1 -1
  61. package/dist/services/session/session-events/namespace.d.mts +1 -1
  62. package/dist/services/settings/namespace.d.mts +10 -10
  63. package/dist/services/subagent-template/index.d.mts +1 -1
  64. package/dist/services/subagent-template/schemas.d.mts +1 -1
  65. package/dist/{storage-namespace-BUSNKZLw.d.mts → storage-namespace-DITavhRL.d.mts} +10 -10
  66. package/dist/{types-HFQQoeAz.d.mts → types-6PHSlnbx.d.mts} +15 -15
  67. package/dist/ui-kernel/index.d.mts +4 -4
  68. package/dist/ui-kernel/pages/namespace.d.mts +4 -4
  69. package/dist/ui-kernel/pages/schemas.d.mts +1 -1
  70. package/dist/{view-builder-ADC1ng2t.d.mts → view-builder--qgYM35J.d.mts} +1 -1
  71. package/dist/{worker-CrYtBGy1.mjs → worker-Bw2UYlVO.mjs} +1 -1
  72. package/dist/workflow-engine/index.d.mts +9 -9
  73. package/dist/{workflow-mCL6Xv-J.mjs → workflow-pOvprFKW.mjs} +1 -1
  74. package/package.json +1 -1
  75. package/dist/bus-DU_7GM0J.mjs +0 -9
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 1,
3
- "fingerprint": "8624855cc77d82f5724821fa9053e5b1cf3fd507de2cad8252fb58b11a19d69c",
4
- "builtAt": "2026-09-11T21:07:38.394Z",
3
+ "fingerprint": "f844e82225821f12fb048db38976f094e5051ec515a66151622da0bd1e1e1ef5",
4
+ "builtAt": "2026-09-11T23:12:19.248Z",
5
5
  "declarations": true,
6
6
  "declarationBackend": "tsc"
7
7
  }
@@ -1 +1 @@
1
- import{o as e}from"./chunk-DTipWd-i.mjs";import{o as t,s as n}from"./json-value-DM-EjTC1.mjs";import{C as r,_ as i,a,b as o,c as s,d as c,i as l,l as ee,n as u,p as te,r as ne,t as d,u as re,w as f,x as ie}from"./schemas-BhkprYU1.mjs";import{a as p,g as ae,l as m,p as oe,s as h,t as g}from"./kind-registration-CyMf-vey.mjs";import{t as se}from"./zod-json-schema-DGWHUOK0.mjs";import{t as ce}from"./ajv-Dz-0DD7m.mjs";import{t as le}from"./2020-DvDj4r_K.mjs";import{t as ue}from"./dist-DMIaE8sg.mjs";import{z as _}from"zod";import{createBusNamespace as de}from"@makaio/framework/core";const fe=_.strictObject({evidence:r}),v=_.strictObject({kind:_.literal(`text`),text:_.string()}),[pe,me,he]=r.options,ge=_.union([pe.pick({source:!0,location:!0}).extend({content:v}),me.pick({source:!0,location:!0}).extend({content:v}),he.pick({source:!0,location:!0}).extend({content:v})]);function y(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function b(e){return e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}function _e(e,t){if(t===`#`)return{node:e,pointer:``};if(!t.startsWith(`#/`))return;let n;try{n=decodeURIComponent(t.slice(1))}catch{return}let r=e;for(let e of n.slice(1).split(`/`)){let t=e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`);if(Array.isArray(r)){if(!/^(0|[1-9]\d*)$/.test(t)||Number(t)>=r.length)return;r=r[Number(t)]}else{let e=y(r);if(!e||!Object.hasOwn(e,t))return;r=e[t]}}let i=typeof r==`boolean`?r:y(r);return i===void 0?void 0:{node:i,pointer:n}}function x(e,t){if(t===``)return!1;let n=e;for(let e of t.slice(1).split(`/`)){let t=e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`);if(n=Array.isArray(n)?n[Number(t)]:y(n)?.[t],typeof y(n)?.$id==`string`)return!0}return!1}function ve(e,t,n){if(e[`x-makaio-value-type`]!==`evidence/v1`)return;let i=r.safeParse(t);if(!i.success)throw Error(`Invalid schema-declared evidence at ${n}`);return{evidence:i.data,dataPath:n}}function ye(e,t,n,r){if(typeof t.$ref!=`string`)return!1;if(r)return!0;let i=_e(e,t.$ref);return i===void 0?!0:typeof i.node!=`boolean`&&S(e,i.node,n,x(e,i.pointer))}function S(e,t,n=new WeakSet,r=!1){let i=y(t);if(!i||n.has(i))return!1;n.add(i);let a=r||i!==e&&typeof i.$id==`string`;if(i[`x-makaio-value-type`]===`evidence/v1`||typeof i.$dynamicRef==`string`||ye(e,i,n,a)||[`additionalItems`,`additionalProperties`,`contains`,`else`,`if`,`items`,`then`,`unevaluatedItems`,`unevaluatedProperties`].some(t=>S(e,i[t],n,a))||[`allOf`,`anyOf`,`oneOf`,`prefixItems`].some(t=>Array.isArray(i[t])&&i[t].some(t=>S(e,t,n,a)))||Array.isArray(i.items)&&i.items.some(t=>S(e,t,n,a)))return!0;for(let t of[`dependentSchemas`,`dependencies`,`patternProperties`,`properties`]){let r=y(i[t]);if(r&&Object.values(r).some(t=>S(e,t,n,a)))return!0}return!1}var be=class{dataSchema;matchesSchema;occurrences=new Map;visited=new WeakMap;constructor(e,t){this.dataSchema=e,this.matchesSchema=t}extract(e){return this.visit(this.dataSchema,e,`/data`),[...this.occurrences.values()]}visit(e,t,n,r=``){let i=this.visited.get(e)??new Set;if(i.has(n))return;if(i.add(n),this.visited.set(e,i),typeof e.$dynamicRef==`string`)throw Error(`Evidence discovery does not support active $dynamicRef at ${n}`);if(typeof e.$ref==`string`){if(x(this.dataSchema,r))throw Error(`Evidence discovery does not support local $ref inside nested $id resource at ${n}`);let i=_e(this.dataSchema,e.$ref);if(i===void 0)throw Error(`Cannot resolve local schema reference ${e.$ref} at ${n}`);if(typeof i.node!=`boolean`&&this.visit(i.node,t,n,i.pointer),this.dataSchema.$schema!==`https://json-schema.org/draft/2020-12/schema`)return}let a=ve(e,t,n);if(a){this.occurrences.set(n,a);return}this.visitCombiners(e,t,n,r),this.visitConditional(e,t,n,r),this.visitDependencies(e,t,n,r),this.assertSupportedApplicators(e,n,r),Array.isArray(t)?this.visitArray(e,t,n,r):typeof t==`object`&&t&&this.visitObject(e,t,n,r)}visitCombiners(e,t,n,r){for(let i of[`allOf`,`anyOf`,`oneOf`]){let a=e[i];if(Array.isArray(a))for(let[e,o]of a.entries()){let a=y(o),s=`${r}/${i}/${e}`;a&&(i===`allOf`||this.matchesSchema(this.dataSchema,s,t))&&this.visit(a,t,n,s)}}}visitConditional(e,t,n,r){let i=typeof e.if==`boolean`?e.if:y(e.if);if(i===void 0)return;let a=`${r}/if`,o=this.matchesSchema(this.dataSchema,a,t);o&&typeof i!=`boolean`&&this.visit(i,t,n,a);let s=o?`then`:`else`,c=y(e[s]);c&&this.visit(c,t,n,`${r}/${s}`)}visitDependencies(e,t,n,r){if(!(typeof t!=`object`||!t||Array.isArray(t)))for(let i of[`dependentSchemas`,`dependencies`]){let a=y(e[i]);if(a)for(let[e,o]of Object.entries(a)){let a=y(o);Object.hasOwn(t,e)&&a&&this.visit(a,t,n,`${r}/${i}/${b(e)}`)}}}assertSupportedApplicators(e,t,n){for(let r of[`unevaluatedProperties`,`unevaluatedItems`])if(S(this.dataSchema,e[r],void 0,x(this.dataSchema,n)))throw Error(`Evidence under unsupported ${r} applicator at ${t}`)}visitArray(e,t,n,r){let i=Array.isArray(e.prefixItems),a=i?e.prefixItems:Array.isArray(e.items)?e.items:[];a.forEach((e,a)=>{let o=y(e),s=i?`prefixItems`:`items`;o&&a<t.length&&this.visit(o,t[a],`${n}/${a}`,`${r}/${s}/${a}`)});let o=Array.isArray(e.items)?y(e.additionalItems):y(e.items);if(o){let i=Array.isArray(e.items)?`additionalItems`:`items`;t.slice(a.length).forEach((e,t)=>this.visit(o,e,`${n}/${a.length+t}`,`${r}/${i}`))}this.visitContains(e,t,n,r)}visitContains(e,t,n,r){let i=y(e.contains);if(!i)return;let a=`${r}/contains`;t.forEach((e,t)=>{this.matchesSchema(this.dataSchema,a,e)&&this.visit(i,e,`${n}/${t}`,a)})}visitObject(e,t,n,r){let i=y(e.properties),a=y(e.patternProperties);for(let[o,s]of Object.entries(t)){let t=b(o),c=i!==void 0&&Object.hasOwn(i,o),l=y(i?.[o]);l&&this.visit(l,s,`${n}/${t}`,`${r}/properties/${t}`);let ee=this.visitPatterns(a,o,s,`${n}/${t}`,r),u=y(e.additionalProperties);!c&&!ee&&u&&this.visit(u,s,`${n}/${t}`,`${r}/additionalProperties`)}}visitPatterns(e,t,n,r,i){let a=!1;for(let[o,s]of Object.entries(e??{})){if(!new RegExp(o,`u`).test(t))continue;a=!0;let e=y(s);e&&this.visit(e,n,r,`${i}/patternProperties/${b(o)}`)}return a}};function xe(e,t,n){return new be(e,n.matchesSchema).extract(t)}function Se(e){let{dataSchema:t,hooks:n,...r}=e,i={$schema:`https://json-schema.org/draft/2020-12/schema`,...se(t)};oe(i);let a=p.parse({...r,dataSchema:i});if(a.kind!==e.kind)throw Error(`Artifact kind identifiers must not contain surrounding whitespace`);let o=_.fromJSONSchema(a.dataSchema),s=_.unknown().superRefine((e,t)=>{let n=o.safeParse(e);if(!n.success)for(let e of n.error.issues)t.addIssue({code:`custom`,path:e.path,message:e.message})}).pipe(t).superRefine((e,t)=>{try{ae(e,a.titlePath)}catch(e){t.addIssue({code:`custom`,path:a.titlePath.split(`.`),message:e instanceof Error?e.message:`Artifact title must be a nonblank string`})}});return{...structuredClone(a),kind:e.kind,schemaVersion:e.schemaVersion,dataSchema:s,...n?{hooks:n}:{},toRegistration:()=>structuredClone(a)}}var Ce=e(ce(),1),we=e(le(),1),Te=e(ue(),1);function Ee(e){let t={allErrors:!0,strict:!1,strictSchema:!0},n=e.dataSchema.$schema===`https://json-schema.org/draft/2020-12/schema`?new we.default(t):new Ce.default(t);return(0,Te.default)(n),n.addKeyword({keyword:ie,schemaType:`string`,valid:!0}),n.compile(e.dataSchema)}function De(e){return e.replace(/~1/gu,`/`).replace(/~0/gu,`~`)}function Oe(e){let t=e.instancePath.split(`/`).slice(1).map(De),n=e.keyword===`required`?e.params.missingProperty:e.params.additionalProperty;return typeof n==`string`&&(e.keyword===`required`||e.keyword===`additionalProperties`)&&t.push(n),t.join(`.`)}function ke(e){if(e.keyword!==`type`)return;let t=e.params.type;if(typeof t==`string`)return t;if(Array.isArray(t)&&t.every(e=>typeof e==`string`))return t.join(` | `)}const Ae=t.array();function je(e){if(e.keyword!==`enum`)return;let t=Ae.safeParse(e.params.allowedValues);return t.success?t.data:void 0}function Me(e){return(e??[]).map(e=>{let t=ke(e),n=je(e);return{path:Oe(e),reason:e.message??`violates ${e.keyword}`,...t===void 0?{}:{expectedType:t},...n===void 0?{}:{allowedValues:n}}})}function Ne(e){return Ee(e)}function Pe(e){let t=Ee(e);return e=>t(e)?{valid:!0}:{valid:!1,issues:Me(t.errors)}}function Fe(e){return{hooks:[...e.hooks]}}const Ie=[`inline`,`summary`,`link`,`omit`],C=_.string().min(1),w=_.object({kinds:_.array(_.string().min(1)).optional(),hint:C.optional(),depth:_.number().int().min(1).max(20).optional(),nested:_.lazy(()=>T).optional()}),T=_.record(_.string().min(1),w);function E(e){return JSON.stringify([e.kind,e.id,e.revision])}const D=_.enum([`not-selected`,`not-found`,`depth-exceeded`,`unsupported-ref-class`,`cycle-detected`]),O=_.object({target:ee,sourceRef:f,relationType:_.string().min(1),hint:C,status:_.enum([`resolved`,`unresolved`]),reason:D.optional()}).superRefine((e,t)=>{e.status===`unresolved`&&e.reason===void 0&&t.addIssue({code:_.ZodIssueCode.custom,path:[`reason`],message:`reason is required for unresolved artifact context refs`}),e.status===`resolved`&&e.reason!==void 0&&t.addIssue({code:_.ZodIssueCode.custom,path:[`reason`],message:`reason must be omitted for resolved artifact context refs`}),e.status===`resolved`&&e.target.refClass!==`artifact`&&t.addIssue({code:_.ZodIssueCode.custom,path:[`target`],message:`resolved artifact context refs must target an artifact revision`})}),k=_.object({rootRef:f,refs:_.array(O),resolved:_.array(c)}).superRefine((e,t)=>{let n=new Set(e.resolved.map(E));n.has(E(e.rootRef))||t.addIssue({code:_.ZodIssueCode.custom,path:[`resolved`],message:`resolved artifact context wire payloads must include the root artifact revision`}),e.refs.forEach((e,r)=>{n.has(E(e.sourceRef))||t.addIssue({code:_.ZodIssueCode.custom,path:[`refs`,r,`sourceRef`],message:`artifact context ref sources must have a matching revision in resolved`}),!(e.status!==`resolved`||e.target.refClass!==`artifact`)&&(n.has(E(e.target))||t.addIssue({code:_.ZodIssueCode.custom,path:[`refs`,r,`target`],message:`resolved artifact context refs must have a matching revision in resolved`}))})});function Le(e){let t=k.parse(e),n=new Map(t.resolved.map(e=>[A(e),e])),r=new Map;for(let e of t.refs){let t=A(e.sourceRef),n=r.get(t);n||(n=[],r.set(t,n)),n.push(e)}let i=n.get(A(t.rootRef));if(!i)throw Error(`Resolved artifact context is missing root artifact '${A(t.rootRef)}'`);let a=Re(t.rootRef,i,`inline`,r,n);return{root:a,flatten(){let e=[];return Ve(a,e),e}}}function Re(e,t,n,r,i){return{status:`resolved`,ref:e,artifact:t,hint:n,children:Be(e,r,i,new Set([A(e)]))}}function ze(e,t,n,r,i,a,o){let s=A(e),c=new Set(o);return c.add(s),{status:`resolved`,ref:e,artifact:t,relation:n,hint:r,children:Be(e,i,a,c)}}function Be(e,t,n,r){return(t.get(A(e))??[]).map(e=>{if(e.status===`unresolved`)return{status:`unresolved`,target:e.target,relation:e.relationType,hint:e.hint,reason:e.reason};if(e.target.refClass!==`artifact`)throw Error(`Resolved artifact context refs must target an artifact revision`);let i=A(e.target),a=n.get(i);if(!a)throw Error(`Resolved artifact context is missing target artifact '${i}'`);return r.has(i)?{status:`unresolved`,target:e.target,relation:e.relationType,hint:e.hint,reason:`cycle-detected`}:ze(e.target,a,e.relationType,e.hint,t,n,r)})}function Ve(e,t){if(e.status!==`unresolved`){t.push(e.artifact);for(let n of e.children)Ve(n,t)}}function A(e){return JSON.stringify([e.kind,e.id,e.revision])}const j=[`$set`,`$unset`,`$push`,`$pull`],M=`[A-Za-z_$][A-Za-z0-9_$]*`,N=`[A-Za-z_$][A-Za-z0-9_$-]*`,He=`(?:0|[1-9][0-9]*)`,Ue=`(?:${`\\$\\[${M}\\]`}|${He}|${N})`,We=RegExp(`^${N}(?:\\.${Ue})*$`),Ge=RegExp(`^${M}(?:\\.${N})*$`),Ke=RegExp(`^${He}$`),qe=RegExp(`^\\$\\[(${M})\\]$`),P=_.string().regex(We,`Expected a data-relative path of object properties, array positions, or $[filter] placeholders`);function Je(e){let t=qe.exec(e);return t?.[1]===void 0?Ke.test(e)?{kind:`index`,index:Number(e)}:{kind:`property`,name:e}:{kind:`filter`,placeholder:t[1]}}function Ye(e){return e.split(`.`).map(Je)}function Xe(e){return Ye(e).flatMap(e=>e.kind===`filter`?[e.placeholder]:[])}const Ze=n(_.record(_.string().regex(Ge,`Expected a filter key of the form name or name.field.path`),t),{prototypeKey:`an array filter cannot compare a __proto__ key, which JSON transport drops`,nonPlainObject:`an array filter must be a plain object of comparison keys`,symbolKey:`an array filter cannot carry symbol-keyed comparisons`,nonEnumerableKey:`an array filter cannot carry non-enumerable comparison keys`,extraArrayKey:`an array filter must be a plain object, not an array`});function Qe(e){let t=new Set(Object.keys(e).map(e=>e.split(`.`)[0]));if(t.size!==1)return;let[n]=t;return n!==void 0&&n.length>0?n:void 0}function F(e,t){return n(_.record(P,t),{prototypeKey:`${e} cannot address __proto__, which JSON transport drops`,nonPlainObject:`${e} must be a plain object of path instructions`,symbolKey:`${e} cannot carry symbol-keyed instructions`,nonEnumerableKey:`${e} cannot carry non-enumerable instructions`,extraArrayKey:`${e} must be a plain object, not an array`})}const $e=_.literal(!0),et=_.strictObject({$set:F(`$set`,t).optional(),$unset:F(`$unset`,$e).optional(),$push:F(`$push`,t).optional(),$pull:F(`$pull`,t).optional(),arrayFilters:_.array(Ze).optional()});function I(e){return j.flatMap(t=>Object.entries(e[t]??{}).map(([e,n])=>({operator:t,path:e,value:n})))}function tt(e,t){let n=I(e),r=new Map;(e.arrayFilters??[]).forEach((e,n)=>{let i=Qe(e);if(i===void 0){t.addIssue({code:`custom`,path:[`arrayFilters`,n],message:`An array filter must bind exactly one placeholder name across all of its keys`});return}if(r.has(i)){t.addIssue({code:`custom`,path:[`arrayFilters`,n],message:`Array filter placeholder ${i} is already bound by another filter`});return}r.set(i,n)});let i=new Set;for(let{operator:e,path:a}of n)for(let n of Xe(a))i.add(n),r.has(n)||t.addIssue({code:`custom`,path:[e,a],message:`Path uses placeholder $[${n}] without a matching entry in arrayFilters`});for(let[e,n]of r)i.has(e)||t.addIssue({code:`custom`,path:[`arrayFilters`,n],message:`Array filter binds placeholder ${e}, which no path uses`})}const nt=et.superRefine(tt).superRefine((e,t)=>{I(e).length===0&&t.addIssue({code:`custom`,message:`Declare at least one of ${j.join(`, `)}`})}),rt=et.superRefine(tt),it=_.strictObject({kind:f.shape.kind,id:f.shape.id}),at=_.strictObject({ref:it,baseRevision:f.shape.revision,patch:rt,dryRun:_.boolean().optional(),schemaVersion:m.optional().describe(`Target schema version for the patched revision; defaults to the base revision's. Use it to migrate an artifact left at an older version by a kind bump.`),statusPath:te.optional(),representations:re.strict().nullable().optional().describe(`Rendering hints (markdown, summary, plaintext) for the new revision. Omit to keep the previous revision's hints. An object replaces all of them, it does not merge: send every hint you want to keep. null clears them.`)}).superRefine((e,t)=>{e.schemaVersion===void 0&&I(e.patch).length===0&&t.addIssue({code:`custom`,path:[`patch`],message:`Declare at least one of ${j.join(`, `)}, or name a schemaVersion to migrate a payload that already fits`})}),ot=[`ARTIFACT_NOT_FOUND`,`BASE_REVISION_CONFLICT`,`KIND_NOT_REGISTERED`,`SCHEMA_VERSION_MISMATCH`,`PATH_NOT_DECLARED`,`PATH_NOT_RESOLVABLE`,`TARGET_NOT_A_COLLECTION`,`UNSUPPORTED_TARGET`,`NO_MATCH`,`SCHEMA_VALIDATION_FAILED`,`NO_CHANGE`,`STORE_REJECTED`,`HOST_FAILED`],st=_.strictObject({path:_.string(),reason:_.string().min(1),expectedType:_.string().min(1).optional(),allowedValues:_.array(t).optional()}),ct=_.strictObject({code:_.enum(ot),message:_.string().min(1),operator:_.enum(j).optional(),path:P.optional(),currentRevision:f.shape.revision.optional(),issues:_.array(st).optional(),repair:_.string().min(1)}).superRefine((e,t)=>{e.code===`BASE_REVISION_CONFLICT`&&e.currentRevision===void 0&&t.addIssue({code:_.ZodIssueCode.custom,message:`A BASE_REVISION_CONFLICT must name the revision the artifact carries.`,path:[`currentRevision`]})}),lt=_.strictObject({operator:_.enum(j),path:P,matched:_.number().int().positive()}),ut=_.strictObject({from:m,to:m}).refine(e=>e.to>e.from,{path:[`to`],message:`A migration moves the artifact forward to a newer schema version`}),dt=_.strictObject({ok:_.literal(!0),base:f,operations:_.array(lt),migration:ut.optional()});function ft(e,t){e.operations.length===0&&e.migration===void 0&&t.addIssue({code:`custom`,path:[`operations`],message:`A success without a migration must report at least one applied instruction`})}const pt=dt.extend({dryRun:_.literal(!0)}).superRefine(ft),mt=dt.extend({dryRun:_.literal(!1),artifact:f}).superRefine(ft),ht=_.discriminatedUnion(`dryRun`,[pt,mt]),gt=_.strictObject({ok:_.literal(!1),error:ct}),_t=_.union([ht,gt]),L=f.pick({kind:!0,id:!0}),R=_.number().int().positive(),z=R,B={knowledge:`valid`,commitment:`proposed`,interaction:`open`},V=_.discriminatedUnion(`category`,[_.strictObject({category:_.literal(`knowledge`),state:_.enum(g.knowledge),version:z}),_.strictObject({category:_.literal(`commitment`),state:_.enum(g.commitment),version:z}),_.strictObject({category:_.literal(`interaction`),state:_.enum(g.interaction),version:z})]).superRefine((e,t)=>{e.version===1&&e.state!==B[e.category]&&t.addIssue({code:`custom`,path:[`state`],message:`Lifecycle version 1 is reserved for the category initial state`})}),H=_.union([V,_.strictObject({category:_.literal(`record`)})]),U=_.string().trim().min(1),vt=_.strictObject({kind:U,ref:U}),W=_.discriminatedUnion(`kind`,[_.strictObject({kind:_.literal(`revision-assessment`),assessedRevision:f.shape.revision,source:vt.optional()}),_.strictObject({kind:_.literal(`handover`),source:vt})]),yt={artifact:L,expectedVersion:z,state:h,situation:W,reason:U.optional()},G=_.strictObject(yt),bt=_.strictObject({...yt,actor:d}),xt={valid:[`retired`],retired:[`valid`],proposed:[`decided`],decided:[`fulfilled`,`revoked`],fulfilled:[],revoked:[],open:[`resolved`,`closed-without-resolution`],resolved:[],"closed-without-resolution":[]};function K(e,t){return xt[e].includes(t)}const St={artifact:L,lifecycle:V,actor:d,timestamp:_.number().int().nonnegative(),observedRevision:f.shape.revision},Ct=_.strictObject({...St,operation:_.literal(`initialized`)}).superRefine((e,t)=>{(e.lifecycle.version!==1||e.lifecycle.state!==B[e.lifecycle.category])&&t.addIssue({code:`custom`,path:[`lifecycle`],message:`Initialization requires the category initial state and version 1`})});function wt(e,t){return t===`retired`||e===`retired`&&t===`valid`}const Tt=`Retiring or reinstating knowledge requires a reason`,q=_.strictObject({...St,operation:_.literal(`transitioned`),previousState:h,situation:W,reason:G.shape.reason}).superRefine((e,t)=>{(!K(e.previousState,e.lifecycle.state)||e.lifecycle.version<=1)&&t.addIssue({code:`custom`,path:[`lifecycle`],message:`History requires a category-compatible transition after initialization`}),wt(e.previousState,e.lifecycle.state)&&!e.reason&&t.addIssue({code:`custom`,path:[`reason`],message:Tt}),e.situation.kind===`revision-assessment`&&e.situation.assessedRevision!==e.observedRevision&&t.addIssue({code:`custom`,path:[`situation`],message:`An assessment cannot authorize a different observed content revision`})}),Et=_.discriminatedUnion(`operation`,[Ct,q]),J=_.discriminatedUnion(`reason`,[_.strictObject({reason:_.literal(`lifecycle-version-conflict`),expectedVersion:z,current:V,requestedState:h}),_.strictObject({reason:_.literal(`content-basis-conflict`),assessedRevision:f.shape.revision,currentRevision:f.shape.revision}),_.strictObject({reason:_.literal(`invalid-transition`),current:H,requestedState:h}),_.strictObject({reason:_.literal(`precondition-failed`),current:V,requestedState:h})]),Y=`artifact-lifecycle-rejected`;var X=class extends Error{code=Y;data;constructor(e,t){super(e),this.name=`ArtifactLifecycleError`,this.data=J.parse(t)}};function Dt(e){return e===`record`?{category:`record`}:V.parse({category:e,state:B[e],version:1})}function Ot(e){let t=H.parse(e.current),n=f.shape.revision.parse(e.currentRevision),r=bt.parse(e.command);if(t.category===`record`)throw new X(`Record artifacts do not have a lifecycle`,{reason:`invalid-transition`,current:t,requestedState:r.state});if(r.expectedVersion!==t.version)throw new X(`Artifact lifecycle changed since the supplied baseline`,{reason:`lifecycle-version-conflict`,expectedVersion:r.expectedVersion,current:t,requestedState:r.state});if(r.situation.kind===`revision-assessment`&&r.situation.assessedRevision!==n)throw new X(`Assessed content revision is no longer current`,{reason:`content-basis-conflict`,assessedRevision:r.situation.assessedRevision,currentRevision:n});if(!K(t.state,r.state))throw new X(`Artifact lifecycle transition is not allowed`,{reason:`invalid-transition`,current:t,requestedState:r.state});if(wt(t.state,r.state)&&!r.reason)throw new X(Tt,{reason:`precondition-failed`,current:t,requestedState:r.state});return V.parse({...t,state:r.state,version:t.version+1})}const kt=_.strictObject({artifact:L}),At=_.strictObject({lifecycle:H}),jt=_.strictObject({artifact:L,afterVersion:R.optional(),limit:_.number().int().min(1).max(100).default(50)}),Mt=_.strictObject({entries:_.array(Et).max(100),nextCursor:R.optional()}).superRefine(({entries:e,nextCursor:t},n)=>{let r=e[0],i;for(let[t,a]of e.entries()){let e=a.artifact.kind===r?.artifact.kind&&a.artifact.id===r?.artifact.id,o=i===void 0||a.lifecycle.version===i.lifecycle.version+1,s=i===void 0||a.operation===`transitioned`&&a.lifecycle.category===i.lifecycle.category&&a.previousState===i.lifecycle.state;if(!e||!o||!s){n.addIssue({code:`custom`,path:[`entries`,t],message:`History pages contain one artifact in contiguous ascending, state-linked order`});break}i=a}t!==void 0&&t!==i?.lifecycle.version&&n.addIssue({code:`custom`,path:[`nextCursor`],message:`nextCursor must equal the last returned lifecycle version`})}),Z=_.strictObject({entry:q}),Nt=Z,Pt=_.strictObject({code:_.literal(Y),message:_.string().min(1),data:J});function Ft(e){return{code:e.code,message:e.message,data:e.data}}function It(e,t){switch(t.reason){case`content-basis-conflict`:return zt(e,t);case`lifecycle-version-conflict`:return[...Lt(e,t),...Rt(e,t)];case`invalid-transition`:case`precondition-failed`:return[...Lt(e,t),...Bt(e,t)]}}function Lt(e,t){return t.requestedState===e.state?[]:[{path:[`requestedState`],message:`Rejection requestedState must match the rejected transition`}]}function Rt(e,t){let n=[];return t.expectedVersion!==e.expectedVersion&&n.push({path:[`expectedVersion`],message:`Version conflict baseline must match the rejected transition`}),t.current.version===e.expectedVersion&&n.push({path:[`current`,`version`],message:`Version conflict requires a current version different from the supplied baseline`}),n}function zt(e,t){let n=[];return(e.situation.kind!==`revision-assessment`||t.assessedRevision!==e.situation.assessedRevision)&&n.push({path:[`assessedRevision`],message:`Content conflict must identify the rejected revision assessment`}),t.currentRevision===t.assessedRevision&&n.push({path:[`currentRevision`],message:`Content conflict requires a current revision different from the assessed revision`}),n}function Bt(e,t){if(t.current.category===`record`)return[];let n=[];t.current.version!==e.expectedVersion&&n.push({path:[`current`,`version`],message:`A rejection after the version check must report the supplied baseline version`});let r=K(t.current.state,t.requestedState);return t.reason===`invalid-transition`&&r&&n.push({path:[`reason`],message:`invalid-transition requires a transition the lifecycle matrix disallows`}),t.reason===`precondition-failed`&&!r&&n.push({path:[`reason`],message:`precondition-failed requires a transition the lifecycle matrix allows`}),n}const Vt=_.strictObject({transition:G,error:Pt}).superRefine(({transition:e,error:t},n)=>{for(let r of It(e,t.data))n.addIssue({code:`custom`,path:[`error`,`data`,...r.path],message:r.message})}),Q={"lifecycle.get":{request:kt,response:At},"lifecycle.history":{request:jt,response:Mt},"lifecycle.transition":{request:G,response:Z},"lifecycle.committed":Nt,"lifecycle.rejected":Vt},Ht={...Q,"kind.register":{request:p,response:_.object({registered:_.boolean()})},"kind.list":{request:_.object({kind:_.string().min(1).optional()}),response:_.object({kinds:_.array(p)})},"relation-type.register":{request:o,response:_.object({registered:_.boolean()})},"relation-type.list":{request:_.object({type:_.string().min(1).optional()}),response:_.object({relationTypes:_.array(o)})},create:{request:c.omit({id:!0,revision:!0,timestamp:!0}).extend({id:f.shape.id.optional()}),response:_.object({artifact:c})},revise:{request:_.object({previous:f,statusPath:te.optional(),revision:c.omit({id:!0,revision:!0,timestamp:!0})}),response:_.object({artifact:c})},patch:{request:at,response:_t},resolve:{request:_.object({ref:f}),response:_.object({artifact:c.nullable()})},query:{request:a,response:_.object({artifacts:_.array(c)})},compare:{request:u,response:ne},"evidence.resolve":{request:fe,response:ge},resolveContext:{request:_.object({ref:f,selectors:T.optional(),maxDepth:_.number().int().min(1).max(20).default(5)}),response:_.object({context:k})},created:_.object({artifact:c}),revised:_.object({previous:f,artifact:c}),"relation.added":_.object({artifact:f,relation:s}),"observation.added":_.object({artifact:f,observation:l}),"status.changed":_.object({artifact:f,path:_.string().min(1),previous:_.unknown().optional(),current:_.unknown().optional()}),"kind.changed":_.object({kind:_.string().min(1),schemaVersion:m})},Ut=de(`artifact`,Ht),Wt=Ut.subjects,Gt=_.discriminatedUnion(`refClass`,[f.omit({revision:!0}),i]);function Kt(e){if(e.refClass===`artifact`)return{refClass:`artifact`,kind:e.kind,id:e.id};if(e.refClass===`entity`)return{refClass:`entity`,entityType:e.entityType,id:e.id}}function $(e){return e.refClass===`artifact`?JSON.stringify([`artifact`,e.kind,e.id]):JSON.stringify([`entity`,e.entityType,e.id])}function qt(e){return e.refClass===`artifact`?`artifact:${e.kind}/${e.id}`:`entity:${e.entityType}/${e.id}`}const Jt=[`relation-target`];function Yt(e,t){if(!e||e.length===0)return{ok:!0,rules:[]};let n=[];for(let[r,i]of e.entries()){for(let[e,a]of i.by.entries())(!Jt.includes(a.kind)||!t.includes(a.kind))&&n.push({ruleIndex:r,selectorIndex:e,capability:a.kind,message:`rule #${r}, selector #${e}: '${a.kind}' selectors are not supported`});i.lifecycleStates!==void 0&&!t.includes(`lifecycle-states`)&&n.push({ruleIndex:r,capability:`lifecycle-states`,message:`rule #${r}: lifecycleStates is declared but 'lifecycle-states' is not a supported capability`})}return n.length>0?{ok:!1,issues:n}:{ok:!0,rules:e}}function Xt(e,t,n,r){if(e.kind===`data`)return{ruleIndex:n,selectorIndex:r,reason:`unsupported-selector`,message:`rule #${n}, selector #${r}: data-path selectors cannot be derived from relations`};let{relationType:i}=e,a=t.filter(e=>e.type===i),o=new Set,s,c;for(let e of a){let t=Kt(e.target);if(t===void 0){c=e.target.refClass;break}o.add($(t)),s=t}return c===void 0?s===void 0?{ruleIndex:n,selectorIndex:r,reason:`missing-target`,relationType:i,message:`rule #${n}, selector #${r}, relation '${i}': no relations of this type found`}:o.size>1?{ruleIndex:n,selectorIndex:r,reason:`ambiguous-target`,relationType:i,message:`rule #${n}, selector #${r}, relation '${i}': ${o.size} distinct targets; expected exactly one`}:{type:i,target:s}:{ruleIndex:n,selectorIndex:r,reason:`unsupported-target`,relationType:i,message:`rule #${n}, selector #${r}, relation '${i}': found a relation with refClass '${c}'; only artifact and entity targets are supported`}}function Zt(e,t){let n=[],r=[];for(let[i,a]of e.entries()){let e=a.by.map((e,n)=>Xt(e,t,i,n)),o=e.find(e=>`reason`in e);if(o!==void 0){r.push(o);continue}let s=e.filter(e=>!(`reason`in e)),c=JSON.stringify(s.map(e=>[e.type,$(e.target)]));n.push({rule:a,ruleIndex:i,parts:s,serialized:c})}return{keys:n,issues:r}}function Qt(e){return e.parts.map(e=>`${e.type} → ${qt(e.target)}`).join(`; `)}export{Qe as $,bt as A,nt as B,X as C,J as D,Ct as E,Dt as F,ut as G,ct as H,K as I,mt as J,lt as K,ot as L,q as M,R as N,W as O,Ot as P,it as Q,j as R,H as S,L as T,gt as U,pt as V,st as W,_t as X,at as Y,ht as Z,Vt as _,fe as _t,Kt as a,O as at,Ft as b,Ut as c,Ie as ct,Nt as d,T as dt,I as et,Pt as f,Fe as ft,Mt as g,xe as gt,jt as h,Se as ht,Gt as i,Le as it,G as j,V as k,Ht as l,w as lt,At as m,Ne as mt,Zt as n,Je as nt,qt as o,D as ot,kt as p,Pe as pt,P as q,Qt as r,Ye as rt,$ as s,k as st,Yt as t,Xe as tt,Wt as u,C as ut,Q as v,ge as vt,Et as w,Y as x,Z as y,Ze as z};
1
+ import{o as e}from"./chunk-DTipWd-i.mjs";import{o as t,s as n}from"./json-value-DM-EjTC1.mjs";import{C as r,_ as i,a,b as o,c as s,d as c,i as l,l as ee,n as u,p as te,r as ne,t as d,u as re,w as f,x as ie}from"./schemas-BhkprYU1.mjs";import{a as p,g as ae,l as m,p as oe,s as h,t as g}from"./kind-registration-CyMf-vey.mjs";import{t as se}from"./zod-json-schema-DGWHUOK0.mjs";import{t as ce}from"./ajv-Dz-0DD7m.mjs";import{t as le}from"./2020-DvDj4r_K.mjs";import{t as ue}from"./dist-DMIaE8sg.mjs";import{z as _}from"zod";import{createBusNamespace as de}from"@makaio/framework/core";const fe=_.strictObject({evidence:r}),v=_.strictObject({kind:_.literal(`text`),text:_.string()}),[pe,me,he]=r.options,ge=_.union([pe.pick({source:!0,location:!0}).extend({content:v}),me.pick({source:!0,location:!0}).extend({content:v}),he.pick({source:!0,location:!0}).extend({content:v})]);function y(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function b(e){return e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}function _e(e,t){if(t===`#`)return{node:e,pointer:``};if(!t.startsWith(`#/`))return;let n;try{n=decodeURIComponent(t.slice(1))}catch{return}let r=e;for(let e of n.slice(1).split(`/`)){let t=e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`);if(Array.isArray(r)){if(!/^(0|[1-9]\d*)$/.test(t)||Number(t)>=r.length)return;r=r[Number(t)]}else{let e=y(r);if(!e||!Object.hasOwn(e,t))return;r=e[t]}}let i=typeof r==`boolean`?r:y(r);return i===void 0?void 0:{node:i,pointer:n}}function x(e,t){if(t===``)return!1;let n=e;for(let e of t.slice(1).split(`/`)){let t=e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`);if(n=Array.isArray(n)?n[Number(t)]:y(n)?.[t],typeof y(n)?.$id==`string`)return!0}return!1}function ve(e,t,n){if(e[`x-makaio-value-type`]!==`evidence/v1`)return;let i=r.safeParse(t);if(!i.success)throw Error(`Invalid schema-declared evidence at ${n}`);return{evidence:i.data,dataPath:n}}function ye(e,t,n,r){if(typeof t.$ref!=`string`)return!1;if(r)return!0;let i=_e(e,t.$ref);return i===void 0?!0:typeof i.node!=`boolean`&&S(e,i.node,n,x(e,i.pointer))}function S(e,t,n=new WeakSet,r=!1){let i=y(t);if(!i||n.has(i))return!1;n.add(i);let a=r||i!==e&&typeof i.$id==`string`;if(i[`x-makaio-value-type`]===`evidence/v1`||typeof i.$dynamicRef==`string`||ye(e,i,n,a)||[`additionalItems`,`additionalProperties`,`contains`,`else`,`if`,`items`,`then`,`unevaluatedItems`,`unevaluatedProperties`].some(t=>S(e,i[t],n,a))||[`allOf`,`anyOf`,`oneOf`,`prefixItems`].some(t=>Array.isArray(i[t])&&i[t].some(t=>S(e,t,n,a)))||Array.isArray(i.items)&&i.items.some(t=>S(e,t,n,a)))return!0;for(let t of[`dependentSchemas`,`dependencies`,`patternProperties`,`properties`]){let r=y(i[t]);if(r&&Object.values(r).some(t=>S(e,t,n,a)))return!0}return!1}var be=class{dataSchema;matchesSchema;occurrences=new Map;visited=new WeakMap;constructor(e,t){this.dataSchema=e,this.matchesSchema=t}extract(e){return this.visit(this.dataSchema,e,`/data`),[...this.occurrences.values()]}visit(e,t,n,r=``){let i=this.visited.get(e)??new Set;if(i.has(n))return;if(i.add(n),this.visited.set(e,i),typeof e.$dynamicRef==`string`)throw Error(`Evidence discovery does not support active $dynamicRef at ${n}`);if(typeof e.$ref==`string`){if(x(this.dataSchema,r))throw Error(`Evidence discovery does not support local $ref inside nested $id resource at ${n}`);let i=_e(this.dataSchema,e.$ref);if(i===void 0)throw Error(`Cannot resolve local schema reference ${e.$ref} at ${n}`);if(typeof i.node!=`boolean`&&this.visit(i.node,t,n,i.pointer),this.dataSchema.$schema!==`https://json-schema.org/draft/2020-12/schema`)return}let a=ve(e,t,n);if(a){this.occurrences.set(n,a);return}this.visitCombiners(e,t,n,r),this.visitConditional(e,t,n,r),this.visitDependencies(e,t,n,r),this.assertSupportedApplicators(e,n,r),Array.isArray(t)?this.visitArray(e,t,n,r):typeof t==`object`&&t&&this.visitObject(e,t,n,r)}visitCombiners(e,t,n,r){for(let i of[`allOf`,`anyOf`,`oneOf`]){let a=e[i];if(Array.isArray(a))for(let[e,o]of a.entries()){let a=y(o),s=`${r}/${i}/${e}`;a&&(i===`allOf`||this.matchesSchema(this.dataSchema,s,t))&&this.visit(a,t,n,s)}}}visitConditional(e,t,n,r){let i=typeof e.if==`boolean`?e.if:y(e.if);if(i===void 0)return;let a=`${r}/if`,o=this.matchesSchema(this.dataSchema,a,t);o&&typeof i!=`boolean`&&this.visit(i,t,n,a);let s=o?`then`:`else`,c=y(e[s]);c&&this.visit(c,t,n,`${r}/${s}`)}visitDependencies(e,t,n,r){if(!(typeof t!=`object`||!t||Array.isArray(t)))for(let i of[`dependentSchemas`,`dependencies`]){let a=y(e[i]);if(a)for(let[e,o]of Object.entries(a)){let a=y(o);Object.hasOwn(t,e)&&a&&this.visit(a,t,n,`${r}/${i}/${b(e)}`)}}}assertSupportedApplicators(e,t,n){for(let r of[`unevaluatedProperties`,`unevaluatedItems`])if(S(this.dataSchema,e[r],void 0,x(this.dataSchema,n)))throw Error(`Evidence under unsupported ${r} applicator at ${t}`)}visitArray(e,t,n,r){let i=Array.isArray(e.prefixItems),a=i?e.prefixItems:Array.isArray(e.items)?e.items:[];a.forEach((e,a)=>{let o=y(e),s=i?`prefixItems`:`items`;o&&a<t.length&&this.visit(o,t[a],`${n}/${a}`,`${r}/${s}/${a}`)});let o=Array.isArray(e.items)?y(e.additionalItems):y(e.items);if(o){let i=Array.isArray(e.items)?`additionalItems`:`items`;t.slice(a.length).forEach((e,t)=>this.visit(o,e,`${n}/${a.length+t}`,`${r}/${i}`))}this.visitContains(e,t,n,r)}visitContains(e,t,n,r){let i=y(e.contains);if(!i)return;let a=`${r}/contains`;t.forEach((e,t)=>{this.matchesSchema(this.dataSchema,a,e)&&this.visit(i,e,`${n}/${t}`,a)})}visitObject(e,t,n,r){let i=y(e.properties),a=y(e.patternProperties);for(let[o,s]of Object.entries(t)){let t=b(o),c=i!==void 0&&Object.hasOwn(i,o),l=y(i?.[o]);l&&this.visit(l,s,`${n}/${t}`,`${r}/properties/${t}`);let ee=this.visitPatterns(a,o,s,`${n}/${t}`,r),u=y(e.additionalProperties);!c&&!ee&&u&&this.visit(u,s,`${n}/${t}`,`${r}/additionalProperties`)}}visitPatterns(e,t,n,r,i){let a=!1;for(let[o,s]of Object.entries(e??{})){if(!new RegExp(o,`u`).test(t))continue;a=!0;let e=y(s);e&&this.visit(e,n,r,`${i}/patternProperties/${b(o)}`)}return a}};function xe(e,t,n){return new be(e,n.matchesSchema).extract(t)}function Se(e){let{dataSchema:t,hooks:n,...r}=e,i={$schema:`https://json-schema.org/draft/2020-12/schema`,...se(t)};oe(i);let a=p.parse({...r,dataSchema:i});if(a.kind!==e.kind)throw Error(`Artifact kind identifiers must not contain surrounding whitespace`);let o=_.fromJSONSchema(a.dataSchema),s=_.unknown().superRefine((e,t)=>{let n=o.safeParse(e);if(!n.success)for(let e of n.error.issues)t.addIssue({code:`custom`,path:e.path,message:e.message})}).pipe(t).superRefine((e,t)=>{try{ae(e,a.titlePath)}catch(e){t.addIssue({code:`custom`,path:a.titlePath.split(`.`),message:e instanceof Error?e.message:`Artifact title must be a nonblank string`})}});return{...structuredClone(a),kind:e.kind,schemaVersion:e.schemaVersion,dataSchema:s,...n?{hooks:n}:{},toRegistration:()=>structuredClone(a)}}var Ce=e(ce(),1),we=e(le(),1),Te=e(ue(),1);function Ee(e){let t={allErrors:!0,strict:!1,strictSchema:!0},n=e.dataSchema.$schema===`https://json-schema.org/draft/2020-12/schema`?new we.default(t):new Ce.default(t);return(0,Te.default)(n),n.addKeyword({keyword:ie,schemaType:`string`,valid:!0}),n.compile(e.dataSchema)}function De(e){return e.replace(/~1/gu,`/`).replace(/~0/gu,`~`)}function Oe(e){let t=e.instancePath.split(`/`).slice(1).map(De),n=e.keyword===`required`?e.params.missingProperty:e.params.additionalProperty;return typeof n==`string`&&(e.keyword===`required`||e.keyword===`additionalProperties`)&&t.push(n),t.join(`.`)}function ke(e){if(e.keyword!==`type`)return;let t=e.params.type;if(typeof t==`string`)return t;if(Array.isArray(t)&&t.every(e=>typeof e==`string`))return t.join(` | `)}const Ae=t.array();function je(e){if(e.keyword!==`enum`)return;let t=Ae.safeParse(e.params.allowedValues);return t.success?t.data:void 0}function Me(e){return(e??[]).map(e=>{let t=ke(e),n=je(e);return{path:Oe(e),reason:e.message??`violates ${e.keyword}`,...t===void 0?{}:{expectedType:t},...n===void 0?{}:{allowedValues:n}}})}function Ne(e){return Ee(e)}function Pe(e){let t=Ee(e);return e=>t(e)?{valid:!0}:{valid:!1,issues:Me(t.errors)}}function Fe(e){return{hooks:[...e.hooks]}}const Ie=[`inline`,`summary`,`link`,`omit`],C=_.string().min(1),w=_.object({kinds:_.array(_.string().min(1)).optional(),hint:C.optional(),depth:_.number().int().min(1).max(20).optional(),nested:_.lazy(()=>T).optional()}),T=_.record(_.string().min(1),w);function E(e){return JSON.stringify([e.kind,e.id,e.revision])}const D=_.enum([`not-selected`,`not-found`,`depth-exceeded`,`unsupported-ref-class`,`cycle-detected`]),O=_.object({target:ee,sourceRef:f,relationType:_.string().min(1),hint:C,status:_.enum([`resolved`,`unresolved`]),reason:D.optional()}).superRefine((e,t)=>{e.status===`unresolved`&&e.reason===void 0&&t.addIssue({code:_.ZodIssueCode.custom,path:[`reason`],message:`reason is required for unresolved artifact context refs`}),e.status===`resolved`&&e.reason!==void 0&&t.addIssue({code:_.ZodIssueCode.custom,path:[`reason`],message:`reason must be omitted for resolved artifact context refs`}),e.status===`resolved`&&e.target.refClass!==`artifact`&&t.addIssue({code:_.ZodIssueCode.custom,path:[`target`],message:`resolved artifact context refs must target an artifact revision`})}),k=_.object({rootRef:f,refs:_.array(O),resolved:_.array(c)}).superRefine((e,t)=>{let n=new Set(e.resolved.map(E));n.has(E(e.rootRef))||t.addIssue({code:_.ZodIssueCode.custom,path:[`resolved`],message:`resolved artifact context wire payloads must include the root artifact revision`}),e.refs.forEach((e,r)=>{n.has(E(e.sourceRef))||t.addIssue({code:_.ZodIssueCode.custom,path:[`refs`,r,`sourceRef`],message:`artifact context ref sources must have a matching revision in resolved`}),!(e.status!==`resolved`||e.target.refClass!==`artifact`)&&(n.has(E(e.target))||t.addIssue({code:_.ZodIssueCode.custom,path:[`refs`,r,`target`],message:`resolved artifact context refs must have a matching revision in resolved`}))})});function Le(e){let t=k.parse(e),n=new Map(t.resolved.map(e=>[A(e),e])),r=new Map;for(let e of t.refs){let t=A(e.sourceRef),n=r.get(t);n||(n=[],r.set(t,n)),n.push(e)}let i=n.get(A(t.rootRef));if(!i)throw Error(`Resolved artifact context is missing root artifact '${A(t.rootRef)}'`);let a=Re(t.rootRef,i,`inline`,r,n);return{root:a,flatten(){let e=[];return Ve(a,e),e}}}function Re(e,t,n,r,i){return{status:`resolved`,ref:e,artifact:t,hint:n,children:Be(e,r,i,new Set([A(e)]))}}function ze(e,t,n,r,i,a,o){let s=A(e),c=new Set(o);return c.add(s),{status:`resolved`,ref:e,artifact:t,relation:n,hint:r,children:Be(e,i,a,c)}}function Be(e,t,n,r){return(t.get(A(e))??[]).map(e=>{if(e.status===`unresolved`)return{status:`unresolved`,target:e.target,relation:e.relationType,hint:e.hint,reason:e.reason};if(e.target.refClass!==`artifact`)throw Error(`Resolved artifact context refs must target an artifact revision`);let i=A(e.target),a=n.get(i);if(!a)throw Error(`Resolved artifact context is missing target artifact '${i}'`);return r.has(i)?{status:`unresolved`,target:e.target,relation:e.relationType,hint:e.hint,reason:`cycle-detected`}:ze(e.target,a,e.relationType,e.hint,t,n,r)})}function Ve(e,t){if(e.status!==`unresolved`){t.push(e.artifact);for(let n of e.children)Ve(n,t)}}function A(e){return JSON.stringify([e.kind,e.id,e.revision])}const j=[`$set`,`$unset`,`$push`,`$pull`],M=`[A-Za-z_$][A-Za-z0-9_$]*`,N=`[A-Za-z_$][A-Za-z0-9_$-]*`,He=`(?:0|[1-9][0-9]*)`,Ue=`(?:${`\\$\\[${M}\\]`}|${He}|${N})`,We=RegExp(`^${N}(?:\\.${Ue})*$`),Ge=RegExp(`^${M}(?:\\.${N})*$`),Ke=RegExp(`^${He}$`),qe=RegExp(`^\\$\\[(${M})\\]$`),P=_.string().regex(We,`Expected a data-relative path of object properties, array positions, or $[filter] placeholders`);function Je(e){let t=qe.exec(e);return t?.[1]===void 0?Ke.test(e)?{kind:`index`,index:Number(e)}:{kind:`property`,name:e}:{kind:`filter`,placeholder:t[1]}}function Ye(e){return e.split(`.`).map(Je)}function Xe(e){return Ye(e).flatMap(e=>e.kind===`filter`?[e.placeholder]:[])}const Ze=n(_.record(_.string().regex(Ge,`Expected a filter key of the form name or name.field.path`),t),{prototypeKey:`an array filter cannot compare a __proto__ key, which JSON transport drops`,nonPlainObject:`an array filter must be a plain object of comparison keys`,symbolKey:`an array filter cannot carry symbol-keyed comparisons`,nonEnumerableKey:`an array filter cannot carry non-enumerable comparison keys`,extraArrayKey:`an array filter must be a plain object, not an array`});function Qe(e){let t=new Set(Object.keys(e).map(e=>e.split(`.`)[0]));if(t.size!==1)return;let[n]=t;return n!==void 0&&n.length>0?n:void 0}function F(e,t){return n(_.record(P,t),{prototypeKey:`${e} cannot address __proto__, which JSON transport drops`,nonPlainObject:`${e} must be a plain object of path instructions`,symbolKey:`${e} cannot carry symbol-keyed instructions`,nonEnumerableKey:`${e} cannot carry non-enumerable instructions`,extraArrayKey:`${e} must be a plain object, not an array`})}const $e=_.literal(!0),et=_.strictObject({$set:F(`$set`,t).optional(),$unset:F(`$unset`,$e).optional(),$push:F(`$push`,t).optional(),$pull:F(`$pull`,t).optional(),arrayFilters:_.array(Ze).optional()});function I(e){return j.flatMap(t=>Object.entries(e[t]??{}).map(([e,n])=>({operator:t,path:e,value:n})))}function tt(e,t){let n=I(e),r=new Map;(e.arrayFilters??[]).forEach((e,n)=>{let i=Qe(e);if(i===void 0){t.addIssue({code:`custom`,path:[`arrayFilters`,n],message:`An array filter must bind exactly one placeholder name across all of its keys`});return}if(r.has(i)){t.addIssue({code:`custom`,path:[`arrayFilters`,n],message:`Array filter placeholder ${i} is already bound by another filter`});return}r.set(i,n)});let i=new Set;for(let{operator:e,path:a}of n)for(let n of Xe(a))i.add(n),r.has(n)||t.addIssue({code:`custom`,path:[e,a],message:`Path uses placeholder $[${n}] without a matching entry in arrayFilters`});for(let[e,n]of r)i.has(e)||t.addIssue({code:`custom`,path:[`arrayFilters`,n],message:`Array filter binds placeholder ${e}, which no path uses`})}const nt=et.superRefine(tt).superRefine((e,t)=>{I(e).length===0&&t.addIssue({code:`custom`,message:`Declare at least one of ${j.join(`, `)}`})}),rt=et.superRefine(tt),it=_.strictObject({kind:f.shape.kind,id:f.shape.id}),at=_.strictObject({ref:it,baseRevision:f.shape.revision,patch:rt,dryRun:_.boolean().optional(),schemaVersion:m.optional().describe(`Target schema version for the patched revision; defaults to the base revision's. Use it to migrate an artifact left at an older version by a kind bump.`),statusPath:te.optional(),representations:re.strict().nullable().optional().describe(`Rendering hints (markdown, summary, plaintext) for the new revision. Omit to keep the previous revision's hints. An object replaces all of them, it does not merge: send every hint you want to keep. null clears them.`)}).superRefine((e,t)=>{e.schemaVersion===void 0&&I(e.patch).length===0&&t.addIssue({code:`custom`,path:[`patch`],message:`Declare at least one of ${j.join(`, `)}, or name a schemaVersion to migrate a payload that already fits`})}),ot=[`ARTIFACT_NOT_FOUND`,`BASE_REVISION_CONFLICT`,`KIND_NOT_REGISTERED`,`SCHEMA_VERSION_MISMATCH`,`PATH_NOT_DECLARED`,`PATH_NOT_RESOLVABLE`,`TARGET_NOT_A_COLLECTION`,`UNSUPPORTED_TARGET`,`NO_MATCH`,`SCHEMA_VALIDATION_FAILED`,`NO_CHANGE`,`STORE_REJECTED`,`HOST_FAILED`],st=_.strictObject({path:_.string(),reason:_.string().min(1),expectedType:_.string().min(1).optional(),allowedValues:_.array(t).optional()}),ct=_.strictObject({code:_.enum(ot),message:_.string().min(1),operator:_.enum(j).optional(),path:P.optional(),currentRevision:f.shape.revision.optional(),issues:_.array(st).optional(),repair:_.string().min(1)}).superRefine((e,t)=>{e.code===`BASE_REVISION_CONFLICT`&&e.currentRevision===void 0&&t.addIssue({code:_.ZodIssueCode.custom,message:`A BASE_REVISION_CONFLICT must name the revision the artifact carries.`,path:[`currentRevision`]})}),lt=_.strictObject({operator:_.enum(j),path:P,matched:_.number().int().positive()}),ut=_.strictObject({from:m,to:m}).refine(e=>e.to>e.from,{path:[`to`],message:`A migration moves the artifact forward to a newer schema version`}),dt=_.strictObject({ok:_.literal(!0),base:f,operations:_.array(lt),migration:ut.optional()});function ft(e,t){e.operations.length===0&&e.migration===void 0&&t.addIssue({code:`custom`,path:[`operations`],message:`A success without a migration must report at least one applied instruction`})}const pt=dt.extend({dryRun:_.literal(!0)}).superRefine(ft),mt=dt.extend({dryRun:_.literal(!1),artifact:f}).superRefine(ft),ht=_.discriminatedUnion(`dryRun`,[pt,mt]),gt=_.strictObject({ok:_.literal(!1),error:ct}),_t=_.union([ht,gt]),L=f.pick({kind:!0,id:!0}),R=_.number().int().positive(),z=R,B={knowledge:`valid`,commitment:`proposed`,interaction:`open`},V=_.discriminatedUnion(`category`,[_.strictObject({category:_.literal(`knowledge`),state:_.enum(g.knowledge),version:z}),_.strictObject({category:_.literal(`commitment`),state:_.enum(g.commitment),version:z}),_.strictObject({category:_.literal(`interaction`),state:_.enum(g.interaction),version:z})]).superRefine((e,t)=>{e.version===1&&e.state!==B[e.category]&&t.addIssue({code:`custom`,path:[`state`],message:`Lifecycle version 1 is reserved for the category initial state`})}),H=_.union([V,_.strictObject({category:_.literal(`record`)})]),U=_.string().trim().min(1),vt=_.strictObject({kind:U,ref:U}),W=_.discriminatedUnion(`kind`,[_.strictObject({kind:_.literal(`revision-assessment`),assessedRevision:f.shape.revision,source:vt.optional()}),_.strictObject({kind:_.literal(`handover`),source:vt})]),yt={artifact:L,expectedVersion:z,state:h,situation:W,reason:U.optional()},G=_.strictObject(yt),bt=_.strictObject({...yt,actor:d}),xt={valid:[`retired`],retired:[`valid`],proposed:[`decided`],decided:[`fulfilled`,`revoked`],fulfilled:[],revoked:[],open:[`resolved`,`closed-without-resolution`],resolved:[],"closed-without-resolution":[]};function K(e,t){return xt[e].includes(t)}const St={artifact:L,lifecycle:V,actor:d,timestamp:_.number().int().nonnegative(),observedRevision:f.shape.revision},Ct=_.strictObject({...St,operation:_.literal(`initialized`)}).superRefine((e,t)=>{(e.lifecycle.version!==1||e.lifecycle.state!==B[e.lifecycle.category])&&t.addIssue({code:`custom`,path:[`lifecycle`],message:`Initialization requires the category initial state and version 1`})});function wt(e,t){return t===`retired`||e===`retired`&&t===`valid`}const Tt=`Retiring or reinstating knowledge requires a reason`,q=_.strictObject({...St,operation:_.literal(`transitioned`),previousState:h,situation:W,reason:G.shape.reason}).superRefine((e,t)=>{(!K(e.previousState,e.lifecycle.state)||e.lifecycle.version<=1)&&t.addIssue({code:`custom`,path:[`lifecycle`],message:`History requires a category-compatible transition after initialization`}),wt(e.previousState,e.lifecycle.state)&&!e.reason&&t.addIssue({code:`custom`,path:[`reason`],message:Tt}),e.situation.kind===`revision-assessment`&&e.situation.assessedRevision!==e.observedRevision&&t.addIssue({code:`custom`,path:[`situation`],message:`An assessment cannot authorize a different observed content revision`})}),Et=_.discriminatedUnion(`operation`,[Ct,q]),J=_.discriminatedUnion(`reason`,[_.strictObject({reason:_.literal(`lifecycle-version-conflict`),expectedVersion:z,current:V,requestedState:h}),_.strictObject({reason:_.literal(`content-basis-conflict`),assessedRevision:f.shape.revision,currentRevision:f.shape.revision}),_.strictObject({reason:_.literal(`invalid-transition`),current:H,requestedState:h}),_.strictObject({reason:_.literal(`precondition-failed`),current:V,requestedState:h})]),Y=`artifact-lifecycle-rejected`;var X=class extends Error{code=Y;data;constructor(e,t){super(e),this.name=`ArtifactLifecycleError`,this.data=J.parse(t)}};function Dt(e){return e===`record`?{category:`record`}:V.parse({category:e,state:B[e],version:1})}function Ot(e){let t=H.parse(e.current),n=f.shape.revision.parse(e.currentRevision),r=bt.parse(e.command);if(t.category===`record`)throw new X(`Record artifacts do not have a lifecycle`,{reason:`invalid-transition`,current:t,requestedState:r.state});if(r.expectedVersion!==t.version)throw new X(`Artifact lifecycle changed since the supplied baseline`,{reason:`lifecycle-version-conflict`,expectedVersion:r.expectedVersion,current:t,requestedState:r.state});if(r.situation.kind===`revision-assessment`&&r.situation.assessedRevision!==n)throw new X(`Assessed content revision is no longer current`,{reason:`content-basis-conflict`,assessedRevision:r.situation.assessedRevision,currentRevision:n});if(!K(t.state,r.state))throw new X(`Artifact lifecycle transition is not allowed`,{reason:`invalid-transition`,current:t,requestedState:r.state});if(wt(t.state,r.state)&&!r.reason)throw new X(Tt,{reason:`precondition-failed`,current:t,requestedState:r.state});return V.parse({...t,state:r.state,version:t.version+1})}const kt=_.strictObject({artifact:L}),At=_.strictObject({lifecycle:H}),jt=_.strictObject({artifact:L,afterVersion:R.optional(),limit:_.number().int().min(1).max(100).default(50)}),Mt=_.strictObject({entries:_.array(Et).max(100),nextCursor:R.optional()}).superRefine(({entries:e,nextCursor:t},n)=>{let r=e[0],i;for(let[t,a]of e.entries()){let e=a.artifact.kind===r?.artifact.kind&&a.artifact.id===r?.artifact.id,o=i===void 0||a.lifecycle.version===i.lifecycle.version+1,s=i===void 0||a.operation===`transitioned`&&a.lifecycle.category===i.lifecycle.category&&a.previousState===i.lifecycle.state;if(!e||!o||!s){n.addIssue({code:`custom`,path:[`entries`,t],message:`History pages contain one artifact in contiguous ascending, state-linked order`});break}i=a}t!==void 0&&t!==i?.lifecycle.version&&n.addIssue({code:`custom`,path:[`nextCursor`],message:`nextCursor must equal the last returned lifecycle version`})}),Z=_.strictObject({entry:q}),Nt=Z,Pt=_.strictObject({code:_.literal(Y),message:_.string().min(1),data:J});function Ft(e){return{code:e.code,message:e.message,data:e.data}}function It(e,t){switch(t.reason){case`content-basis-conflict`:return zt(e,t);case`lifecycle-version-conflict`:return[...Lt(e,t),...Rt(e,t)];case`invalid-transition`:case`precondition-failed`:return[...Lt(e,t),...Bt(e,t)]}}function Lt(e,t){return t.requestedState===e.state?[]:[{path:[`requestedState`],message:`Rejection requestedState must match the rejected transition`}]}function Rt(e,t){let n=[];return t.expectedVersion!==e.expectedVersion&&n.push({path:[`expectedVersion`],message:`Version conflict baseline must match the rejected transition`}),t.current.version===e.expectedVersion&&n.push({path:[`current`,`version`],message:`Version conflict requires a current version different from the supplied baseline`}),n}function zt(e,t){let n=[];return(e.situation.kind!==`revision-assessment`||t.assessedRevision!==e.situation.assessedRevision)&&n.push({path:[`assessedRevision`],message:`Content conflict must identify the rejected revision assessment`}),t.currentRevision===t.assessedRevision&&n.push({path:[`currentRevision`],message:`Content conflict requires a current revision different from the assessed revision`}),n}function Bt(e,t){if(t.current.category===`record`)return[];let n=[];t.current.version!==e.expectedVersion&&n.push({path:[`current`,`version`],message:`A rejection after the version check must report the supplied baseline version`});let r=K(t.current.state,t.requestedState);return t.reason===`invalid-transition`&&r&&n.push({path:[`reason`],message:`invalid-transition requires a transition the lifecycle matrix disallows`}),t.reason===`precondition-failed`&&!r&&n.push({path:[`reason`],message:`precondition-failed requires a transition the lifecycle matrix allows`}),n}const Vt=_.strictObject({transition:G,error:Pt}).superRefine(({transition:e,error:t},n)=>{for(let r of It(e,t.data))n.addIssue({code:`custom`,path:[`error`,`data`,...r.path],message:r.message})}),Q={"lifecycle.get":{request:kt,response:At},"lifecycle.history":{request:jt,response:Mt},"lifecycle.transition":{request:G,response:Z},"lifecycle.committed":Nt,"lifecycle.rejected":Vt},Ht={...Q,"kind.register":{request:p,response:_.object({registered:_.boolean()})},"kind.list":{request:_.object({kind:_.string().min(1).optional()}),response:_.object({kinds:_.array(p)})},"relation-type.register":{request:o,response:_.object({registered:_.boolean()})},"relation-type.list":{request:_.object({type:_.string().min(1).optional()}),response:_.object({relationTypes:_.array(o)})},create:{request:c.omit({id:!0,revision:!0,timestamp:!0}).extend({id:f.shape.id.optional()}),response:_.object({artifact:c})},revise:{request:_.object({previous:f,statusPath:te.optional(),revision:c.omit({id:!0,revision:!0,timestamp:!0})}),response:_.object({artifact:c})},patch:{request:at,response:_t},resolve:{request:_.object({ref:f}),response:_.object({artifact:c.nullable()})},query:{request:a,response:_.object({artifacts:_.array(c)})},compare:{request:u,response:ne},"evidence.resolve":{request:fe,response:ge},resolveContext:{request:_.object({ref:f,selectors:T.optional(),maxDepth:_.number().int().min(1).max(20).default(5)}),response:_.object({context:k})},created:_.object({artifact:c}),revised:_.object({previous:f,artifact:c}),"relation.added":_.object({artifact:f,relation:s}),"observation.added":_.object({artifact:f,observation:l}),"status.changed":_.object({artifact:f,path:_.string().min(1),previous:_.unknown().optional(),current:_.unknown().optional()}),"kind.changed":_.object({kind:_.string().min(1),schemaVersion:m})},Ut=de(`artifact`,Ht),Wt=Ut.subjects,Gt=_.discriminatedUnion(`refClass`,[f.omit({revision:!0}),i]);function Kt(e){if(e.refClass===`artifact`)return{refClass:`artifact`,kind:e.kind,id:e.id};if(e.refClass===`entity`)return{refClass:`entity`,entityType:e.entityType,id:e.id}}function $(e){return e.refClass===`artifact`?JSON.stringify([`artifact`,e.kind,e.id]):JSON.stringify([`entity`,e.entityType,e.id])}function qt(e){return e.refClass===`artifact`?`artifact:${e.kind}/${e.id}`:`entity:${e.entityType}/${e.id}`}const Jt=[`relation-target`];function Yt(e,t){if(!e||e.length===0)return{ok:!0,rules:[]};let n=[];for(let[r,i]of e.entries()){for(let[e,a]of i.by.entries())(!Jt.includes(a.kind)||!t.includes(a.kind))&&n.push({ruleIndex:r,selectorIndex:e,capability:a.kind,message:`rule #${r}, selector #${e}: '${a.kind}' selectors are not supported`});i.lifecycleStates!==void 0&&!t.includes(`lifecycle-states`)&&n.push({ruleIndex:r,capability:`lifecycle-states`,message:`rule #${r}: lifecycleStates is declared but 'lifecycle-states' is not a supported capability`})}return n.length>0?{ok:!1,issues:n}:{ok:!0,rules:e}}function Xt(e,t,n,r){if(e.kind===`data`)return{ruleIndex:n,selectorIndex:r,reason:`unsupported-selector`,message:`rule #${n}, selector #${r}: data-path selectors cannot be derived from relations`};let{relationType:i}=e,a=t.filter(e=>e.type===i),o=new Set,s,c;for(let e of a){let t=Kt(e.target);if(t===void 0){c=e.target.refClass;break}o.add($(t)),s=t}return c===void 0?s===void 0?{ruleIndex:n,selectorIndex:r,reason:`missing-target`,relationType:i,message:`rule #${n}, selector #${r}, relation '${i}': no relations of this type found`}:o.size>1?{ruleIndex:n,selectorIndex:r,reason:`ambiguous-target`,relationType:i,message:`rule #${n}, selector #${r}, relation '${i}': ${o.size} distinct targets; expected exactly one`}:{type:i,target:s}:{ruleIndex:n,selectorIndex:r,reason:`unsupported-target`,relationType:i,message:`rule #${n}, selector #${r}, relation '${i}': found a relation with refClass '${c}'; only artifact and entity targets are supported`}}function Zt(e,t){let n=[],r=[];for(let[i,a]of e.entries()){let e=a.by.map((e,n)=>Xt(e,t,i,n)),o=e.filter(e=>`reason`in e);if(o.length>0){r.push(...o);continue}let s=e.filter(e=>!(`reason`in e)),c=JSON.stringify(s.map(e=>[e.type,$(e.target)]));n.push({rule:a,ruleIndex:i,parts:s,serialized:c})}return{keys:n,issues:r}}function Qt(e){return e.parts.map(e=>`${e.type} → ${qt(e.target)}`).join(`; `)}export{Qe as $,bt as A,nt as B,X as C,J as D,Ct as E,Dt as F,ut as G,ct as H,K as I,mt as J,lt as K,ot as L,q as M,R as N,W as O,Ot as P,it as Q,j as R,H as S,L as T,gt as U,pt as V,st as W,_t as X,at as Y,ht as Z,Vt as _,fe as _t,Kt as a,O as at,Ft as b,Ut as c,Ie as ct,Nt as d,T as dt,I as et,Pt as f,Fe as ft,Mt as g,xe as gt,jt as h,Se as ht,Gt as i,Le as it,G as j,V as k,Ht as l,w as lt,At as m,Ne as mt,Zt as n,Je as nt,qt as o,D as ot,kt as p,Pe as pt,P as q,Qt as r,Ye as rt,$ as s,k as st,Yt as t,Xe as tt,Wt as u,C as ut,Q as v,ge as vt,Et as w,Y as x,Z as y,Ze as z};
@@ -2945,10 +2945,17 @@ declare function deserializeTransportError(transportError: BusTransportError): E
2945
2945
  * under its own `data` property.
2946
2946
  *
2947
2947
  * Merge rule: own enumerable props are collected (skipping codec fields), then,
2948
- * if the object has an own `data` that is a plain JSON object, the `data` key is
2949
- * removed from the flat set and the bag members are spread in bag members win
2950
- * on collision. A non-plain-object `data` (array, primitive) is kept as a
2951
- * verbatim member of the flat set.
2948
+ * if the object has an own `data` whose _value_ (read via descriptor, never via
2949
+ * a getter) is a plain JSON object, the `data` key is removed from the flat set
2950
+ * and the bag members are spread in after filtering codec field names — bag
2951
+ * members win on collision. A non-plain-object `data` value (array, primitive)
2952
+ * is kept as a verbatim member of the flat set. An accessor-backed `data`
2953
+ * property is omitted entirely: its descriptor has no `value`, so both
2954
+ * `collectStructuredProps` and the merge branch ignore it — getters never run.
2955
+ *
2956
+ * Codec field names (`message`, `name`, `stack`, `cause`, `subject`, `code`)
2957
+ * are reserved and never appear in the result, whether they originate from the
2958
+ * flat props or from inside a `data` bag.
2952
2959
  *
2953
2960
  * Standard Error fields and top-level codec fields (`message`, `name`, `stack`,
2954
2961
  * `cause`, `subject`, `code`) are never part of the result. Returns `undefined`
@@ -1 +1 @@
1
- import{$ as e,A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as ee,M as f,N as te,O as ne,P as re,Q as ie,R as p,S as m,T as ae,U as oe,V as h,W as g,X as se,Y as ce,Z as _,_ as le,a as ue,b as de,d as v,et as fe,f as pe,g as me,h as y,i as he,it as ge,j as b,k as x,l as S,m as C,nt as w,o as T,p as E,q as D,r as O,rt as k,s as A,t as j,tt as M,u as N,v as P,w as F,x as I,y as L,z as _e}from"../bus-DU_7GM0J.mjs";import{z as R}from"zod";const z={"channel.open":{request:R.object({endpoint:R.string(),token:R.string(),clientPubKey:R.string(),transports:R.array(R.string())}),response:R.object({channelId:R.string(),endpointPubKey:R.string()})}};function B(e){let t=e instanceof Uint8Array?e:new Uint8Array(e),n=Array(t.length);for(let e=0;e<t.length;e++)n[e]=String.fromCharCode(t[e]);return btoa(n.join(``))}function V(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}async function H(){return globalThis.crypto.subtle.generateKey({name:`ECDH`,namedCurve:`P-256`},!1,[`deriveKey`])}async function U(e){return B(await globalThis.crypto.subtle.exportKey(`raw`,e))}async function W(e){let t=V(e);return globalThis.crypto.subtle.importKey(`raw`,t,{name:`ECDH`,namedCurve:`P-256`},!1,[])}async function G(e,t){return globalThis.crypto.subtle.deriveKey({name:`ECDH`,public:t},e,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`])}async function K(e,t,n){let r=globalThis.crypto.getRandomValues(new Uint8Array(12)),i=new TextEncoder().encode(t),a={name:`AES-GCM`,iv:r};n!==void 0&&(a.additionalData=new TextEncoder().encode(n));let o=await globalThis.crypto.subtle.encrypt(a,e,i);return{iv:B(r),data:B(o)}}async function q(e,t,n){let r=V(t.iv),i=V(t.data),a={name:`AES-GCM`,iv:r};n!==void 0&&(a.additionalData=new TextEncoder().encode(n));let o=await globalThis.crypto.subtle.decrypt(a,e,i);return new TextDecoder().decode(o)}function J(e,t){return{subject:t,$meta:{namespace:`channel:${e}`,isRequest:!1,payload:{},local:!1,channel:!1}}}function Y(e,t){return{subject:t,$meta:{namespace:`channel:${e}`,isRequest:!0,payload:{},local:!1,channel:!1}}}var X=class{channelId;sharedKey;context;transportNames;cleanups=[];pendingRequests=new Set;closed=!1;constructor(e,t,n,r){this.channelId=e,this.sharedKey=t,this.context=n,this.transportNames=r;let i=J(e,`$close`);this.cleanups.push(this.registerEventHandler(i,t,e=>{this.handlePeerClose()}))}on(e,t,n){this.assertOpen();let r=this.requireKey(),i=e.$meta.isRequest?this.registerRequestHandler(e,r,t,n):this.registerEventHandler(e,r,t,n);return this.cleanups.push(i),()=>{i();let e=this.cleanups.indexOf(i);e!==-1&&this.cleanups.splice(e,1)}}once(e,t){this.assertOpen();let n=this.requireKey(),r=null,i=(e=>{let n=r;if(r=null,n){let e=this.cleanups.indexOf(n);e!==-1&&this.cleanups.splice(e,1)}return n?.(),t(e)});return r=e.$meta.isRequest?this.registerRequestHandler(e,n,i):this.registerEventHandler(e,n,i),this.cleanups.push(r),()=>{if(r){let e=r;r=null;let t=this.cleanups.indexOf(e);t!==-1&&this.cleanups.splice(t,1),e()}}}async emit(e,t){this.assertOpen();let n=this.requireKey(),r=J(this.channelId,e.subject),i=await K(n,JSON.stringify(t),`${this.channelId}:${e.subject}:evt`);await E(this.context,r,i,{...this.transportNames?{transports:[...this.transportNames]}:{}})}async request(e,t,n){this.assertOpen();let r=this.requireKey(),i=new AbortController;this.pendingRequests.add(i);try{let a=Y(this.channelId,e.subject),o=await K(r,JSON.stringify(t),`${this.channelId}:${e.subject}:req`),s=await q(r,await v(this.context,a,o,{signal:i.signal,...n?.timeout===void 0?{}:{timeout:n.timeout},...this.transportNames?{transports:[...this.transportNames]}:{}}),`${this.channelId}:${e.subject}:res`);return JSON.parse(s)}finally{this.pendingRequests.delete(i)}}async requestOptional(e,t,n){try{return{handled:!0,data:await this.request(e,t,n)}}catch(e){if(e instanceof o)return{handled:!1};throw e}}close(){if(this.closed)return;this.closed=!0;let e=this.sharedKey;if(e){let t=J(this.channelId,`$close`);K(e,JSON.stringify({}),`${this.channelId}:$close:evt`).then(e=>E(this.context,t,e,{...this.transportNames?{transports:[...this.transportNames]}:{}})).catch(()=>{})}this.abortPendingRequests(),this.runCleanups(),this.sharedKey=null}assertOpen(){if(this.closed)throw new n(this.channelId)}requireKey(){return this.sharedKey}registerEventHandler(e,t,n,r){let i=J(this.channelId,e.subject),a=`${this.channelId}:${e.subject}:evt`;return y(this.context,i,async e=>{let r=await q(t,e.payload,a),i=JSON.parse(r);return n({...e,payload:i})},r)}registerRequestHandler(e,t,n,r){let i=Y(this.channelId,e.subject),a=`${this.channelId}:${e.subject}:req`,o=`${this.channelId}:${e.subject}:res`;return y(this.context,i,async e=>{let r=await q(t,e.payload,a),i=JSON.parse(r),s,c=e=>{s={value:e}},l=e=>{s={value:{...s?.value??{},...e}}},u=async()=>{let n=s;if(await e.next(),n!==void 0){s=n;return}let r=e.result;if(r!==void 0){let e=await q(t,r,o);s={value:JSON.parse(e)}}};if(await n({...e,payload:i,get result(){return s?.value},setResult:c,extendResult:l,next:u}),s!==void 0){let n=await K(t,JSON.stringify(s.value),o);e.setResult(n)}},r)}handlePeerClose(){this.closed||(this.closed=!0,this.abortPendingRequests(),this.runCleanups(),this.sharedKey=null)}abortPendingRequests(){let e=new n(this.channelId);for(let t of this.pendingRequests)t.abort(e);this.pendingRequests.clear()}runCleanups(){for(let e of this.cleanups)try{e()}catch{}this.cleanups.length=0}};function Z(e){return e.namespaceRegistry.registerNamespace(_(`system`,z)).subjects.channel.open}function ve(e,t,n,r){let i=y(e,Z(e),async i=>{if(i.payload.endpoint!==t){await i.next();return}if(i.payload.token!==r.token)throw new h(t);let{publicKey:a,privateKey:o}=await H(),s=await G(o,await W(i.payload.clientPubKey)),c=globalThis.crypto.randomUUID(),l=new Set(e.transportRegistry.names()),u=new X(c,s,e,(i.payload.transports??[]).filter(e=>l.has(e)));try{n(u),i.setResult({channelId:c,endpointPubKey:await U(a)})}catch(e){throw u.close(),e}});return{name:t,token:r.token,close:i}}async function ye(e,t,n){let r=Z(e),{publicKey:i,privateKey:a}=await H(),o=await U(i),s=n.transports!==void 0,c=s?[...n.transports]:[...e.transportRegistry.names()],l=s?{transports:c}:void 0,u=await v(e,r,{endpoint:t,token:n.token,clientPubKey:o,transports:c},l),d=await G(a,await W(u.endpointPubKey));return new X(u.channelId,d,e,c)}var be=class{pending;constructor(){this.pending=new Map}track(e,t,n){return new Promise((r,i)=>{if(n?.aborted){i(g(n.reason));return}let a=t===0?void 0:setTimeout(()=>{let n=this.pending.get(e);n!==void 0&&(clearTimeout(n.timeoutId),n.removeAbortListener?.(),this.pending.delete(e),n.reject(new f(e,t)))},t);if(this.pending.set(e,{resolve:r,reject:i,timeoutId:a,removeAbortListener:void 0}),n){let t=()=>{this.reject(e,g(n.reason))};n.addEventListener(`abort`,t,{once:!0});let r=()=>{n.removeEventListener(`abort`,t)},i=this.pending.get(e);i&&(i.removeAbortListener=r)}n?.aborted&&this.reject(e,g(n.reason))})}resolve(e,t){let n=this.pending.get(e);n&&(clearTimeout(n.timeoutId),n.removeAbortListener?.(),this.pending.delete(e),n.resolve(t))}reject(e,t){let n=this.pending.get(e);n&&(clearTimeout(n.timeoutId),n.removeAbortListener?.(),this.pending.delete(e),n.reject(t))}cancel(e,t){this.reject(e,t??g(void 0))}rejectAll(e){for(let[t,n]of this.pending.entries())clearTimeout(n.timeoutId),n.removeAbortListener?.(),n.reject(e);this.pending.clear()}cleanup(){this.rejectAll(Error(`Transport disconnected`))}};const xe=_(`bus:lifecycle`,ue).subjects;function Q(e,t){let n={},r={},i={};for(let[t,a]of e)n[t]=a.priorities,r[t]=a.deliveryClass??`relayable`,a.filter!==void 0&&(i[t]=a.filter);return{type:`subscribe`,...t===void 0?{}:{ackId:t},subjects:n,deliveryClasses:r,...Object.keys(i).length>0&&{filters:i}}}function Se(e,t){return{type:`unsubscribe`,...t===void 0?{}:{ackId:t},subjects:e}}function Ce(e,t){let n=e.trim();if(n.length===0||n.startsWith(`extension:`))throw Error(`Invalid extensionName: expected a non-empty extension name without the "extension:" prefix.`);let r=n;return{..._(`extension:${r}`,t.schemas),domain:r,extensions:t.extensions??{}}}function $(e,t){return`${e}.${t}`}function we(){let e=new Map;return{register(t){let n=$(t.namespace,t.subject);return e.set(n,t),()=>{e.get(n)===t&&e.delete(n)}},get(t,n){return e.get($(t,n))}}}const Te=t.fact.$meta.namespace,Ee=t.fact.subject;function De(e){return e.type===`event`||e.type===`request`||e.type===`broadcast`}async function Oe(e,t,n,r,i,a){let o=C({message:t,direction:`outbound`,observedAt:a(),machineId:i,namespaceRegistry:n,projectorRegistry:r});for(let n of o)await e.send({type:`event`,namespace:Te,subject:Ee,payload:n,messageId:`${t.messageId}:telemetry:${n.factId}`,correlationId:t.correlationId})}function ke(e,t,n,r,i){return async function(a,o){if(!De(a))return!0;if(await Oe(e,a,t,n,r,i),a.type===`request`)throw Error(`Projected telemetry transport cannot satisfy request responses; exclude it from request routing.`);return a.type===`broadcast`?[]:!0}}function Ae(e){let{inner:t,namespaceRegistry:n,projectorRegistry:r,machineId:i,now:a=Date.now}=e,o={name:e.name,send:ke(t,n,r,i,a),onReceive(e){return t.onReceive(async()=>{})},connect(){return t.connect()},disconnect(){return t.disconnect()},subscribe(){return Promise.resolve()},unsubscribe(){return Promise.resolve()},get ready(){return t.ready},get onNewReadySession(){return t.onNewReadySession},set onNewReadySession(e){t.onNewReadySession=e},get onConnected(){return t.onConnected},set onConnected(e){t.onConnected=e},get onDisconnected(){return t.onDisconnected},set onDisconnected(e){t.onDisconnected=e},isReady(){return t.isReady?.()??!0},cancelRequest(e,n){t.cancelRequest?.(e,n)},onBroadcastResults(e,n,r){t.onBroadcastResults?.(e,n,r)}};return t.reconnect&&(o.reconnect=()=>t.reconnect()),o}export{c as BusAbortError,s as BusError,xe as BusLifecycle,ee as CONNECTION_LOST_ERROR_CODE,h as ChannelAuthError,n as ChannelClosedError,_e as ChannelOnlyError,p as ConnectionLostError,be as CorrelationTracker,pe as DEFAULT_REQUEST_TIMEOUT_MS,L as LOCAL_ORIGIN,l as LocalSubjectError,j as MakaioBus,re as NO_HANDLER_ERROR_CODE,o as NoHandlerError,N as OnceAbortError,de as REMOTE_ORIGIN,te as RequestError,z as SystemChannelSchemas,f as TimeoutError,b as ValidationError,le as __resetWarnedSubjects,Q as buildSubscribeMessage,Se as buildUnsubscribeMessage,k as channelSubject,e as collectorOnlySubject,O as createBusContext,he as createBusInstance,ve as createChannelEndpoint,Ce as createExtensionNamespace,S as createFilteredBus,Ae as createProjectedTelemetryTransport,we as createSubjectTelemetryProjectorRegistry,fe as defaultTransports,T as defineSubjectExtension,ae as deserializeTransportError,A as extendSubject,a as findInErrorChain,ie as getFullSubjectForSubjectDefinition,d as getPath,i as getSubjectFromBusMessage,I as handleCorrelationResponse,M as hostLocalRequest,ne as isNoHandlerErrorForSubject,oe as isRequestCancellation,ge as isRequestSchema,w as localSubject,ce as matchesAnySubscription,D as matchesFilter,se as matchesSubscription,u as mergeFilters,ye as openChannel,P as parseBusUrl,C as projectSubjectTelemetryFacts,m as serializeTransportError,r as shouldReceiveMessage,F as trackMessageCorrelation,x as transportErrorData,me as waitForSubscriptionPropagation};
1
+ import{$ as e,A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as ee,M as f,N as te,O as ne,P as re,Q as ie,R as p,S as m,T as ae,U as oe,V as h,W as g,X as se,Y as ce,Z as _,_ as le,a as ue,b as de,d as v,et as fe,f as pe,g as me,h as y,i as he,it as ge,j as b,k as x,l as S,m as C,nt as w,o as T,p as E,q as D,r as O,rt as k,s as A,t as j,tt as M,u as N,v as P,w as F,x as I,y as L,z as _e}from"../bus-KqRHrusX.mjs";import{z as R}from"zod";const z={"channel.open":{request:R.object({endpoint:R.string(),token:R.string(),clientPubKey:R.string(),transports:R.array(R.string())}),response:R.object({channelId:R.string(),endpointPubKey:R.string()})}};function B(e){let t=e instanceof Uint8Array?e:new Uint8Array(e),n=Array(t.length);for(let e=0;e<t.length;e++)n[e]=String.fromCharCode(t[e]);return btoa(n.join(``))}function V(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}async function H(){return globalThis.crypto.subtle.generateKey({name:`ECDH`,namedCurve:`P-256`},!1,[`deriveKey`])}async function U(e){return B(await globalThis.crypto.subtle.exportKey(`raw`,e))}async function W(e){let t=V(e);return globalThis.crypto.subtle.importKey(`raw`,t,{name:`ECDH`,namedCurve:`P-256`},!1,[])}async function G(e,t){return globalThis.crypto.subtle.deriveKey({name:`ECDH`,public:t},e,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`])}async function K(e,t,n){let r=globalThis.crypto.getRandomValues(new Uint8Array(12)),i=new TextEncoder().encode(t),a={name:`AES-GCM`,iv:r};n!==void 0&&(a.additionalData=new TextEncoder().encode(n));let o=await globalThis.crypto.subtle.encrypt(a,e,i);return{iv:B(r),data:B(o)}}async function q(e,t,n){let r=V(t.iv),i=V(t.data),a={name:`AES-GCM`,iv:r};n!==void 0&&(a.additionalData=new TextEncoder().encode(n));let o=await globalThis.crypto.subtle.decrypt(a,e,i);return new TextDecoder().decode(o)}function J(e,t){return{subject:t,$meta:{namespace:`channel:${e}`,isRequest:!1,payload:{},local:!1,channel:!1}}}function Y(e,t){return{subject:t,$meta:{namespace:`channel:${e}`,isRequest:!0,payload:{},local:!1,channel:!1}}}var X=class{channelId;sharedKey;context;transportNames;cleanups=[];pendingRequests=new Set;closed=!1;constructor(e,t,n,r){this.channelId=e,this.sharedKey=t,this.context=n,this.transportNames=r;let i=J(e,`$close`);this.cleanups.push(this.registerEventHandler(i,t,e=>{this.handlePeerClose()}))}on(e,t,n){this.assertOpen();let r=this.requireKey(),i=e.$meta.isRequest?this.registerRequestHandler(e,r,t,n):this.registerEventHandler(e,r,t,n);return this.cleanups.push(i),()=>{i();let e=this.cleanups.indexOf(i);e!==-1&&this.cleanups.splice(e,1)}}once(e,t){this.assertOpen();let n=this.requireKey(),r=null,i=(e=>{let n=r;if(r=null,n){let e=this.cleanups.indexOf(n);e!==-1&&this.cleanups.splice(e,1)}return n?.(),t(e)});return r=e.$meta.isRequest?this.registerRequestHandler(e,n,i):this.registerEventHandler(e,n,i),this.cleanups.push(r),()=>{if(r){let e=r;r=null;let t=this.cleanups.indexOf(e);t!==-1&&this.cleanups.splice(t,1),e()}}}async emit(e,t){this.assertOpen();let n=this.requireKey(),r=J(this.channelId,e.subject),i=await K(n,JSON.stringify(t),`${this.channelId}:${e.subject}:evt`);await E(this.context,r,i,{...this.transportNames?{transports:[...this.transportNames]}:{}})}async request(e,t,n){this.assertOpen();let r=this.requireKey(),i=new AbortController;this.pendingRequests.add(i);try{let a=Y(this.channelId,e.subject),o=await K(r,JSON.stringify(t),`${this.channelId}:${e.subject}:req`),s=await q(r,await v(this.context,a,o,{signal:i.signal,...n?.timeout===void 0?{}:{timeout:n.timeout},...this.transportNames?{transports:[...this.transportNames]}:{}}),`${this.channelId}:${e.subject}:res`);return JSON.parse(s)}finally{this.pendingRequests.delete(i)}}async requestOptional(e,t,n){try{return{handled:!0,data:await this.request(e,t,n)}}catch(e){if(e instanceof o)return{handled:!1};throw e}}close(){if(this.closed)return;this.closed=!0;let e=this.sharedKey;if(e){let t=J(this.channelId,`$close`);K(e,JSON.stringify({}),`${this.channelId}:$close:evt`).then(e=>E(this.context,t,e,{...this.transportNames?{transports:[...this.transportNames]}:{}})).catch(()=>{})}this.abortPendingRequests(),this.runCleanups(),this.sharedKey=null}assertOpen(){if(this.closed)throw new n(this.channelId)}requireKey(){return this.sharedKey}registerEventHandler(e,t,n,r){let i=J(this.channelId,e.subject),a=`${this.channelId}:${e.subject}:evt`;return y(this.context,i,async e=>{let r=await q(t,e.payload,a),i=JSON.parse(r);return n({...e,payload:i})},r)}registerRequestHandler(e,t,n,r){let i=Y(this.channelId,e.subject),a=`${this.channelId}:${e.subject}:req`,o=`${this.channelId}:${e.subject}:res`;return y(this.context,i,async e=>{let r=await q(t,e.payload,a),i=JSON.parse(r),s,c=e=>{s={value:e}},l=e=>{s={value:{...s?.value??{},...e}}},u=async()=>{let n=s;if(await e.next(),n!==void 0){s=n;return}let r=e.result;if(r!==void 0){let e=await q(t,r,o);s={value:JSON.parse(e)}}};if(await n({...e,payload:i,get result(){return s?.value},setResult:c,extendResult:l,next:u}),s!==void 0){let n=await K(t,JSON.stringify(s.value),o);e.setResult(n)}},r)}handlePeerClose(){this.closed||(this.closed=!0,this.abortPendingRequests(),this.runCleanups(),this.sharedKey=null)}abortPendingRequests(){let e=new n(this.channelId);for(let t of this.pendingRequests)t.abort(e);this.pendingRequests.clear()}runCleanups(){for(let e of this.cleanups)try{e()}catch{}this.cleanups.length=0}};function Z(e){return e.namespaceRegistry.registerNamespace(_(`system`,z)).subjects.channel.open}function ve(e,t,n,r){let i=y(e,Z(e),async i=>{if(i.payload.endpoint!==t){await i.next();return}if(i.payload.token!==r.token)throw new h(t);let{publicKey:a,privateKey:o}=await H(),s=await G(o,await W(i.payload.clientPubKey)),c=globalThis.crypto.randomUUID(),l=new Set(e.transportRegistry.names()),u=new X(c,s,e,(i.payload.transports??[]).filter(e=>l.has(e)));try{n(u),i.setResult({channelId:c,endpointPubKey:await U(a)})}catch(e){throw u.close(),e}});return{name:t,token:r.token,close:i}}async function ye(e,t,n){let r=Z(e),{publicKey:i,privateKey:a}=await H(),o=await U(i),s=n.transports!==void 0,c=s?[...n.transports]:[...e.transportRegistry.names()],l=s?{transports:c}:void 0,u=await v(e,r,{endpoint:t,token:n.token,clientPubKey:o,transports:c},l),d=await G(a,await W(u.endpointPubKey));return new X(u.channelId,d,e,c)}var be=class{pending;constructor(){this.pending=new Map}track(e,t,n){return new Promise((r,i)=>{if(n?.aborted){i(g(n.reason));return}let a=t===0?void 0:setTimeout(()=>{let n=this.pending.get(e);n!==void 0&&(clearTimeout(n.timeoutId),n.removeAbortListener?.(),this.pending.delete(e),n.reject(new f(e,t)))},t);if(this.pending.set(e,{resolve:r,reject:i,timeoutId:a,removeAbortListener:void 0}),n){let t=()=>{this.reject(e,g(n.reason))};n.addEventListener(`abort`,t,{once:!0});let r=()=>{n.removeEventListener(`abort`,t)},i=this.pending.get(e);i&&(i.removeAbortListener=r)}n?.aborted&&this.reject(e,g(n.reason))})}resolve(e,t){let n=this.pending.get(e);n&&(clearTimeout(n.timeoutId),n.removeAbortListener?.(),this.pending.delete(e),n.resolve(t))}reject(e,t){let n=this.pending.get(e);n&&(clearTimeout(n.timeoutId),n.removeAbortListener?.(),this.pending.delete(e),n.reject(t))}cancel(e,t){this.reject(e,t??g(void 0))}rejectAll(e){for(let[t,n]of this.pending.entries())clearTimeout(n.timeoutId),n.removeAbortListener?.(),n.reject(e);this.pending.clear()}cleanup(){this.rejectAll(Error(`Transport disconnected`))}};const xe=_(`bus:lifecycle`,ue).subjects;function Q(e,t){let n={},r={},i={};for(let[t,a]of e)n[t]=a.priorities,r[t]=a.deliveryClass??`relayable`,a.filter!==void 0&&(i[t]=a.filter);return{type:`subscribe`,...t===void 0?{}:{ackId:t},subjects:n,deliveryClasses:r,...Object.keys(i).length>0&&{filters:i}}}function Se(e,t){return{type:`unsubscribe`,...t===void 0?{}:{ackId:t},subjects:e}}function Ce(e,t){let n=e.trim();if(n.length===0||n.startsWith(`extension:`))throw Error(`Invalid extensionName: expected a non-empty extension name without the "extension:" prefix.`);let r=n;return{..._(`extension:${r}`,t.schemas),domain:r,extensions:t.extensions??{}}}function $(e,t){return`${e}.${t}`}function we(){let e=new Map;return{register(t){let n=$(t.namespace,t.subject);return e.set(n,t),()=>{e.get(n)===t&&e.delete(n)}},get(t,n){return e.get($(t,n))}}}const Te=t.fact.$meta.namespace,Ee=t.fact.subject;function De(e){return e.type===`event`||e.type===`request`||e.type===`broadcast`}async function Oe(e,t,n,r,i,a){let o=C({message:t,direction:`outbound`,observedAt:a(),machineId:i,namespaceRegistry:n,projectorRegistry:r});for(let n of o)await e.send({type:`event`,namespace:Te,subject:Ee,payload:n,messageId:`${t.messageId}:telemetry:${n.factId}`,correlationId:t.correlationId})}function ke(e,t,n,r,i){return async function(a,o){if(!De(a))return!0;if(await Oe(e,a,t,n,r,i),a.type===`request`)throw Error(`Projected telemetry transport cannot satisfy request responses; exclude it from request routing.`);return a.type===`broadcast`?[]:!0}}function Ae(e){let{inner:t,namespaceRegistry:n,projectorRegistry:r,machineId:i,now:a=Date.now}=e,o={name:e.name,send:ke(t,n,r,i,a),onReceive(e){return t.onReceive(async()=>{})},connect(){return t.connect()},disconnect(){return t.disconnect()},subscribe(){return Promise.resolve()},unsubscribe(){return Promise.resolve()},get ready(){return t.ready},get onNewReadySession(){return t.onNewReadySession},set onNewReadySession(e){t.onNewReadySession=e},get onConnected(){return t.onConnected},set onConnected(e){t.onConnected=e},get onDisconnected(){return t.onDisconnected},set onDisconnected(e){t.onDisconnected=e},isReady(){return t.isReady?.()??!0},cancelRequest(e,n){t.cancelRequest?.(e,n)},onBroadcastResults(e,n,r){t.onBroadcastResults?.(e,n,r)}};return t.reconnect&&(o.reconnect=()=>t.reconnect()),o}export{c as BusAbortError,s as BusError,xe as BusLifecycle,ee as CONNECTION_LOST_ERROR_CODE,h as ChannelAuthError,n as ChannelClosedError,_e as ChannelOnlyError,p as ConnectionLostError,be as CorrelationTracker,pe as DEFAULT_REQUEST_TIMEOUT_MS,L as LOCAL_ORIGIN,l as LocalSubjectError,j as MakaioBus,re as NO_HANDLER_ERROR_CODE,o as NoHandlerError,N as OnceAbortError,de as REMOTE_ORIGIN,te as RequestError,z as SystemChannelSchemas,f as TimeoutError,b as ValidationError,le as __resetWarnedSubjects,Q as buildSubscribeMessage,Se as buildUnsubscribeMessage,k as channelSubject,e as collectorOnlySubject,O as createBusContext,he as createBusInstance,ve as createChannelEndpoint,Ce as createExtensionNamespace,S as createFilteredBus,Ae as createProjectedTelemetryTransport,we as createSubjectTelemetryProjectorRegistry,fe as defaultTransports,T as defineSubjectExtension,ae as deserializeTransportError,A as extendSubject,a as findInErrorChain,ie as getFullSubjectForSubjectDefinition,d as getPath,i as getSubjectFromBusMessage,I as handleCorrelationResponse,M as hostLocalRequest,ne as isNoHandlerErrorForSubject,oe as isRequestCancellation,ge as isRequestSchema,w as localSubject,ce as matchesAnySubscription,D as matchesFilter,se as matchesSubscription,u as mergeFilters,ye as openChannel,P as parseBusUrl,C as projectSubjectTelemetryFacts,m as serializeTransportError,r as shouldReceiveMessage,F as trackMessageCorrelation,x as transportErrorData,me as waitForSubscriptionPropagation};