arkgate 3.1.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,3 @@
1
- "use strict";var fe=Object.create;var k=Object.defineProperty;var pe=Object.getOwnPropertyDescriptor;var ge=Object.getOwnPropertyNames;var me=Object.getPrototypeOf,ye=Object.prototype.hasOwnProperty;var be=(e,n)=>{for(var t in n)k(e,t,{get:n[t],enumerable:!0})},U=(e,n,t,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of ge(n))!ye.call(e,r)&&r!==t&&k(e,r,{get:()=>n[r],enumerable:!(i=pe(n,r))||i.enumerable});return e};var B=(e,n,t)=>(t=e!=null?fe(me(e)):{},U(n||!e||!e.__esModule?k(t,"default",{value:e,enumerable:!0}):t,e)),he=e=>U(k({},"__esModule",{value:!0}),e);var Ve={};be(Ve,{default:()=>Fe,findConfigPath:()=>G,globToRegExp:()=>I,isEdgeDenied:()=>P,layerForRelativePath:()=>S,loadArkConfig:()=>D,noDomainInfraImports:()=>le,noForbiddenGlobals:()=>de,noRawEventPublish:()=>ce,patternSpecificity:()=>$,plugin:()=>E,requirePublishSource:()=>ue,resolveRelativeImport:()=>re});module.exports=he(Ve);var A=B(require("fs"),1),c=B(require("path"),1);var K=new Map;function W(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function O(e){let n="";for(let t=0;t<e.length;t+=1){let i=e[t];if(i==="\\"&&t+1<e.length){let r=e[t+1];if("*?{}[],".includes(r)||r==="\\"){n+="\\"+r,t+=1;continue}n+="/";continue}n+=i}return n}function Ae(e){let n=0;for(let t=0;t<e.length;t+=1){let i=e[t];if(i==="\\"){t+=1;continue}if(i==="{")n+=1;else if(i==="}"&&(n-=1,n<0))return!1}return n===0}function I(e){let n=K.get(e);if(n)return n;let t=O(e),i=Ae(t),r="",o=0;for(let a=0;a<t.length;a+=1){let d=t[a];d==="\\"&&a+1<t.length?(r+=W(t[a+1]),a+=1):d==="*"?t[a+1]==="*"?t[a+2]==="/"?(r+="(?:.*/)?",a+=2):(r+=".*",a+=1):r+="[^/]*":d==="?"?r+="[^/]":d==="{"&&i?(r+="(?:",o+=1):d==="}"&&i&&o>0?(r+=")",o-=1):d===","&&i&&o>0?r+="|":r+=W(d)}let s=new RegExp(`^${r}$`);return K.set(e,s),s}function $(e){let n=O(String(e)),i=n.split("*")[0].split("/").filter(Boolean).length,r=n.replace(/\*/g,"").length;return i*1e4+r}function S(e,n){let t=String(e).split(/[/\\]/).join("/"),i,r=-1;for(let o of n??[])if(!(o.exclude??[]).some(s=>I(s).test(t))){for(let s of o.patterns??[])if(I(s).test(t)){let a=$(s);a>r&&(r=a,i=o.name)}}return i}function q(e,n){if(!n?.length)return;let t=String(e).split(/[/\\]/).filter(Boolean),i=new Set(n.map(r=>String(r).toLowerCase()));for(let r=0;r<t.length-1;r+=1)if(i.has(t[r].toLowerCase()))return`${t[r]}/${t[r+1]}`}function Se(e){let n=new Set;for(let t of e??[]){let r=O(String(t)).split("/").filter(Boolean);for(let o=0;o<r.length;o+=1){let s=r[o];if((s==="**"||s==="*")&&o>0){let a=r[o-1];a&&!a.includes("*")&&!a.includes("{")&&!a.includes("}")&&n.add(a)}}}return[...n]}function ke(e,n,t){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(r=>typeof r=="string"&&r.length>0);let i=(t??[]).find(r=>r.name===n);return Se(i?.patterns)}function Ie(e,n,t,i){for(let r of e??[])if(!(r.from!==n||r.to!==t)&&r.allowed===!1){if(r.peerIsolation){let o=i?.fromPath,s=i?.toPath;if(!o||!s)continue;let a=ke(r,n,i?.layers);if(a.length===0)continue;let d=q(o,a),p=q(s,a);if(!d||!p)continue;if(d!==p)return r;continue}if(n!==t)return r}}function P(e,n,t,i){return Ie(e,n,t,i)!==void 0}var F="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",J=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Re=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Ce(){let e=[];for(let n of J)for(let t of J)n===t||Re.has(`${n}->${t}`)||e.push({from:n,to:t,allowed:!1});return e}var z=Ce();var y={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Y={$schema:"https://json-schema.org/draft/2020-12/schema",$id:F,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:F,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.0",default:"1.0"},name:{type:"string",minLength:1},include:{...y,minItems:1,default:["src"]},exclude:{...y,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:z,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...y,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...y,minItems:1},exclude:y,intentPrefixes:y,description:{type:"string",minLength:1},forbiddenGlobals:y,mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...y,minItems:1}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}}}},h=class extends Error{issues;source;constructor(n,t){super(`Invalid ArkGate config (${n}):
2
- ${t.map(i=>`- ${i.path}: ${i.message}`).join(`
3
- `)}`),this.name="ArkConfigValidationError",this.source=n,this.issues=t}};function Z(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function j(e,n){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(n)?`${e}.${n}`:`${e}[${JSON.stringify(n)}]`}function b(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Ee(e,n){let t="#/$defs/";if(e.startsWith(t))return n.$defs[e.slice(t.length)]}function R(e,n,t,i,r){if(n.$ref){let o=Ee(n.$ref,i);if(!o){r.push({path:t,message:`schema reference ${n.$ref} cannot be resolved`});return}R(e,o,t,i,r);return}if(n.const!==void 0&&!Object.is(e,n.const)){r.push({path:t,message:`must equal ${JSON.stringify(n.const)}`});return}if(n.enum&&!n.enum.some(o=>Object.is(o,e))){r.push({path:t,message:`must be one of ${n.enum.map(String).join(", ")}`});return}if(n.type==="object"){if(!Z(e)){r.push({path:t,message:`must be an object; received ${b(e)}`});return}let o=n.properties??{};for(let s of n.required??[])e[s]===void 0&&r.push({path:j(t,s),message:"is required"});if(n.additionalProperties===!1)for(let s of Object.keys(e))s in o||r.push({path:j(t,s),message:"unknown field"});for(let[s,a]of Object.entries(o))e[s]!==void 0&&R(e[s],a,j(t,s),i,r);return}if(n.type==="array"){if(!Array.isArray(e)){r.push({path:t,message:`must be an array; received ${b(e)}`});return}if(n.minItems!==void 0&&e.length<n.minItems&&r.push({path:t,message:`must contain at least ${n.minItems} item(s)`}),n.uniqueItems){let o=e.map(s=>JSON.stringify(s));new Set(o).size!==o.length&&r.push({path:t,message:"must not contain duplicate items"})}n.items&&e.forEach((o,s)=>R(o,n.items,`${t}[${s}]`,i,r));return}if(n.type==="string"){if(typeof e!="string"){r.push({path:t,message:`must be a string; received ${b(e)}`});return}n.minLength!==void 0&&e.length<n.minLength&&r.push({path:t,message:`must contain at least ${n.minLength} character(s)`});return}if(n.type==="boolean"){typeof e!="boolean"&&r.push({path:t,message:`must be a boolean; received ${b(e)}`});return}if(n.type==="integer"){if(!Number.isInteger(e)){r.push({path:t,message:`must be an integer; received ${b(e)}`});return}n.minimum!==void 0&&e<n.minimum&&r.push({path:t,message:`must be at least ${n.minimum}`})}}function xe(e){return{...e,$schema:e.$schema===void 0?F:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.0":e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?z.map(n=>({...n})):e.rules}}function Ne(e,n="ark.config.json"){if(!Z(e))throw new h(n,[{path:"$",message:`must be an object; received ${b(e)}`}]);let t=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new h(n,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:xe(e),migratedFrom:t}}function we(e,n="ark.config.json"){let{candidate:t,migratedFrom:i}=Ne(e,n),r=[];if(R(t,Y,"$",Y,r),r.length>0)throw new h(n,r);return{config:t,migratedFrom:i}}function Q(e,n="ark.config.json"){let t;try{t=JSON.parse(e)}catch(i){throw new h(n,[{path:"$",message:`invalid JSON: ${i instanceof Error?i.message:String(i)}`}])}return we(t,n)}function m(e){return typeof e=="string"&&e.length>0?e:void 0}function X(e,n){return Number.isInteger(e)&&Number(e)>0?Number(e):n}function Le(e,n,t){return e==="LAYER_IMPORT_VIOLATION"?n.typeOnly||t.targetTypeOnlyExports===!0||t.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":t.peerIsolation===!0?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${n.fromLayer??"the source layer"}, inject the ${n.toLayer??"outer-layer"} implementation, then preflight again.`:e==="FORBIDDEN_GLOBAL"?`Inject ${n.target??"the capability"} through a port, then preflight again.`:e==="CIRCULAR_DEPENDENCY"?"Extract the shared dependency into a third module, then preflight again.":e==="RAW_EVENT_PUBLISH"?"Publish through a registered intent creator, then run Ark again.":e==="PUBLISH_MISSING_SOURCE"?"Add metadata.source to the publish call, then run Ark again.":`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function ee(e,n="error"){let t=m(e.ruleId)??m(e.code)??"ARK_UNKNOWN",i=e.severity==="warning"?"warning":n,r={...m(e.target)?{target:m(e.target)}:{},...m(e.fromLayer)?{fromLayer:m(e.fromLayer)}:{},...m(e.toLayer)?{toLayer:m(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{}};return{ruleId:t,severity:i,message:m(e.message)??t,location:{file:m(e.file)??"<unknown>",line:X(e.line,1),column:X(e.column,1)},evidence:r,nextAction:m(e.nextAction)??Le(t,r,e)}}var ne={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."};function _e(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function V(e){if(!e.publishCall)return[];let n=[];return(e.rawIntentName!==void 0&&_e(e.rawIntentName)||e.objectHasIntent)&&n.push({ruleId:"RAW_EVENT_PUBLISH",message:ne.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&n.push({ruleId:"PUBLISH_MISSING_SOURCE",message:ne.PUBLISH_MISSING_SOURCE}),n}function x(e){if(typeof e.physicalFilename=="string"&&e.physicalFilename.length>0)return e.physicalFilename;if(typeof e.filename=="string"&&e.filename.length>0)return e.filename;if(typeof e.getFilename=="function")try{let n=e.getFilename();if(typeof n=="string"&&n.length>0)return n}catch{}return""}function N(e,n,t,i,r){let o=ee({...i,line:i.line??n.loc?.start?.line,column:i.column??(typeof n.loc?.start?.column=="number"?n.loc.start.column+1:void 0)});return e.report({node:n,messageId:t,...r?{data:r}:{},diagnostic:o}),o}function G(e){if(!e||e==="<input>"||e.startsWith("stdin"))return null;let n=c.default.dirname(c.default.resolve(e));for(;;){let t=c.default.join(n,"ark.config.json");if(A.default.existsSync(t))return t;let i=c.default.dirname(n);if(i===n)return null;n=i}}var M=new Map;function D(e){if(M.has(e))return M.get(e)??null;if(!A.default.existsSync(e))return null;let n=Q(A.default.readFileSync(e,"utf8"),e).config;return M.set(e,n),n}function re(e,n){if(!n.startsWith("."))return null;let t=c.default.resolve(c.default.dirname(e),n),i=[t,`${t}.ts`,`${t}.tsx`,`${t}.mts`,`${t}.cts`,`${t}.js`,`${t}.jsx`,c.default.join(t,"index.ts"),c.default.join(t,"index.tsx"),c.default.join(t,"index.js")];for(let r of i)try{if(A.default.existsSync(r)&&A.default.statSync(r).isFile())return r}catch{}return`${t}.ts`}function w(e){return typeof e?.value=="string"?e.value:void 0}function T(e){return e?.name??w(e)}function H(e){return e.sourceCode??e.getSourceCode?.()}function ie(e,n){let t=H(e)?.getScope?.(n);for(;t;){let i=t.references?.find(r=>r.identifier===n);if(i)return i;t=t.upper??void 0}}function te(e,n,t){let i=ie(e,n);if(i?.resolved)return(i.resolved.defs?.length??0)>0;let r=H(e)?.getScope?.(n);for(;r;){let o=r.set?.get(t);if(o)return(o.defs?.length??0)>0;r=r.upper??void 0}return!1}function Oe(e,n){let t=ie(e,n);return t?t.isValueReference!==!1:n.parent?.type==="VariableDeclarator"&&n.parent.init===n}function oe(e){if(e?.type==="Identifier"&&e.name)return{root:e,segments:[e.name]};if(!e||!(e.type==="MemberExpression"||!!(e.object&&e.property))||e.computed===!0)return;let t=oe(e.object),i=T(e.property);if(!(!t||!i))return{root:t.root,segments:[...t.segments,i]}}function $e(e){return T(e.callee?.property)}function se(e,n){return e?.properties?.find(t=>T(t.key)===n)}function C(e,n){return se(e,n)!==void 0}function Pe(e){let n=se(e,"metadata")?.value;return C(n,"source")}function ae(e){return $e(e)==="publish"}var le={meta:{type:"problem",docs:{description:"Disallow imports that violate ark.config.json layer rules (same contract as arkgate-check)."},messages:{forbiddenImport:"Architecture: {{fromLayer}} must not import {{toLayer}} (ark.config.json). Specifier: {{specifier}}",forbiddenImportHeuristic:"Domain code must not import infrastructure, adapters, repositories, or database modules."},schema:[]},create(e){let n=x(e),t=G(n),i=t?D(t):null,r=t?c.default.dirname(t):null,o=s=>{let a=w(s.source);if(a&&i&&r&&n){let d=c.default.isAbsolute(n)?n:c.default.resolve(n),p=c.default.relative(r,d).split(c.default.sep).join("/"),l=S(p,i.layers);if(!l)return;let u=re(d,a);if(!u)return;let f=c.default.relative(r,u).split(c.default.sep).join("/");if(f.startsWith(".."))return;let g=S(f,i.layers);if(!g)return;P(i.rules,l,g,{fromPath:p,toPath:f,layers:i.layers})&&N(e,s,"forbiddenImport",{ruleId:"LAYER_IMPORT_VIOLATION",file:p,fromLayer:l,toLayer:g,target:f,...s.importKind==="type"?{typeOnly:!0}:{},message:`${l} must not import ${g}.`},{fromLayer:l,toLayer:g,specifier:a});return}};return{ImportDeclaration:o,ExportNamedDeclaration:o,ExportAllDeclaration:o}}},ce={meta:{type:"problem",docs:{description:"Require event bus publish calls to use registered intent creators instead of raw event objects or intent strings."},messages:{rawPublish:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts."},schema:[]},create(e){return{CallExpression(n){let t=n.arguments?.[0],i=w(t),r=V({publishCall:ae(n),rawIntentName:i,objectHasIntent:C(t,"intent"),arkPublishCandidate:!1,hasSource:!0});if(r.some(o=>o.ruleId==="RAW_EVENT_PUBLISH")){let o=r.find(s=>s.ruleId==="RAW_EVENT_PUBLISH");N(e,n,"rawPublish",{...o,file:x(e)})}}}}},ue={meta:{type:"problem",docs:{description:"Require event bus publish calls to include source metadata."},messages:{missingSource:"Strict Ark publish calls must include metadata.source."},schema:[]},create(e){return{CallExpression(n){let t=n.arguments?.[0],i=n.arguments?.[2],o=V({publishCall:ae(n),rawIntentName:w(t),objectHasIntent:C(t,"intent"),arkPublishCandidate:!0,hasSource:Pe(t)||C(i,"source")}).find(s=>s.ruleId==="PUBLISH_MISSING_SOURCE");o&&N(e,n,"missingSource",{...o,file:x(e)})}}}},de={meta:{type:"problem",docs:{description:"Disallow ambient globals from the layer\u2019s forbiddenGlobals in ark.config.json (same purity surface as ark-check). Option `globals` explicitly overrides."},messages:{forbiddenGlobal:'Ambient global "{{name}}" is forbidden in {{layer}} (ark.config.json); inject the capability through a port instead.',forbiddenGlobalDefault:'Ambient global "{{name}}" is forbidden here; inject the capability through a port instead.'},schema:[{type:"object",properties:{globals:{type:"array",items:{type:"string"}}},additionalProperties:!1}]},create(e){let n=x(e),t=e.options?.[0],i=G(n),r=i?D(i):null,o=i?c.default.dirname(i):null,s=null,a="this layer";if(t?.globals)s=new Set(t.globals);else if(r&&o&&n){let l=c.default.isAbsolute(n)?n:c.default.resolve(n),u=c.default.relative(o,l).split(c.default.sep).join("/"),f=r.layers?.find(g=>g.name===S(u,r.layers));f?.forbiddenGlobals?.length?(s=new Set(f.forbiddenGlobals),a=f.name):s=null}if(!s)return{};let d=typeof H(e)?.getScope=="function",p=(l,u)=>{let f=c.default.isAbsolute(n)?n:c.default.resolve(n),g=o?c.default.relative(o,f).split(c.default.sep).join("/"):n;N(e,l,r?"forbiddenGlobal":"forbiddenGlobalDefault",{ruleId:"FORBIDDEN_GLOBAL",file:g,fromLayer:a,target:u,message:`${a} must not use the ambient global "${u}".`},{name:u,layer:a})};return{MemberExpression(l){if(l.parent?.type==="MemberExpression"&&l.parent.object===l)return;let u=oe(l);if(!u||te(e,u.root,u.segments[0]))return;let f=u.segments[0]==="globalThis",g=f?u.segments.slice(1):u.segments,L;for(let _=g.length;_>=(f?1:2);_-=1){let v=g.slice(0,_).join(".");if(s.has(v)){L=v;break}}L?p(l,L):!d&&s.has(u.segments[0])&&p(l,u.segments[0])},CallExpression(l){if(d)return;let u=l.callee?.type==="Identifier"?l.callee.name:void 0;u&&s.has(u)&&p(l,u)},NewExpression(l){if(d)return;let u=l.callee?.type==="Identifier"?l.callee.name:void 0;u&&s.has(u)&&p(l,u)},Identifier(l){!d||!l.name||!s.has(l.name)||!Oe(e,l)||te(e,l,l.name)||p(l,l.name)}}}},je={"no-domain-infra-imports":le,"no-raw-event-publish":ce,"require-publish-source":ue,"no-forbidden-globals":de},E={rules:je};E.configs={recommended:{plugins:{ark:E},rules:{"ark/no-domain-infra-imports":"error","ark/no-raw-event-publish":"error","ark/require-publish-source":"error","ark/no-forbidden-globals":"error"}}};var Fe=E;0&&(module.exports={findConfigPath,globToRegExp,isEdgeDenied,layerForRelativePath,loadArkConfig,noDomainInfraImports,noForbiddenGlobals,noRawEventPublish,patternSpecificity,plugin,requirePublishSource,resolveRelativeImport});
1
+ "use strict";var de=Object.create;var k=Object.defineProperty;var ge=Object.getOwnPropertyDescriptor;var pe=Object.getOwnPropertyNames;var me=Object.getPrototypeOf,ye=Object.prototype.hasOwnProperty;var he=(e,t)=>{for(var n in t)k(e,n,{get:t[n],enumerable:!0})},v=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of pe(t))!ye.call(e,r)&&r!==n&&k(e,r,{get:()=>t[r],enumerable:!(i=ge(t,r))||i.enumerable});return e};var B=(e,t,n)=>(n=e!=null?de(me(e)):{},v(t||!e||!e.__esModule?k(n,"default",{value:e,enumerable:!0}):n,e)),Ae=e=>v(k({},"__esModule",{value:!0}),e);var Fe={};he(Fe,{default:()=>Ve,findConfigPath:()=>D,globToRegExp:()=>R,isEdgeDenied:()=>P,layerForRelativePath:()=>S,loadArkConfig:()=>G,noDomainInfraImports:()=>le,noForbiddenGlobals:()=>fe,noRawEventPublish:()=>ce,patternSpecificity:()=>$,plugin:()=>E,requirePublishSource:()=>ue,resolveRelativeImport:()=>re});module.exports=Ae(Fe);var b=B(require("fs"),1),c=B(require("path"),1);var K=new Map;function W(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function O(e){let t="";for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="\\"&&n+1<e.length){let r=e[n+1];if("*?{}[],".includes(r)||r==="\\"){t+="\\"+r,n+=1;continue}t+="/";continue}t+=i}return t}function be(e){let t=0;for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="\\"){n+=1;continue}if(i==="{")t+=1;else if(i==="}"&&(t-=1,t<0))return!1}return t===0}function R(e){let t=K.get(e);if(t)return t;let n=O(e),i=be(n),r="",o=0;for(let a=0;a<n.length;a+=1){let f=n[a];f==="\\"&&a+1<n.length?(r+=W(n[a+1]),a+=1):f==="*"?n[a+1]==="*"?n[a+2]==="/"?(r+="(?:.*/)?",a+=2):(r+=".*",a+=1):r+="[^/]*":f==="?"?r+="[^/]":f==="{"&&i?(r+="(?:",o+=1):f==="}"&&i&&o>0?(r+=")",o-=1):f===","&&i&&o>0?r+="|":r+=W(f)}let s=new RegExp(`^${r}$`);return K.set(e,s),s}function $(e){let t=O(String(e)),i=t.split("*")[0].split("/").filter(Boolean).length,r=t.replace(/\*/g,"").length;return i*1e4+r}function S(e,t){let n=String(e).split(/[/\\]/).join("/"),i,r=-1;for(let o of t??[])if(!(o.exclude??[]).some(s=>R(s).test(n))){for(let s of o.patterns??[])if(R(s).test(n)){let a=$(s);a>r&&(r=a,i=o.name)}}return i}function q(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),i=new Set(t.map(r=>String(r).toLowerCase()));for(let r=0;r<n.length-1;r+=1)if(i.has(n[r].toLowerCase()))return`${n[r]}/${n[r+1]}`}function Se(e){let t=new Set;for(let n of e??[]){let r=O(String(n)).split("/").filter(Boolean);for(let o=0;o<r.length;o+=1){let s=r[o];if((s==="**"||s==="*")&&o>0){let a=r[o-1];a&&!a.includes("*")&&!a.includes("{")&&!a.includes("}")&&t.add(a)}}}return[...t]}function ke(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(r=>typeof r=="string"&&r.length>0);let i=(n??[]).find(r=>r.name===t);return Se(i?.patterns)}function Re(e,t,n,i){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&r.allowed===!1){if(r.peerIsolation){let o=i?.fromPath,s=i?.toPath;if(!o||!s)continue;let a=ke(r,t,i?.layers);if(a.length===0)continue;let f=q(o,a),g=q(s,a);if(!f||!g)continue;if(f!==g)return r;continue}if(t!==n)return r}}function P(e,t,n,i){return Re(e,t,n,i)!==void 0}var V="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",J=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Ie=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Ce(){let e=[];for(let t of J)for(let n of J)t===n||Ie.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var z=Ce();var y={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Y={$schema:"https://json-schema.org/draft/2020-12/schema",$id:V,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:V,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.0",default:"1.0"},name:{type:"string",minLength:1},include:{...y,minItems:1,default:["src"]},exclude:{...y,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:z,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...y,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...y,minItems:1},exclude:y,intentPrefixes:y,description:{type:"string",minLength:1},forbiddenGlobals:y,mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...y,minItems:1}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}}}},A=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
2
+ ${n.map(i=>`- ${i.path}: ${i.message}`).join(`
3
+ `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Z(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function j(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function h(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Ee(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function I(e,t,n,i,r){if(t.$ref){let o=Ee(t.$ref,i);if(!o){r.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}I(e,o,n,i,r);return}if(t.const!==void 0&&!Object.is(e,t.const)){r.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(o=>Object.is(o,e))){r.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Z(e)){r.push({path:n,message:`must be an object; received ${h(e)}`});return}let o=t.properties??{};for(let s of t.required??[])e[s]===void 0&&r.push({path:j(n,s),message:"is required"});if(t.additionalProperties===!1)for(let s of Object.keys(e))s in o||r.push({path:j(n,s),message:"unknown field"});for(let[s,a]of Object.entries(o))e[s]!==void 0&&I(e[s],a,j(n,s),i,r);return}if(t.type==="array"){if(!Array.isArray(e)){r.push({path:n,message:`must be an array; received ${h(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&r.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let o=e.map(s=>JSON.stringify(s));new Set(o).size!==o.length&&r.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((o,s)=>I(o,t.items,`${n}[${s}]`,i,r));return}if(t.type==="string"){if(typeof e!="string"){r.push({path:n,message:`must be a string; received ${h(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&r.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&r.push({path:n,message:`must be a boolean; received ${h(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){r.push({path:n,message:`must be an integer; received ${h(e)}`});return}t.minimum!==void 0&&e<t.minimum&&r.push({path:n,message:`must be at least ${t.minimum}`})}}function Ne(e){return{...e,$schema:e.$schema===void 0?V:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.0":e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?z.map(t=>({...t})):e.rules}}function xe(e,t="ark.config.json"){if(!Z(e))throw new A(t,[{path:"$",message:`must be an object; received ${h(e)}`}]);let n=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new A(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:Ne(e),migratedFrom:n}}function we(e,t="ark.config.json"){let{candidate:n,migratedFrom:i}=xe(e,t),r=[];if(I(n,Y,"$",Y,r),r.length>0)throw new A(t,r);return{config:n,migratedFrom:i}}function Q(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(i){throw new A(t,[{path:"$",message:`invalid JSON: ${i instanceof Error?i.message:String(i)}`}])}return we(n,t)}function m(e){return typeof e=="string"&&e.length>0?e:void 0}function X(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function Le(e,t,n){return e==="LAYER_IMPORT_VIOLATION"?t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, then preflight again.`:e==="FORBIDDEN_GLOBAL"?`Inject ${t.target??"the capability"} through a port, then preflight again.`:e==="CIRCULAR_DEPENDENCY"?"Extract the shared dependency into a third module, then preflight again.":e==="RAW_EVENT_PUBLISH"?"Publish through a registered intent creator, then run Ark again.":e==="PUBLISH_MISSING_SOURCE"?"Add metadata.source to the publish call, then run Ark again.":`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function ee(e,t="error"){let n=m(e.ruleId)??m(e.code)??"ARK_UNKNOWN",i=e.severity==="warning"?"warning":t,r={...m(e.target)?{target:m(e.target)}:{},...m(e.fromLayer)?{fromLayer:m(e.fromLayer)}:{},...m(e.toLayer)?{toLayer:m(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{}};return{ruleId:n,severity:i,message:m(e.message)??n,location:{file:m(e.file)??"<unknown>",line:X(e.line,1),column:X(e.column,1)},evidence:r,nextAction:m(e.nextAction)??Le(n,r,e)}}var te={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."};function _e(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function F(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&_e(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:te.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:te.PUBLISH_MISSING_SOURCE}),t}function N(e){if(typeof e.physicalFilename=="string"&&e.physicalFilename.length>0)return e.physicalFilename;if(typeof e.filename=="string"&&e.filename.length>0)return e.filename;if(typeof e.getFilename=="function")try{let t=e.getFilename();if(typeof t=="string"&&t.length>0)return t}catch{}return""}function x(e,t,n,i,r){let o=ee({...i,line:i.line??t.loc?.start?.line,column:i.column??(typeof t.loc?.start?.column=="number"?t.loc.start.column+1:void 0)});return e.report({node:t,messageId:n,...r?{data:r}:{},diagnostic:o}),o}function D(e){if(!e||e==="<input>"||e.startsWith("stdin"))return null;let t=c.default.dirname(c.default.resolve(e));for(;;){let n=c.default.join(t,"ark.config.json");if(b.default.existsSync(n))return n;let i=c.default.dirname(t);if(i===t)return null;t=i}}var M=new Map;function G(e){if(M.has(e))return M.get(e)??null;if(!b.default.existsSync(e))return null;let t=Q(b.default.readFileSync(e,"utf8"),e).config;return M.set(e,t),t}function re(e,t){if(!t.startsWith("."))return null;let n=c.default.resolve(c.default.dirname(e),t),i=[n,`${n}.ts`,`${n}.tsx`,`${n}.mts`,`${n}.cts`,`${n}.js`,`${n}.jsx`,c.default.join(n,"index.ts"),c.default.join(n,"index.tsx"),c.default.join(n,"index.js")];for(let r of i)try{if(b.default.existsSync(r)&&b.default.statSync(r).isFile())return r}catch{}return`${n}.ts`}function w(e){return typeof e?.value=="string"?e.value:void 0}function T(e){return e?.name??w(e)}function H(e){return e.sourceCode??e.getSourceCode?.()}function ie(e,t){let n=H(e)?.getScope?.(t);for(;n;){let i=n.references?.find(r=>r.identifier===t);if(i)return i;n=n.upper??void 0}}function ne(e,t,n){let i=ie(e,t);if(i?.resolved)return(i.resolved.defs?.length??0)>0;let r=H(e)?.getScope?.(t);for(;r;){let o=r.set?.get(n);if(o)return(o.defs?.length??0)>0;r=r.upper??void 0}return!1}function Oe(e,t){let n=ie(e,t);return n?n.isValueReference!==!1:t.parent?.type==="VariableDeclarator"&&t.parent.init===t}function oe(e){if(e?.type==="Identifier"&&e.name)return{root:e,segments:[e.name]};if(!e||!(e.type==="MemberExpression"||!!(e.object&&e.property))||e.computed===!0)return;let n=oe(e.object),i=T(e.property);if(!(!n||!i))return{root:n.root,segments:[...n.segments,i]}}function $e(e){return T(e.callee?.property)}function se(e,t){return e?.properties?.find(n=>T(n.key)===t)}function C(e,t){return se(e,t)!==void 0}function Pe(e){let t=se(e,"metadata")?.value;return C(t,"source")}function ae(e){return $e(e)==="publish"}var le={meta:{type:"problem",docs:{description:"Disallow imports that violate ark.config.json layer rules (same contract as arkgate-check)."},messages:{forbiddenImport:"Architecture: {{fromLayer}} must not import {{toLayer}} (ark.config.json). Specifier: {{specifier}}",forbiddenImportHeuristic:"Domain code must not import infrastructure, adapters, repositories, or database modules."},schema:[]},create(e){let t=N(e),n=D(t),i=n?G(n):null,r=n?c.default.dirname(n):null,o=s=>{let a=w(s.source);if(a&&i&&r&&t){let f=c.default.isAbsolute(t)?t:c.default.resolve(t),g=c.default.relative(r,f).split(c.default.sep).join("/"),l=S(g,i.layers);if(!l)return;let u=re(f,a);if(!u)return;let d=c.default.relative(r,u).split(c.default.sep).join("/");if(d.startsWith(".."))return;let p=S(d,i.layers);if(!p)return;P(i.rules,l,p,{fromPath:g,toPath:d,layers:i.layers})&&x(e,s,"forbiddenImport",{ruleId:"LAYER_IMPORT_VIOLATION",file:g,fromLayer:l,toLayer:p,target:d,...s.importKind==="type"?{typeOnly:!0}:{},message:`${l} must not import ${p}.`},{fromLayer:l,toLayer:p,specifier:a});return}};return{ImportDeclaration:o,ExportNamedDeclaration:o,ExportAllDeclaration:o}}},ce={meta:{type:"problem",docs:{description:"Require event bus publish calls to use registered intent creators instead of raw event objects or intent strings."},messages:{rawPublish:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts."},schema:[]},create(e){return{CallExpression(t){let n=t.arguments?.[0],i=w(n),r=F({publishCall:ae(t),rawIntentName:i,objectHasIntent:C(n,"intent"),arkPublishCandidate:!1,hasSource:!0});if(r.some(o=>o.ruleId==="RAW_EVENT_PUBLISH")){let o=r.find(s=>s.ruleId==="RAW_EVENT_PUBLISH");x(e,t,"rawPublish",{...o,file:N(e)})}}}}},ue={meta:{type:"problem",docs:{description:"Require event bus publish calls to include source metadata."},messages:{missingSource:"Strict Ark publish calls must include metadata.source."},schema:[]},create(e){return{CallExpression(t){let n=t.arguments?.[0],i=t.arguments?.[2],o=F({publishCall:ae(t),rawIntentName:w(n),objectHasIntent:C(n,"intent"),arkPublishCandidate:!0,hasSource:Pe(n)||C(i,"source")}).find(s=>s.ruleId==="PUBLISH_MISSING_SOURCE");o&&x(e,t,"missingSource",{...o,file:N(e)})}}}},fe={meta:{type:"problem",docs:{description:"Disallow ambient globals from the layer\u2019s forbiddenGlobals in ark.config.json (same purity surface as ark-check). Option `globals` explicitly overrides."},messages:{forbiddenGlobal:'Ambient global "{{name}}" is forbidden in {{layer}} (ark.config.json); inject the capability through a port instead.',forbiddenGlobalDefault:'Ambient global "{{name}}" is forbidden here; inject the capability through a port instead.'},schema:[{type:"object",properties:{globals:{type:"array",items:{type:"string"}}},additionalProperties:!1}]},create(e){let t=N(e),n=e.options?.[0],i=D(t),r=i?G(i):null,o=i?c.default.dirname(i):null,s=null,a="this layer";if(n?.globals)s=new Set(n.globals);else if(r&&o&&t){let l=c.default.isAbsolute(t)?t:c.default.resolve(t),u=c.default.relative(o,l).split(c.default.sep).join("/"),d=r.layers?.find(p=>p.name===S(u,r.layers));d?.forbiddenGlobals?.length?(s=new Set(d.forbiddenGlobals),a=d.name):s=null}if(!s)return{};let f=typeof H(e)?.getScope=="function",g=(l,u)=>{let d=c.default.isAbsolute(t)?t:c.default.resolve(t),p=o?c.default.relative(o,d).split(c.default.sep).join("/"):t;x(e,l,r?"forbiddenGlobal":"forbiddenGlobalDefault",{ruleId:"FORBIDDEN_GLOBAL",file:p,fromLayer:a,target:u,message:`${a} must not use the ambient global "${u}".`},{name:u,layer:a})};return{MemberExpression(l){if(l.parent?.type==="MemberExpression"&&l.parent.object===l)return;let u=oe(l);if(!u||ne(e,u.root,u.segments[0]))return;let d=u.segments[0]==="globalThis",p=d?u.segments.slice(1):u.segments,L;for(let _=p.length;_>=(d?1:2);_-=1){let U=p.slice(0,_).join(".");if(s.has(U)){L=U;break}}L?g(l,L):!f&&s.has(u.segments[0])&&g(l,u.segments[0])},CallExpression(l){if(f)return;let u=l.callee?.type==="Identifier"?l.callee.name:void 0;u&&s.has(u)&&g(l,u)},NewExpression(l){if(f)return;let u=l.callee?.type==="Identifier"?l.callee.name:void 0;u&&s.has(u)&&g(l,u)},Identifier(l){!f||!l.name||!s.has(l.name)||!Oe(e,l)||ne(e,l,l.name)||g(l,l.name)}}}},je={"no-domain-infra-imports":le,"no-raw-event-publish":ce,"require-publish-source":ue,"no-forbidden-globals":fe},E={rules:je};E.configs={recommended:{plugins:{ark:E},rules:{"ark/no-domain-infra-imports":"error","ark/no-raw-event-publish":"error","ark/require-publish-source":"error","ark/no-forbidden-globals":"error"}}};var Ve=E;0&&(module.exports={findConfigPath,globToRegExp,isEdgeDenied,layerForRelativePath,loadArkConfig,noDomainInfraImports,noForbiddenGlobals,noRawEventPublish,patternSpecificity,plugin,requirePublishSource,resolveRelativeImport});
@@ -1,4 +1,4 @@
1
- import { A as ArkConfig } from '../configContract-BxSIwVRo.cjs';
1
+ import { A as ArkConfig } from '../configTypes-CVWWhBoe.cjs';
2
2
 
3
3
  /**
4
4
  * Pure layer-glob matching for ark.config.json.
@@ -1,4 +1,4 @@
1
- import { A as ArkConfig } from '../configContract-BxSIwVRo.js';
1
+ import { A as ArkConfig } from '../configTypes-CVWWhBoe.js';
2
2
 
3
3
  /**
4
4
  * Pure layer-glob matching for ark.config.json.
@@ -1,3 +1,3 @@
1
- import A from"fs";import u from"path";var G=new Map;function D(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function L(e){let n="";for(let t=0;t<e.length;t+=1){let i=e[t];if(i==="\\"&&t+1<e.length){let r=e[t+1];if("*?{}[],".includes(r)||r==="\\"){n+="\\"+r,t+=1;continue}n+="/";continue}n+=i}return n}function ie(e){let n=0;for(let t=0;t<e.length;t+=1){let i=e[t];if(i==="\\"){t+=1;continue}if(i==="{")n+=1;else if(i==="}"&&(n-=1,n<0))return!1}return n===0}function w(e){let n=G.get(e);if(n)return n;let t=L(e),i=ie(t),r="",o=0;for(let a=0;a<t.length;a+=1){let d=t[a];d==="\\"&&a+1<t.length?(r+=D(t[a+1]),a+=1):d==="*"?t[a+1]==="*"?t[a+2]==="/"?(r+="(?:.*/)?",a+=2):(r+=".*",a+=1):r+="[^/]*":d==="?"?r+="[^/]":d==="{"&&i?(r+="(?:",o+=1):d==="}"&&i&&o>0?(r+=")",o-=1):d===","&&i&&o>0?r+="|":r+=D(d)}let s=new RegExp(`^${r}$`);return G.set(e,s),s}function H(e){let n=L(String(e)),i=n.split("*")[0].split("/").filter(Boolean).length,r=n.replace(/\*/g,"").length;return i*1e4+r}function S(e,n){let t=String(e).split(/[/\\]/).join("/"),i,r=-1;for(let o of n??[])if(!(o.exclude??[]).some(s=>w(s).test(t))){for(let s of o.patterns??[])if(w(s).test(t)){let a=H(s);a>r&&(r=a,i=o.name)}}return i}function T(e,n){if(!n?.length)return;let t=String(e).split(/[/\\]/).filter(Boolean),i=new Set(n.map(r=>String(r).toLowerCase()));for(let r=0;r<t.length-1;r+=1)if(i.has(t[r].toLowerCase()))return`${t[r]}/${t[r+1]}`}function oe(e){let n=new Set;for(let t of e??[]){let r=L(String(t)).split("/").filter(Boolean);for(let o=0;o<r.length;o+=1){let s=r[o];if((s==="**"||s==="*")&&o>0){let a=r[o-1];a&&!a.includes("*")&&!a.includes("{")&&!a.includes("}")&&n.add(a)}}}return[...n]}function se(e,n,t){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(r=>typeof r=="string"&&r.length>0);let i=(t??[]).find(r=>r.name===n);return oe(i?.patterns)}function ae(e,n,t,i){for(let r of e??[])if(!(r.from!==n||r.to!==t)&&r.allowed===!1){if(r.peerIsolation){let o=i?.fromPath,s=i?.toPath;if(!o||!s)continue;let a=se(r,n,i?.layers);if(a.length===0)continue;let d=T(o,a),p=T(s,a);if(!d||!p)continue;if(d!==p)return r;continue}if(n!==t)return r}}function v(e,n,t,i){return ae(e,n,t,i)!==void 0}var O="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",U=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],le=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function ce(){let e=[];for(let n of U)for(let t of U)n===t||le.has(`${n}->${t}`)||e.push({from:n,to:t,allowed:!1});return e}var K=ce();var y={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},B={$schema:"https://json-schema.org/draft/2020-12/schema",$id:O,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:O,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.0",default:"1.0"},name:{type:"string",minLength:1},include:{...y,minItems:1,default:["src"]},exclude:{...y,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:K,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...y,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...y,minItems:1},exclude:y,intentPrefixes:y,description:{type:"string",minLength:1},forbiddenGlobals:y,mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...y,minItems:1}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}}}},h=class extends Error{issues;source;constructor(n,t){super(`Invalid ArkGate config (${n}):
2
- ${t.map(i=>`- ${i.path}: ${i.message}`).join(`
3
- `)}`),this.name="ArkConfigValidationError",this.source=n,this.issues=t}};function W(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function _(e,n){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(n)?`${e}.${n}`:`${e}[${JSON.stringify(n)}]`}function b(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function ue(e,n){let t="#/$defs/";if(e.startsWith(t))return n.$defs[e.slice(t.length)]}function k(e,n,t,i,r){if(n.$ref){let o=ue(n.$ref,i);if(!o){r.push({path:t,message:`schema reference ${n.$ref} cannot be resolved`});return}k(e,o,t,i,r);return}if(n.const!==void 0&&!Object.is(e,n.const)){r.push({path:t,message:`must equal ${JSON.stringify(n.const)}`});return}if(n.enum&&!n.enum.some(o=>Object.is(o,e))){r.push({path:t,message:`must be one of ${n.enum.map(String).join(", ")}`});return}if(n.type==="object"){if(!W(e)){r.push({path:t,message:`must be an object; received ${b(e)}`});return}let o=n.properties??{};for(let s of n.required??[])e[s]===void 0&&r.push({path:_(t,s),message:"is required"});if(n.additionalProperties===!1)for(let s of Object.keys(e))s in o||r.push({path:_(t,s),message:"unknown field"});for(let[s,a]of Object.entries(o))e[s]!==void 0&&k(e[s],a,_(t,s),i,r);return}if(n.type==="array"){if(!Array.isArray(e)){r.push({path:t,message:`must be an array; received ${b(e)}`});return}if(n.minItems!==void 0&&e.length<n.minItems&&r.push({path:t,message:`must contain at least ${n.minItems} item(s)`}),n.uniqueItems){let o=e.map(s=>JSON.stringify(s));new Set(o).size!==o.length&&r.push({path:t,message:"must not contain duplicate items"})}n.items&&e.forEach((o,s)=>k(o,n.items,`${t}[${s}]`,i,r));return}if(n.type==="string"){if(typeof e!="string"){r.push({path:t,message:`must be a string; received ${b(e)}`});return}n.minLength!==void 0&&e.length<n.minLength&&r.push({path:t,message:`must contain at least ${n.minLength} character(s)`});return}if(n.type==="boolean"){typeof e!="boolean"&&r.push({path:t,message:`must be a boolean; received ${b(e)}`});return}if(n.type==="integer"){if(!Number.isInteger(e)){r.push({path:t,message:`must be an integer; received ${b(e)}`});return}n.minimum!==void 0&&e<n.minimum&&r.push({path:t,message:`must be at least ${n.minimum}`})}}function de(e){return{...e,$schema:e.$schema===void 0?O:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.0":e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?K.map(n=>({...n})):e.rules}}function fe(e,n="ark.config.json"){if(!W(e))throw new h(n,[{path:"$",message:`must be an object; received ${b(e)}`}]);let t=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new h(n,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:de(e),migratedFrom:t}}function pe(e,n="ark.config.json"){let{candidate:t,migratedFrom:i}=fe(e,n),r=[];if(k(t,B,"$",B,r),r.length>0)throw new h(n,r);return{config:t,migratedFrom:i}}function q(e,n="ark.config.json"){let t;try{t=JSON.parse(e)}catch(i){throw new h(n,[{path:"$",message:`invalid JSON: ${i instanceof Error?i.message:String(i)}`}])}return pe(t,n)}function m(e){return typeof e=="string"&&e.length>0?e:void 0}function J(e,n){return Number.isInteger(e)&&Number(e)>0?Number(e):n}function ge(e,n,t){return e==="LAYER_IMPORT_VIOLATION"?n.typeOnly||t.targetTypeOnlyExports===!0||t.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":t.peerIsolation===!0?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${n.fromLayer??"the source layer"}, inject the ${n.toLayer??"outer-layer"} implementation, then preflight again.`:e==="FORBIDDEN_GLOBAL"?`Inject ${n.target??"the capability"} through a port, then preflight again.`:e==="CIRCULAR_DEPENDENCY"?"Extract the shared dependency into a third module, then preflight again.":e==="RAW_EVENT_PUBLISH"?"Publish through a registered intent creator, then run Ark again.":e==="PUBLISH_MISSING_SOURCE"?"Add metadata.source to the publish call, then run Ark again.":`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function Y(e,n="error"){let t=m(e.ruleId)??m(e.code)??"ARK_UNKNOWN",i=e.severity==="warning"?"warning":n,r={...m(e.target)?{target:m(e.target)}:{},...m(e.fromLayer)?{fromLayer:m(e.fromLayer)}:{},...m(e.toLayer)?{toLayer:m(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{}};return{ruleId:t,severity:i,message:m(e.message)??t,location:{file:m(e.file)??"<unknown>",line:J(e.line,1),column:J(e.column,1)},evidence:r,nextAction:m(e.nextAction)??ge(t,r,e)}}var z={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."};function me(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function $(e){if(!e.publishCall)return[];let n=[];return(e.rawIntentName!==void 0&&me(e.rawIntentName)||e.objectHasIntent)&&n.push({ruleId:"RAW_EVENT_PUBLISH",message:z.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&n.push({ruleId:"PUBLISH_MISSING_SOURCE",message:z.PUBLISH_MISSING_SOURCE}),n}function R(e){if(typeof e.physicalFilename=="string"&&e.physicalFilename.length>0)return e.physicalFilename;if(typeof e.filename=="string"&&e.filename.length>0)return e.filename;if(typeof e.getFilename=="function")try{let n=e.getFilename();if(typeof n=="string"&&n.length>0)return n}catch{}return""}function C(e,n,t,i,r){let o=Y({...i,line:i.line??n.loc?.start?.line,column:i.column??(typeof n.loc?.start?.column=="number"?n.loc.start.column+1:void 0)});return e.report({node:n,messageId:t,...r?{data:r}:{},diagnostic:o}),o}function Q(e){if(!e||e==="<input>"||e.startsWith("stdin"))return null;let n=u.dirname(u.resolve(e));for(;;){let t=u.join(n,"ark.config.json");if(A.existsSync(t))return t;let i=u.dirname(n);if(i===n)return null;n=i}}var P=new Map;function X(e){if(P.has(e))return P.get(e)??null;if(!A.existsSync(e))return null;let n=q(A.readFileSync(e,"utf8"),e).config;return P.set(e,n),n}function ye(e,n){if(!n.startsWith("."))return null;let t=u.resolve(u.dirname(e),n),i=[t,`${t}.ts`,`${t}.tsx`,`${t}.mts`,`${t}.cts`,`${t}.js`,`${t}.jsx`,u.join(t,"index.ts"),u.join(t,"index.tsx"),u.join(t,"index.js")];for(let r of i)try{if(A.existsSync(r)&&A.statSync(r).isFile())return r}catch{}return`${t}.ts`}function E(e){return typeof e?.value=="string"?e.value:void 0}function F(e){return e?.name??E(e)}function V(e){return e.sourceCode??e.getSourceCode?.()}function ee(e,n){let t=V(e)?.getScope?.(n);for(;t;){let i=t.references?.find(r=>r.identifier===n);if(i)return i;t=t.upper??void 0}}function Z(e,n,t){let i=ee(e,n);if(i?.resolved)return(i.resolved.defs?.length??0)>0;let r=V(e)?.getScope?.(n);for(;r;){let o=r.set?.get(t);if(o)return(o.defs?.length??0)>0;r=r.upper??void 0}return!1}function be(e,n){let t=ee(e,n);return t?t.isValueReference!==!1:n.parent?.type==="VariableDeclarator"&&n.parent.init===n}function ne(e){if(e?.type==="Identifier"&&e.name)return{root:e,segments:[e.name]};if(!e||!(e.type==="MemberExpression"||!!(e.object&&e.property))||e.computed===!0)return;let t=ne(e.object),i=F(e.property);if(!(!t||!i))return{root:t.root,segments:[...t.segments,i]}}function he(e){return F(e.callee?.property)}function te(e,n){return e?.properties?.find(t=>F(t.key)===n)}function I(e,n){return te(e,n)!==void 0}function Ae(e){let n=te(e,"metadata")?.value;return I(n,"source")}function re(e){return he(e)==="publish"}var Se={meta:{type:"problem",docs:{description:"Disallow imports that violate ark.config.json layer rules (same contract as arkgate-check)."},messages:{forbiddenImport:"Architecture: {{fromLayer}} must not import {{toLayer}} (ark.config.json). Specifier: {{specifier}}",forbiddenImportHeuristic:"Domain code must not import infrastructure, adapters, repositories, or database modules."},schema:[]},create(e){let n=R(e),t=Q(n),i=t?X(t):null,r=t?u.dirname(t):null,o=s=>{let a=E(s.source);if(a&&i&&r&&n){let d=u.isAbsolute(n)?n:u.resolve(n),p=u.relative(r,d).split(u.sep).join("/"),l=S(p,i.layers);if(!l)return;let c=ye(d,a);if(!c)return;let f=u.relative(r,c).split(u.sep).join("/");if(f.startsWith(".."))return;let g=S(f,i.layers);if(!g)return;v(i.rules,l,g,{fromPath:p,toPath:f,layers:i.layers})&&C(e,s,"forbiddenImport",{ruleId:"LAYER_IMPORT_VIOLATION",file:p,fromLayer:l,toLayer:g,target:f,...s.importKind==="type"?{typeOnly:!0}:{},message:`${l} must not import ${g}.`},{fromLayer:l,toLayer:g,specifier:a});return}};return{ImportDeclaration:o,ExportNamedDeclaration:o,ExportAllDeclaration:o}}},ke={meta:{type:"problem",docs:{description:"Require event bus publish calls to use registered intent creators instead of raw event objects or intent strings."},messages:{rawPublish:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts."},schema:[]},create(e){return{CallExpression(n){let t=n.arguments?.[0],i=E(t),r=$({publishCall:re(n),rawIntentName:i,objectHasIntent:I(t,"intent"),arkPublishCandidate:!1,hasSource:!0});if(r.some(o=>o.ruleId==="RAW_EVENT_PUBLISH")){let o=r.find(s=>s.ruleId==="RAW_EVENT_PUBLISH");C(e,n,"rawPublish",{...o,file:R(e)})}}}}},Ie={meta:{type:"problem",docs:{description:"Require event bus publish calls to include source metadata."},messages:{missingSource:"Strict Ark publish calls must include metadata.source."},schema:[]},create(e){return{CallExpression(n){let t=n.arguments?.[0],i=n.arguments?.[2],o=$({publishCall:re(n),rawIntentName:E(t),objectHasIntent:I(t,"intent"),arkPublishCandidate:!0,hasSource:Ae(t)||I(i,"source")}).find(s=>s.ruleId==="PUBLISH_MISSING_SOURCE");o&&C(e,n,"missingSource",{...o,file:R(e)})}}}},Re={meta:{type:"problem",docs:{description:"Disallow ambient globals from the layer\u2019s forbiddenGlobals in ark.config.json (same purity surface as ark-check). Option `globals` explicitly overrides."},messages:{forbiddenGlobal:'Ambient global "{{name}}" is forbidden in {{layer}} (ark.config.json); inject the capability through a port instead.',forbiddenGlobalDefault:'Ambient global "{{name}}" is forbidden here; inject the capability through a port instead.'},schema:[{type:"object",properties:{globals:{type:"array",items:{type:"string"}}},additionalProperties:!1}]},create(e){let n=R(e),t=e.options?.[0],i=Q(n),r=i?X(i):null,o=i?u.dirname(i):null,s=null,a="this layer";if(t?.globals)s=new Set(t.globals);else if(r&&o&&n){let l=u.isAbsolute(n)?n:u.resolve(n),c=u.relative(o,l).split(u.sep).join("/"),f=r.layers?.find(g=>g.name===S(c,r.layers));f?.forbiddenGlobals?.length?(s=new Set(f.forbiddenGlobals),a=f.name):s=null}if(!s)return{};let d=typeof V(e)?.getScope=="function",p=(l,c)=>{let f=u.isAbsolute(n)?n:u.resolve(n),g=o?u.relative(o,f).split(u.sep).join("/"):n;C(e,l,r?"forbiddenGlobal":"forbiddenGlobalDefault",{ruleId:"FORBIDDEN_GLOBAL",file:g,fromLayer:a,target:c,message:`${a} must not use the ambient global "${c}".`},{name:c,layer:a})};return{MemberExpression(l){if(l.parent?.type==="MemberExpression"&&l.parent.object===l)return;let c=ne(l);if(!c||Z(e,c.root,c.segments[0]))return;let f=c.segments[0]==="globalThis",g=f?c.segments.slice(1):c.segments,x;for(let N=g.length;N>=(f?1:2);N-=1){let M=g.slice(0,N).join(".");if(s.has(M)){x=M;break}}x?p(l,x):!d&&s.has(c.segments[0])&&p(l,c.segments[0])},CallExpression(l){if(d)return;let c=l.callee?.type==="Identifier"?l.callee.name:void 0;c&&s.has(c)&&p(l,c)},NewExpression(l){if(d)return;let c=l.callee?.type==="Identifier"?l.callee.name:void 0;c&&s.has(c)&&p(l,c)},Identifier(l){!d||!l.name||!s.has(l.name)||!be(e,l)||Z(e,l,l.name)||p(l,l.name)}}}},Ce={"no-domain-infra-imports":Se,"no-raw-event-publish":ke,"require-publish-source":Ie,"no-forbidden-globals":Re},j={rules:Ce};j.configs={recommended:{plugins:{ark:j},rules:{"ark/no-domain-infra-imports":"error","ark/no-raw-event-publish":"error","ark/require-publish-source":"error","ark/no-forbidden-globals":"error"}}};var Fe=j;export{Fe as default,Q as findConfigPath,w as globToRegExp,v as isEdgeDenied,S as layerForRelativePath,X as loadArkConfig,Se as noDomainInfraImports,Re as noForbiddenGlobals,ke as noRawEventPublish,H as patternSpecificity,j as plugin,Ie as requirePublishSource,ye as resolveRelativeImport};
1
+ import b from"fs";import u from"path";var D=new Map;function G(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function L(e){let t="";for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="\\"&&n+1<e.length){let r=e[n+1];if("*?{}[],".includes(r)||r==="\\"){t+="\\"+r,n+=1;continue}t+="/";continue}t+=i}return t}function ie(e){let t=0;for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="\\"){n+=1;continue}if(i==="{")t+=1;else if(i==="}"&&(t-=1,t<0))return!1}return t===0}function w(e){let t=D.get(e);if(t)return t;let n=L(e),i=ie(n),r="",o=0;for(let a=0;a<n.length;a+=1){let f=n[a];f==="\\"&&a+1<n.length?(r+=G(n[a+1]),a+=1):f==="*"?n[a+1]==="*"?n[a+2]==="/"?(r+="(?:.*/)?",a+=2):(r+=".*",a+=1):r+="[^/]*":f==="?"?r+="[^/]":f==="{"&&i?(r+="(?:",o+=1):f==="}"&&i&&o>0?(r+=")",o-=1):f===","&&i&&o>0?r+="|":r+=G(f)}let s=new RegExp(`^${r}$`);return D.set(e,s),s}function H(e){let t=L(String(e)),i=t.split("*")[0].split("/").filter(Boolean).length,r=t.replace(/\*/g,"").length;return i*1e4+r}function S(e,t){let n=String(e).split(/[/\\]/).join("/"),i,r=-1;for(let o of t??[])if(!(o.exclude??[]).some(s=>w(s).test(n))){for(let s of o.patterns??[])if(w(s).test(n)){let a=H(s);a>r&&(r=a,i=o.name)}}return i}function T(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),i=new Set(t.map(r=>String(r).toLowerCase()));for(let r=0;r<n.length-1;r+=1)if(i.has(n[r].toLowerCase()))return`${n[r]}/${n[r+1]}`}function oe(e){let t=new Set;for(let n of e??[]){let r=L(String(n)).split("/").filter(Boolean);for(let o=0;o<r.length;o+=1){let s=r[o];if((s==="**"||s==="*")&&o>0){let a=r[o-1];a&&!a.includes("*")&&!a.includes("{")&&!a.includes("}")&&t.add(a)}}}return[...t]}function se(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(r=>typeof r=="string"&&r.length>0);let i=(n??[]).find(r=>r.name===t);return oe(i?.patterns)}function ae(e,t,n,i){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&r.allowed===!1){if(r.peerIsolation){let o=i?.fromPath,s=i?.toPath;if(!o||!s)continue;let a=se(r,t,i?.layers);if(a.length===0)continue;let f=T(o,a),g=T(s,a);if(!f||!g)continue;if(f!==g)return r;continue}if(t!==n)return r}}function U(e,t,n,i){return ae(e,t,n,i)!==void 0}var O="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",v=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],le=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function ce(){let e=[];for(let t of v)for(let n of v)t===n||le.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var K=ce();var y={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},B={$schema:"https://json-schema.org/draft/2020-12/schema",$id:O,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:O,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.0",default:"1.0"},name:{type:"string",minLength:1},include:{...y,minItems:1,default:["src"]},exclude:{...y,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:K,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...y,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...y,minItems:1},exclude:y,intentPrefixes:y,description:{type:"string",minLength:1},forbiddenGlobals:y,mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...y,minItems:1}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}}}},A=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
2
+ ${n.map(i=>`- ${i.path}: ${i.message}`).join(`
3
+ `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function W(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function _(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function h(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function ue(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function k(e,t,n,i,r){if(t.$ref){let o=ue(t.$ref,i);if(!o){r.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}k(e,o,n,i,r);return}if(t.const!==void 0&&!Object.is(e,t.const)){r.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(o=>Object.is(o,e))){r.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!W(e)){r.push({path:n,message:`must be an object; received ${h(e)}`});return}let o=t.properties??{};for(let s of t.required??[])e[s]===void 0&&r.push({path:_(n,s),message:"is required"});if(t.additionalProperties===!1)for(let s of Object.keys(e))s in o||r.push({path:_(n,s),message:"unknown field"});for(let[s,a]of Object.entries(o))e[s]!==void 0&&k(e[s],a,_(n,s),i,r);return}if(t.type==="array"){if(!Array.isArray(e)){r.push({path:n,message:`must be an array; received ${h(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&r.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let o=e.map(s=>JSON.stringify(s));new Set(o).size!==o.length&&r.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((o,s)=>k(o,t.items,`${n}[${s}]`,i,r));return}if(t.type==="string"){if(typeof e!="string"){r.push({path:n,message:`must be a string; received ${h(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&r.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&r.push({path:n,message:`must be a boolean; received ${h(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){r.push({path:n,message:`must be an integer; received ${h(e)}`});return}t.minimum!==void 0&&e<t.minimum&&r.push({path:n,message:`must be at least ${t.minimum}`})}}function fe(e){return{...e,$schema:e.$schema===void 0?O:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.0":e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?K.map(t=>({...t})):e.rules}}function de(e,t="ark.config.json"){if(!W(e))throw new A(t,[{path:"$",message:`must be an object; received ${h(e)}`}]);let n=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new A(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:fe(e),migratedFrom:n}}function ge(e,t="ark.config.json"){let{candidate:n,migratedFrom:i}=de(e,t),r=[];if(k(n,B,"$",B,r),r.length>0)throw new A(t,r);return{config:n,migratedFrom:i}}function q(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(i){throw new A(t,[{path:"$",message:`invalid JSON: ${i instanceof Error?i.message:String(i)}`}])}return ge(n,t)}function m(e){return typeof e=="string"&&e.length>0?e:void 0}function J(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function pe(e,t,n){return e==="LAYER_IMPORT_VIOLATION"?t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, then preflight again.`:e==="FORBIDDEN_GLOBAL"?`Inject ${t.target??"the capability"} through a port, then preflight again.`:e==="CIRCULAR_DEPENDENCY"?"Extract the shared dependency into a third module, then preflight again.":e==="RAW_EVENT_PUBLISH"?"Publish through a registered intent creator, then run Ark again.":e==="PUBLISH_MISSING_SOURCE"?"Add metadata.source to the publish call, then run Ark again.":`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function Y(e,t="error"){let n=m(e.ruleId)??m(e.code)??"ARK_UNKNOWN",i=e.severity==="warning"?"warning":t,r={...m(e.target)?{target:m(e.target)}:{},...m(e.fromLayer)?{fromLayer:m(e.fromLayer)}:{},...m(e.toLayer)?{toLayer:m(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{}};return{ruleId:n,severity:i,message:m(e.message)??n,location:{file:m(e.file)??"<unknown>",line:J(e.line,1),column:J(e.column,1)},evidence:r,nextAction:m(e.nextAction)??pe(n,r,e)}}var z={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."};function me(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function $(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&me(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:z.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:z.PUBLISH_MISSING_SOURCE}),t}function I(e){if(typeof e.physicalFilename=="string"&&e.physicalFilename.length>0)return e.physicalFilename;if(typeof e.filename=="string"&&e.filename.length>0)return e.filename;if(typeof e.getFilename=="function")try{let t=e.getFilename();if(typeof t=="string"&&t.length>0)return t}catch{}return""}function C(e,t,n,i,r){let o=Y({...i,line:i.line??t.loc?.start?.line,column:i.column??(typeof t.loc?.start?.column=="number"?t.loc.start.column+1:void 0)});return e.report({node:t,messageId:n,...r?{data:r}:{},diagnostic:o}),o}function Q(e){if(!e||e==="<input>"||e.startsWith("stdin"))return null;let t=u.dirname(u.resolve(e));for(;;){let n=u.join(t,"ark.config.json");if(b.existsSync(n))return n;let i=u.dirname(t);if(i===t)return null;t=i}}var P=new Map;function X(e){if(P.has(e))return P.get(e)??null;if(!b.existsSync(e))return null;let t=q(b.readFileSync(e,"utf8"),e).config;return P.set(e,t),t}function ye(e,t){if(!t.startsWith("."))return null;let n=u.resolve(u.dirname(e),t),i=[n,`${n}.ts`,`${n}.tsx`,`${n}.mts`,`${n}.cts`,`${n}.js`,`${n}.jsx`,u.join(n,"index.ts"),u.join(n,"index.tsx"),u.join(n,"index.js")];for(let r of i)try{if(b.existsSync(r)&&b.statSync(r).isFile())return r}catch{}return`${n}.ts`}function E(e){return typeof e?.value=="string"?e.value:void 0}function V(e){return e?.name??E(e)}function F(e){return e.sourceCode??e.getSourceCode?.()}function ee(e,t){let n=F(e)?.getScope?.(t);for(;n;){let i=n.references?.find(r=>r.identifier===t);if(i)return i;n=n.upper??void 0}}function Z(e,t,n){let i=ee(e,t);if(i?.resolved)return(i.resolved.defs?.length??0)>0;let r=F(e)?.getScope?.(t);for(;r;){let o=r.set?.get(n);if(o)return(o.defs?.length??0)>0;r=r.upper??void 0}return!1}function he(e,t){let n=ee(e,t);return n?n.isValueReference!==!1:t.parent?.type==="VariableDeclarator"&&t.parent.init===t}function te(e){if(e?.type==="Identifier"&&e.name)return{root:e,segments:[e.name]};if(!e||!(e.type==="MemberExpression"||!!(e.object&&e.property))||e.computed===!0)return;let n=te(e.object),i=V(e.property);if(!(!n||!i))return{root:n.root,segments:[...n.segments,i]}}function Ae(e){return V(e.callee?.property)}function ne(e,t){return e?.properties?.find(n=>V(n.key)===t)}function R(e,t){return ne(e,t)!==void 0}function be(e){let t=ne(e,"metadata")?.value;return R(t,"source")}function re(e){return Ae(e)==="publish"}var Se={meta:{type:"problem",docs:{description:"Disallow imports that violate ark.config.json layer rules (same contract as arkgate-check)."},messages:{forbiddenImport:"Architecture: {{fromLayer}} must not import {{toLayer}} (ark.config.json). Specifier: {{specifier}}",forbiddenImportHeuristic:"Domain code must not import infrastructure, adapters, repositories, or database modules."},schema:[]},create(e){let t=I(e),n=Q(t),i=n?X(n):null,r=n?u.dirname(n):null,o=s=>{let a=E(s.source);if(a&&i&&r&&t){let f=u.isAbsolute(t)?t:u.resolve(t),g=u.relative(r,f).split(u.sep).join("/"),l=S(g,i.layers);if(!l)return;let c=ye(f,a);if(!c)return;let d=u.relative(r,c).split(u.sep).join("/");if(d.startsWith(".."))return;let p=S(d,i.layers);if(!p)return;U(i.rules,l,p,{fromPath:g,toPath:d,layers:i.layers})&&C(e,s,"forbiddenImport",{ruleId:"LAYER_IMPORT_VIOLATION",file:g,fromLayer:l,toLayer:p,target:d,...s.importKind==="type"?{typeOnly:!0}:{},message:`${l} must not import ${p}.`},{fromLayer:l,toLayer:p,specifier:a});return}};return{ImportDeclaration:o,ExportNamedDeclaration:o,ExportAllDeclaration:o}}},ke={meta:{type:"problem",docs:{description:"Require event bus publish calls to use registered intent creators instead of raw event objects or intent strings."},messages:{rawPublish:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts."},schema:[]},create(e){return{CallExpression(t){let n=t.arguments?.[0],i=E(n),r=$({publishCall:re(t),rawIntentName:i,objectHasIntent:R(n,"intent"),arkPublishCandidate:!1,hasSource:!0});if(r.some(o=>o.ruleId==="RAW_EVENT_PUBLISH")){let o=r.find(s=>s.ruleId==="RAW_EVENT_PUBLISH");C(e,t,"rawPublish",{...o,file:I(e)})}}}}},Re={meta:{type:"problem",docs:{description:"Require event bus publish calls to include source metadata."},messages:{missingSource:"Strict Ark publish calls must include metadata.source."},schema:[]},create(e){return{CallExpression(t){let n=t.arguments?.[0],i=t.arguments?.[2],o=$({publishCall:re(t),rawIntentName:E(n),objectHasIntent:R(n,"intent"),arkPublishCandidate:!0,hasSource:be(n)||R(i,"source")}).find(s=>s.ruleId==="PUBLISH_MISSING_SOURCE");o&&C(e,t,"missingSource",{...o,file:I(e)})}}}},Ie={meta:{type:"problem",docs:{description:"Disallow ambient globals from the layer\u2019s forbiddenGlobals in ark.config.json (same purity surface as ark-check). Option `globals` explicitly overrides."},messages:{forbiddenGlobal:'Ambient global "{{name}}" is forbidden in {{layer}} (ark.config.json); inject the capability through a port instead.',forbiddenGlobalDefault:'Ambient global "{{name}}" is forbidden here; inject the capability through a port instead.'},schema:[{type:"object",properties:{globals:{type:"array",items:{type:"string"}}},additionalProperties:!1}]},create(e){let t=I(e),n=e.options?.[0],i=Q(t),r=i?X(i):null,o=i?u.dirname(i):null,s=null,a="this layer";if(n?.globals)s=new Set(n.globals);else if(r&&o&&t){let l=u.isAbsolute(t)?t:u.resolve(t),c=u.relative(o,l).split(u.sep).join("/"),d=r.layers?.find(p=>p.name===S(c,r.layers));d?.forbiddenGlobals?.length?(s=new Set(d.forbiddenGlobals),a=d.name):s=null}if(!s)return{};let f=typeof F(e)?.getScope=="function",g=(l,c)=>{let d=u.isAbsolute(t)?t:u.resolve(t),p=o?u.relative(o,d).split(u.sep).join("/"):t;C(e,l,r?"forbiddenGlobal":"forbiddenGlobalDefault",{ruleId:"FORBIDDEN_GLOBAL",file:p,fromLayer:a,target:c,message:`${a} must not use the ambient global "${c}".`},{name:c,layer:a})};return{MemberExpression(l){if(l.parent?.type==="MemberExpression"&&l.parent.object===l)return;let c=te(l);if(!c||Z(e,c.root,c.segments[0]))return;let d=c.segments[0]==="globalThis",p=d?c.segments.slice(1):c.segments,N;for(let x=p.length;x>=(d?1:2);x-=1){let M=p.slice(0,x).join(".");if(s.has(M)){N=M;break}}N?g(l,N):!f&&s.has(c.segments[0])&&g(l,c.segments[0])},CallExpression(l){if(f)return;let c=l.callee?.type==="Identifier"?l.callee.name:void 0;c&&s.has(c)&&g(l,c)},NewExpression(l){if(f)return;let c=l.callee?.type==="Identifier"?l.callee.name:void 0;c&&s.has(c)&&g(l,c)},Identifier(l){!f||!l.name||!s.has(l.name)||!he(e,l)||Z(e,l,l.name)||g(l,l.name)}}}},Ce={"no-domain-infra-imports":Se,"no-raw-event-publish":ke,"require-publish-source":Re,"no-forbidden-globals":Ie},j={rules:Ce};j.configs={recommended:{plugins:{ark:j},rules:{"ark/no-domain-infra-imports":"error","ark/no-raw-event-publish":"error","ark/require-publish-source":"error","ark/no-forbidden-globals":"error"}}};var Ve=j;export{Ve as default,Q as findConfigPath,w as globToRegExp,U as isEdgeDenied,S as layerForRelativePath,X as loadArkConfig,Se as noDomainInfraImports,Ie as noForbiddenGlobals,ke as noRawEventPublish,H as patternSpecificity,j as plugin,Re as requirePublishSource,ye as resolveRelativeImport};
package/dist/index.cjs CHANGED
@@ -1,6 +1,7 @@
1
- "use strict";var ge=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var it=Object.prototype.hasOwnProperty;var at=(e,t)=>{for(var n in t)ge(e,n,{get:t[n],enumerable:!0})},ot=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of rt(t))!it.call(e,i)&&i!==n&&ge(e,i,{get:()=>t[i],enumerable:!(r=nt(t,i))||r.enumerable});return e};var st=e=>ot(ge({},"__esModule",{value:!0}),e);var zt={};at(zt,{ANALYSIS_IR_SCHEMA_VERSION:()=>ae,ARK_ANALYSIS_RESULT_SCHEMA:()=>_e,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>$e,ARK_CONFIG_SCHEMA:()=>ne,ARK_CONFIG_SCHEMA_VERSION:()=>Be,POLICY_DELTA_SCHEMA_VERSION:()=>qe,analyzeArchitectureConvergence:()=>Y,analyzeChange:()=>Le,analyzePolicyDelta:()=>Ze,analyzeProject:()=>fe,classifyArkPolicyDelta:()=>ce,collectAnalysisConfigWarnings:()=>tt,collectForbiddenCapabilityUses:()=>V,createAICodeGate:()=>xe,createAdapterResult:()=>ve,createArchitectureProfile:()=>z,createArchitectureProfileFromArkConfig:()=>Se,createElevenLayerArkConfig:()=>ke,detectArchitectureCycles:()=>we,deterministicHash:()=>P,elevenLayerProfile:()=>K,evaluateArchitectureGraph:()=>Pe,explainViolation:()=>Xe,extractSemanticDependencies:()=>H,loadArkConfigContract:()=>B,loadContract:()=>de,parseArkConfigJson:()=>ie,policyDeltaAcknowledgementMatches:()=>le,preflightChange:()=>et,stableSerialize:()=>L,toAdapterDiagnostic:()=>Q,version:()=>Re});module.exports=st(zt);var Re="3.1.0";var $e="1.1";function E(e){return typeof e=="string"&&e.length>0?e:void 0}function Oe(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function ct(e,t,n){return e==="LAYER_IMPORT_VIOLATION"?t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, then preflight again.`:e==="FORBIDDEN_GLOBAL"?`Inject ${t.target??"the capability"} through a port, then preflight again.`:e==="CIRCULAR_DEPENDENCY"?"Extract the shared dependency into a third module, then preflight again.":e==="RAW_EVENT_PUBLISH"?"Publish through a registered intent creator, then run Ark again.":e==="PUBLISH_MISSING_SOURCE"?"Add metadata.source to the publish call, then run Ark again.":`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function Q(e,t="error"){let n=E(e.ruleId)??E(e.code)??"ARK_UNKNOWN",r=e.severity==="warning"?"warning":t,i={...E(e.target)?{target:E(e.target)}:{},...E(e.fromLayer)?{fromLayer:E(e.fromLayer)}:{},...E(e.toLayer)?{toLayer:E(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{}};return{ruleId:n,severity:r,message:E(e.message)??n,location:{file:E(e.file)??"<unknown>",line:Oe(e.line,1),column:Oe(e.column,1)},evidence:i,nextAction:E(e.nextAction)??ct(n,i,e)}}function ve(e){return{schemaVersion:"1.1",valid:e.valid,diagnostics:[...(e.violations??[]).map(t=>Q(t,"error")),...(e.warnings??[]).map(t=>Q(t,"warning"))]}}var _e={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@2/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","valid","diagnostics"],properties:{schemaVersion:{const:"1.1"},valid:{type:"boolean"},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"}}},nextAction:{type:"string",minLength:1}}}}}};var Ne=new Map;function Me(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function ye(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let i=e[n+1];if("*?{}[],".includes(i)||i==="\\"){t+="\\"+i,n+=1;continue}t+="/";continue}t+=r}return t}function lt(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}function F(e){let t=Ne.get(e);if(t)return t;let n=ye(e),r=lt(n),i="",a=0;for(let c=0;c<n.length;c+=1){let d=n[c];d==="\\"&&c+1<n.length?(i+=Me(n[c+1]),c+=1):d==="*"?n[c+1]==="*"?n[c+2]==="/"?(i+="(?:.*/)?",c+=2):(i+=".*",c+=1):i+="[^/]*":d==="?"?i+="[^/]":d==="{"&&r?(i+="(?:",a+=1):d==="}"&&r&&a>0?(i+=")",a-=1):d===","&&r&&a>0?i+="|":i+=Me(d)}let s=new RegExp(`^${i}$`);return Ne.set(e,s),s}function he(e){let t=ye(String(e)),r=t.split("*")[0].split("/").filter(Boolean).length,i=t.replace(/\*/g,"").length;return r*1e4+i}function X(e,t){let n=String(e).split(/[/\\]/).join("/"),r,i=-1;for(let a of t??[])if(!(a.exclude??[]).some(s=>F(s).test(n))){for(let s of a.patterns??[])if(F(s).test(n)){let c=he(s);c>i&&(i=c,r=a.name)}}return r}function De(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(i=>String(i).toLowerCase()));for(let i=0;i<n.length-1;i+=1)if(r.has(n[i].toLowerCase()))return`${n[i]}/${n[i+1]}`}function dt(e){let t=new Set;for(let n of e??[]){let i=ye(String(n)).split("/").filter(Boolean);for(let a=0;a<i.length;a+=1){let s=i[a];if((s==="**"||s==="*")&&a>0){let c=i[a-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}function pt(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(i=>typeof i=="string"&&i.length>0);let r=(n??[]).find(i=>i.name===t);return dt(r?.patterns)}function v(e,t,n,r){for(let i of e??[])if(!(i.from!==t||i.to!==n)&&i.allowed===!1){if(i.peerIsolation){let a=r?.fromPath,s=r?.toPath;if(!a||!s)continue;let c=pt(i,t,r?.layers);if(c.length===0)continue;let d=De(a,c),u=De(s,c);if(!d||!u)continue;if(d!==u)return i;continue}if(t!==n)return i}}var me={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."};function O(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function Ae(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&O(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:me.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:me.PUBLISH_MISSING_SOURCE}),t}function _(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function He(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function Te(e,t){if(e.isImportDeclaration(t)){let n=t.importClause;if(!n)return!1;if(n.isTypeOnly)return!0;let r=n.namedBindings;return!!(r&&e.isNamedImports(r)&&r.elements.length>0&&r.elements.every(i=>i.isTypeOnly))}if(e.isExportDeclaration(t)){if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}return!1}function Ve(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=i=>i===t.fileName?t:void 0,r.fileExists=i=>i===t.fileName,r.readFile=i=>i===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}function Ce(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function be(e,t,n,r){let i=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,a;try{a=i?t.getShorthandAssignmentValueSymbol(r.parent):Ce(t,r)}catch{a=void 0}return!!a?.declarations?.some(s=>s.getSourceFile().fileName===n.fileName)}function H(e,t){let n,r=[],i=(s,c,d,u=!1)=>r.push({specifier:d,kind:c,line:He(t,s),typeOnly:u,unresolved:d===void 0,node:s}),a=s=>{if(e.isImportDeclaration(s))i(s,"import",_(e,s.moduleSpecifier),Te(e,s));else if(e.isExportDeclaration(s)&&s.moduleSpecifier)i(s,"export",_(e,s.moduleSpecifier),Te(e,s));else if(e.isImportEqualsDeclaration(s)&&e.isExternalModuleReference(s.moduleReference))i(s,"require",_(e,s.moduleReference.expression));else if(e.isCallExpression(s)){let c=s.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(s.expression)&&s.expression.text==="require"&&!be(e,n??(n=Ve(e,t)),t,s.expression);(c||u)&&i(s,u?"require":"dynamic-import",_(e,s.arguments[0]))}e.forEachChild(s,a)};return a(t),r}function ft(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let i=_(e,r.argumentExpression);if(i===void 0)return;n.unshift(i)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}function ut(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}function Fe(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let i=n.slice(0,r).join(".");if(e.has(i))return i}}function V(e,t,n){if(n.length===0)return[];let r=new Set(n),i=Ve(e,t),a=new Map,s=new Set;for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations)e.isIdentifier(l.name)&&s.add(l.name.text);let c=o=>{let l=ft(e,o);if(!l)return;let f=Ce(i,l.root),y=f?a.get(f):void 0;return y?[...y,...l.segments.slice(1)]:be(e,i,t,l.root)||s.has(l.root.text)?void 0:l.segments};for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations){if(!l.initializer||!e.isIdentifier(l.name))continue;let f=c(l.initializer),y=Ce(i,l.name);!f||!y||a.set(y,f)}let d=[],u=new Set,g=(o,l)=>{let f=He(t,l),y=`${o}:${l.getStart(t)}`;u.has(y)||(u.add(y),d.push({name:o,line:f,node:l}))},h=o=>{let l=o.parent&&(e.isPropertyAccessExpression(o.parent)||e.isElementAccessExpression(o.parent))&&o.parent.expression===o;if((e.isPropertyAccessExpression(o)||e.isElementAccessExpression(o))&&!l){let f=c(o),y=f?Fe(r,f):void 0;y&&g(y,o)}else e.isIdentifier(o)&&r.has(o.text)&&ut(e,o)&&!be(e,i,t,o)&&g(o.text,o);if(e.isVariableDeclaration(o)&&e.isObjectBindingPattern(o.name)&&o.initializer){let f=c(o.initializer);if(f)for(let y of o.name.elements){if(!e.isIdentifier(y.name))continue;let k=y.propertyName?_(e,y.propertyName)??y.propertyName.text:y.name.text,b=Fe(r,[...f,k]);b&&g(b,o.initializer)}}e.forEachChild(o,h)};return h(t),d}function A(e,t,n){return{ruleId:e,code:e,message:t,...n}}function N(e,t){return e.slice(0,t).split(`
2
- `).length}function gt(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,r;for(;(r=n.exec(e))!==null;)t.push({value:r[1],index:r.index});return t}function yt(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let i;for(;(i=r.re.exec(e))!==null;){let a=i.index+i[0].indexOf(i[1]),s=i[0],c=r.kind==="import"&&/\bimport\s+type\b/.test(s)||r.kind==="export"&&/\bexport\s+type\b/.test(s);t.push({value:i[1],index:a,kind:r.kind,typeOnly:c})}}return t.sort((r,i)=>r.index-i.index)}function ht(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],i=a=>{e.isStringLiteralLike(a)&&r.push({value:a.text,index:a.getStart(n)}),e.forEachChild(a,i)};return i(n),r}function mt(e){let t=e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return["adapter","adapters","infra","infrastructure","persistence","repository","repositories","integration","database","db"].some(n=>t.includes(n))}function At(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function Ct(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function G(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function bt(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function je(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:bt(e,r.name)===n)}function U(e,t,n){return je(e,t,n)!==void 0}function j(e,t,n){let r=je(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}function xt(e,t){let n=j(e,t,"metadata");return U(e,n,"source")}function Ge(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Ge(e,t.name):!1:!1}function It(e,t){if(!e.isCallExpression(t))return!1;let n=t.expression;return e.isPropertyAccessExpression(n)?n.name.text==="publish":e.isIdentifier(n)&&n.text==="publish"}function St(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=G(e,n);return r!==void 0&&O(r)||U(e,n,"intent")||Ge(e,n)}function kt(e,t){if(!e.isCallExpression(t))return!1;let[n,r,i]=t.arguments;return xt(e,n)||U(e,r,"source")||U(e,i,"source")}function Et(e,t){if(!e.isCallExpression(t))return;let[n,r,i]=t.arguments,a=j(e,n,"metadata");return G(e,j(e,a,"source"))??G(e,j(e,r,"source"))??G(e,j(e,i,"source"))}function Lt(e,t,n,r){let i=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),a=n,s=a?.filePath,c=a?.layer,d=[],u=h=>i.getLineAndCharacterOfPosition(h.getStart(i)).line+1,g=h=>{if(It(e,h)){let o=h.arguments[0],l=G(e,o);for(let y of Ae({publishCall:!0,rawIntentName:l,objectHasIntent:U(e,o,"intent"),arkPublishCandidate:St(e,h),hasSource:kt(e,h)}))d.push(A(y.ruleId,y.message,{line:u(h),filePath:s}));let f=Et(e,h);if(r&&c&&f&&O(f)){let y=r.resolveLayer(f);y&&y!==c&&d.push(A("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${f}" resolves to ${y}, but the target file is classified as ${c}.`,{line:u(h),filePath:s,target:f,fromLayer:c,toLayer:y}))}}e.forEachChild(h,g)};return g(i),d}function xe(e={}){let t=new Set((e.intents||[]).map(a=>typeof a=="string"?a:a.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),i=e.enforceIntentAllowlist??t.size>0;return{validate(a,s){let c=[],d=s,u=d?.filePath,g=d?.layer,h=e.typescript,o=h?h.createSourceFile(u??"generated.ts",a,h.ScriptTarget.Latest,!0):void 0,l=o?H(e.typescript,o):void 0,f=l?l.filter(p=>p.specifier!==void 0).map(p=>({value:p.specifier,index:p.node.getStart(o),kind:p.kind,typeOnly:p.typeOnly})):yt(a),y=e.typescript?ht(e.typescript,a):gt(a);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let p of l?.filter(({unresolved:m})=>m)??[]){let m=p.kind==="require";c.push(A(m?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${m?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:p.line,filePath:u}))}let k=g!==void 0&&(r.has(g)||Ct(g)),b=g!==void 0?` If "${g}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let p of n)if(p instanceof RegExp){p.lastIndex=0;let m=p.exec(a);p.lastIndex=0,m&&c.push(A("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${p}`,{line:m.index===void 0?void 0:N(a,m.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+b}))}else a.includes(p)&&c.push(A("FORBIDDEN_SUBSTRING",`Forbidden substring: ${p}`,{line:N(a,a.indexOf(p)),filePath:u}));for(let p of f){let m=e.resolveImportTarget?.(p.value,u)??(e.resolveImportLayer?{layer:e.resolveImportLayer(p.value,u)}:void 0),R=typeof u=="string"?e.resolveImportTarget?.(u)??(e.resolveImportLayer?{layer:g,relPath:void 0}:void 0):void 0,$=m?.layer;if($&&g){let Z=v(e.architectureProfile?.rules,g,$,{fromPath:R?.relPath,toPath:m?.relPath,layers:e.architectureLayers});if(Z){if(p.typeOnly&&!Z.peerIsolation)continue;let ue=!!Z.peerIsolation;c.push(A("LAYER_IMPORT_VIOLATION",Z.message??(ue?`Layer "${g}" must not import across slices into "${$}".`:`Layer "${g}" must not import "${$}".`),{line:N(a,p.index),source:p.value,target:p.value,filePath:u,fromLayer:g,toLayer:$,suggestion:ue?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:p.kind,peerIsolation:ue,...p.typeOnly?{typeOnly:!0}:{}}}));continue}if($!==g)continue}k||p.typeOnly||!mt(p.value)&&!At(p.value)||c.push(A("FORBIDDEN_IMPORT",`Forbidden ${p.kind} target: "${p.value}".`,{line:N(a,p.index),source:p.value,target:p.value,filePath:u,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+b,details:{importKind:p.kind}}))}if(e.policies)for(let p of e.policies){let m=p.check({source:a,context:s});if(m!==!0)if(Array.isArray(m))for(let R of m)c.push(A("POLICY_VIOLATION",R.message,{filePath:u,suggestion:`Fix violation of policy "${p.name}".`}));else m===!1?c.push(A("POLICY_VIOLATION",`Policy ${p.name} failed on generated code`)):c.push(A("POLICY_VIOLATION",m.message))}if(i&&t.size>0)for(let p of y)O(p.value)&&!t.has(p.value)&&c.push(A("UNKNOWN_INTENT",`Unknown intent reference: "${p.value}"`,{line:N(a,p.index),filePath:u,target:p.value,suggestion:`Register intent "${p.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&g)for(let p of y){if(!O(p.value))continue;let m=e.architectureProfile.resolveLayer(p.value);if(!m)continue;let R=v(e.architectureProfile.rules,g,m);R&&c.push(A("LAYER_REFERENCE_VIOLATION",R.message??`Layer "${g}" must not reference "${m}" through "${p.value}".`,{line:N(a,p.index),filePath:u,target:p.value,fromLayer:g,toLayer:m,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:R}}))}if(e.extensions)for(let p of e.extensions)try{let m=p.analyze(a,s);c.push(...m)}catch(m){c.push(A("EXTENSION_ERROR",`Extension "${p.name}" failed: ${m instanceof Error?m.message:String(m)}`))}if(e.typescript&&o&&g&&e.forbiddenGlobals?.[g]?.length)try{c.push(...V(e.typescript,o,e.forbiddenGlobals[g]).map(p=>A("FORBIDDEN_GLOBAL",`${g} must not use the ambient global "${p.name}".`,{line:p.line,filePath:u,target:p.name,fromLayer:g,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})))}catch(p){c.push(A("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${p instanceof Error?p.message:String(p)}`))}if(e.typescript)try{c.push(...Lt(e.typescript,a,s,e.architectureProfile))}catch(p){c.push(A("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${p instanceof Error?p.message:String(p)}`))}return{valid:c.length===0,violations:c}}}}var Be="1.0",te="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Ue=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],wt=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Pt(){let e=[];for(let t of Ue)for(let n of Ue)t===n||wt.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var re=Pt();var w={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},ne={$schema:"https://json-schema.org/draft/2020-12/schema",$id:te,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:te,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.0",default:"1.0"},name:{type:"string",minLength:1},include:{...w,minItems:1,default:["src"]},exclude:{...w,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:re,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...w,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...w,minItems:1},exclude:w,intentPrefixes:w,description:{type:"string",minLength:1},forbiddenGlobals:w,mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...w,minItems:1}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}}}},D=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
3
- ${n.map(r=>`- ${r.path}: ${r.message}`).join(`
4
- `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Ke(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ie(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function M(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Rt(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function ee(e,t,n,r,i){if(t.$ref){let a=Rt(t.$ref,r);if(!a){i.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}ee(e,a,n,r,i);return}if(t.const!==void 0&&!Object.is(e,t.const)){i.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(a=>Object.is(a,e))){i.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Ke(e)){i.push({path:n,message:`must be an object; received ${M(e)}`});return}let a=t.properties??{};for(let s of t.required??[])e[s]===void 0&&i.push({path:Ie(n,s),message:"is required"});if(t.additionalProperties===!1)for(let s of Object.keys(e))s in a||i.push({path:Ie(n,s),message:"unknown field"});for(let[s,c]of Object.entries(a))e[s]!==void 0&&ee(e[s],c,Ie(n,s),r,i);return}if(t.type==="array"){if(!Array.isArray(e)){i.push({path:n,message:`must be an array; received ${M(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&i.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let a=e.map(s=>JSON.stringify(s));new Set(a).size!==a.length&&i.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((a,s)=>ee(a,t.items,`${n}[${s}]`,r,i));return}if(t.type==="string"){if(typeof e!="string"){i.push({path:n,message:`must be a string; received ${M(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&i.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&i.push({path:n,message:`must be a boolean; received ${M(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){i.push({path:n,message:`must be an integer; received ${M(e)}`});return}t.minimum!==void 0&&e<t.minimum&&i.push({path:n,message:`must be at least ${t.minimum}`})}}function Ot(e){return{...e,$schema:e.$schema===void 0?te:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.0":e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?re.map(t=>({...t})):e.rules}}function $t(e,t="ark.config.json"){if(!Ke(e))throw new D(t,[{path:"$",message:`must be an object; received ${M(e)}`}]);let n=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new D(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:Ot(e),migratedFrom:n}}function B(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=$t(e,t),i=[];if(ee(n,ne,"$",ne,i),i.length>0)throw new D(t,i);return{config:n,migratedFrom:r}}function ie(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new D(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return B(n,t)}function ze(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:te,schemaVersion:"1.0"};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}function vt(e){return e.endsWith(".")?e:`${e}.`}function _t(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(i=>i.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(i=>i.length)):0)-n}function z(e){let t=e.layers.map(i=>({...i,prefixes:i.prefixes.map(vt)})),n=[...t].sort(_t),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(i){return t.find(a=>a.match?.(i))?.name??n.find(a=>a.prefixes.some(s=>i.startsWith(s)))?.name}}}function Se(e,t={}){return z({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:r+1})),rules:e.rules??[]})}var Nt=[{name:"DomainModel",prefixes:["Domain"],description:"Rich domain model, business rules, and domain events.",order:1},{name:"ApplicationOrchestration",prefixes:["Application"],description:"Use cases and command orchestration.",order:2},{name:"PersistenceAdapters",prefixes:["Adapter.Persistence","Adapter.Repository"],description:"Database, repository, and storage adapters.",order:3},{name:"IntegrationAdapters",prefixes:["Adapter.Integration","Adapter.External"],description:"External systems, APIs, and integration adapters.",order:4},{name:"WorkflowSagaEngine",prefixes:["Workflow"],description:"Sagas, workflows, and long-running processes.",order:5},{name:"BackgroundJobsScheduling",prefixes:["Job"],description:"Background jobs, scheduled work, and async processors.",order:6},{name:"PresentationAdapters",prefixes:["Presentation","Adapter.Presentation","Adapter.Api"],description:"API, UI, controller, and presentation adapters.",order:7},{name:"ReportingReadModels",prefixes:["Reporting"],description:"Read models, projections, and reporting surfaces.",order:8},{name:"ExtensibilityMetadata",prefixes:["Metadata"],description:"Metadata, extensions, and schema contracts.",order:9},{name:"SecurityAuditObservability",prefixes:["Security","Audit","Observability"],description:"Security, audit, and observability concerns.",order:10},{name:"Kernel",prefixes:["Kernel"],description:"Ark-owned governance and kernel signals.",order:11}],K=z({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Nt,rules:re.map(e=>({...e}))}),Mt={DomainModel:["domain"],ApplicationOrchestration:["application","app"],PersistenceAdapters:["adapters/persistence","adapters/repository","repositories","infra/persistence"],IntegrationAdapters:["adapters/integration","adapters/external","integrations"],WorkflowSagaEngine:["workflows","sagas"],BackgroundJobsScheduling:["jobs","schedules"],PresentationAdapters:["presentation","adapters/presentation","adapters/api"],ReportingReadModels:["reporting","read-models","projections"],ExtensibilityMetadata:["metadata","extensions"],SecurityAuditObservability:["security","audit","observability"],Kernel:["kernel"]};function ke(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return ze({include:e.include??[t],layers:K.layers.map(i=>({name:i.name,patterns:(Mt[i.name]??[i.name]).map(a=>`${r}${a}/**`),intentPrefixes:i.prefixes,optional:n})),rules:[...K.rules]})}var ae="1.0";function P(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}function L(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(L).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${L(t[n])}`).join(",")}}`}var qe="1.0";function C(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}function I(e){return[...new Set(e??[])].sort()}function T(e,t,n,r,i){let a=I(n),s=I(r),c=new Set(a),d=new Set(s),u=s.filter(h=>!c.has(h)),g=a.filter(h=>!d.has(h));u.length===0&&g.length===0||(u.length>0&&C(e,{kind:"added",path:t,classification:i.added,message:i.addedMessage,before:a,after:s}),g.length>0&&C(e,{kind:"removed",path:t,classification:i.removed,message:i.removedMessage,before:a,after:s}))}function oe(e,t,n,r,i,a,s){if(n===r)return;C(e,{kind:r?"enabled":"disabled",path:t,classification:r?i:i==="strengthening"?"weakening":"strengthening",message:r?a:s,before:n,after:r})}function se(e,t){let n=new Map,r=new Set;for(let i of e){let a=t(i);n.has(a)?r.add(a):n.set(a,i)}return{values:n,duplicates:[...r].sort()}}function Dt(e,t,n){let r=se(t,a=>a.name),i=se(n,a=>a.name);(r.duplicates.length>0||i.duplicates.length>0)&&C(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:i.duplicates});for(let a of[...new Set([...r.values.keys(),...i.values.keys()])].sort()){let s=r.values.get(a),c=i.values.get(a),d=`$.layers[${a}]`;if(!s&&c){C(e,{kind:"layer-added",path:d,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:c});continue}if(s&&!c){C(e,{kind:"layer-removed",path:d,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:s});continue}!s||!c||(T(e,`${d}.patterns`,s.patterns,c.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),T(e,`${d}.exclude`,s.exclude,c.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."}),T(e,`${d}.forbiddenGlobals`,s.forbiddenGlobals,c.forbiddenGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),I(s.intentPrefixes).join("\0")!==I(c.intentPrefixes).join("\0")&&C(e,{kind:"intent-prefixes-changed",path:`${d}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:I(s.intentPrefixes),after:I(c.intentPrefixes)}),oe(e,`${d}.mayImportInfrastructure`,s.mayImportInfrastructure===!0,c.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),oe(e,`${d}.optional`,s.optional===!0,c.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active."))}}function Tt(e,t,n){let r=s=>`${s.from}->${s.to}`,i=se(t,r),a=se(n,r);(i.duplicates.length>0||a.duplicates.length>0)&&C(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:i.duplicates,after:a.duplicates});for(let s of[...new Set([...i.values.keys(),...a.values.keys()])].sort()){let c=i.values.get(s),d=a.values.get(s),u=`$.rules[${s}]`;if(!c&&d){d.allowed===!1&&C(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:d});continue}if(c&&!d){c.allowed===!1&&C(e,{kind:"deny-removed",path:u,classification:"weakening",message:"A denied dependency edge was removed.",before:c});continue}if(!c||!d)continue;c.allowed!==d.allowed&&C(e,{kind:d.allowed?"deny-disabled":"deny-enabled",path:`${u}.allowed`,classification:d.allowed?"weakening":"strengthening",message:d.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:c.allowed,after:d.allowed});let g=c.peerIsolation===!0,h=d.peerIsolation===!0;if(g!==h){let o=c.from===c.to&&d.from===d.to;C(e,{kind:h?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:o?h?"strengthening":"weakening":"judgment-required",message:o?h?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:g,after:h})}I(c.sliceFolders).join("\0")!==I(d.sliceFolders).join("\0")&&C(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:I(c.sliceFolders),after:I(d.sliceFolders)})}}function Ft(e,t,n){let r=t.safety??{},i=n.safety??{};for(let a of["maxTsSuppressions","maxAnyCasts"]){let s=r[a]??0,c=i[a]??0;s!==c&&C(e,{kind:c>s?"threshold-raised":"threshold-lowered",path:`$.safety.${a}`,classification:c>s?"weakening":"strengthening",message:c>s?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:s,after:c})}for(let a of["allowInMemory","allowDisabledPeerIsolation"])oe(e,`$.safety.${a}`,r[a]===!0,i[a]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function Ht(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}function ce(e,t){let n=[];T(n,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),T(n,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),T(n,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),oe(n,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let r={off:0,soft:1,"framework-soft":1,strict:2},i=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(i!==a){let s=r[a]===r[i]?"judgment-required":r[a]>r[i]?"strengthening":"weakening";C(n,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:s,message:"The cycle enforcement level changed.",before:i,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&C(n,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),Dt(n,e.layers,t.layers),Tt(n,e.rules,t.rules),Ft(n,e,t),n.sort((s,c)=>s.path.localeCompare(c.path)||s.id.localeCompare(c.id)),{schemaVersion:"1.0",classification:Ht(n),findings:n}}function le(e,t){if(!e||e.schemaVersion!=="1.0"||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(i=>typeof i!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=I(e.findingIds),r=I(t.findingIds);return n.length===r.length&&n.every((i,a)=>i===r[a])}function S(e){return`${e.from}->${e.to}`}function q(e,t,n,r="dependency"){return{id:`${e}:${r}:${S(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${S(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${S(t)}, then preflight again.`}:e==="unplanned"?{nextAction:`Remove the unplanned dependency ${S(t)} from the candidate, then preflight again.`}:{}}}function Y(e){let t=[],n=new Map(e.changeMap.map.files.map(o=>[o.path,o])),r=new Map(e.changes.map(o=>[o.path,o])),i=new Map(e.changeMap.map.dependencies.map(o=>[S(o),o])),a=new Map(e.baseDependencies.map(o=>[S(o),o])),s=new Map(e.candidateDependencies.map(o=>[S(o),o]));for(let o of[...n.values()].sort((l,f)=>l.path.localeCompare(f.path))){let l=r.get(o.path);l?l.operation!==o.operation?t.push({id:`contradictory:file:${o.path}`,classification:"contradictory",subject:"file",path:o.path,expectedOperation:o.operation,actualOperation:l.operation,message:`${o.path} was planned as ${o.operation} but the actual operation is ${l.operation}.`,nextAction:`Change ${o.path} to the planned ${o.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${o.path}`,classification:"satisfied",subject:"file",path:o.path,expectedOperation:o.operation,actualOperation:l.operation,message:`${o.path} matches the planned ${o.operation} operation.`}):t.push({id:`missing:file:${o.path}`,classification:"missing",subject:"file",path:o.path,expectedOperation:o.operation,message:`${o.path} was planned as ${o.operation} but is absent from the actual change.`,nextAction:`${o.operation[0].toUpperCase()}${o.operation.slice(1)} ${o.path} in the complete change set, then preflight again.`})}for(let o of[...r.values()].sort((l,f)=>l.path.localeCompare(f.path)))n.has(o.path)||t.push({id:`unplanned:file:${o.path}`,classification:"unplanned",subject:"file",path:o.path,actualOperation:o.operation,message:`${o.path} has an unplanned ${o.operation} operation.`,nextAction:`Remove ${o.path} from the change set, then preflight again.`});let c=new Set;for(let o of[...i.values()].sort((l,f)=>S(l).localeCompare(S(f)))){if(s.has(S(o))){t.push(q("satisfied",o,`${o.from} -> ${o.to} exists in the candidate architecture.`));continue}let l={from:o.to,to:o.from};s.has(S(l))?(c.add(S(l)),t.push(q("contradictory",o,`${o.from} -> ${o.to} was planned, but the candidate contains the reverse edge.`))):t.push(q("missing",o,`${o.from} -> ${o.to} is absent from the candidate architecture.`))}let d=new Set([...n.keys(),...r.keys()]);for(let[o,l]of[...s].sort(([f],[y])=>f.localeCompare(y)))a.has(o)||i.has(o)||c.has(o)||!d.has(l.from)&&!d.has(l.to)||t.push({...q("unplanned",l,`${l.from} -> ${l.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(o=>o.operation==="delete").map(o=>o.path));for(let[o,l]of[...a].sort(([f],[y])=>f.localeCompare(y)))s.has(o)||u.has(l.from)||u.has(l.to)||!d.has(l.from)&&!d.has(l.to)||t.push({...q("unplanned",l,`${l.from} -> ${l.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let g={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((o,l)=>g[o.classification]-g[l.classification]||(o.subject===l.subject?0:o.subject==="file"?-1:1)||o.id.localeCompare(l.id));let h={satisfied:t.filter(o=>o.classification==="satisfied").length,missing:t.filter(o=>o.classification==="missing").length,contradictory:t.filter(o=>o.classification==="contradictory").length,unplanned:t.filter(o=>o.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:h.missing===0&&h.contradictory===0&&h.unplanned===0,behavioralCompletion:"not-evaluated",summary:h,findings:t}}function Ye(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":e.peerIsolation?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, then preflight again.`;case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}function de(e,t){let n=typeof e=="string"?ie(e,t):B(e,t);return{...n,policyHash:P(L(n.config))}}function Ze(e){let t=de(e.baseConfig,e.baseSource??"base ark.config.json"),n=de(e.candidateConfig,e.candidateSource??"candidate ark.config.json"),r=ce(t.config,n.config),i=r.findings.filter(c=>c.classification==="weakening"||c.classification==="judgment-required").map(c=>c.id).sort(),a=i.length>0,s=a&&le(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:i});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:i,requiresAcknowledgement:a,acknowledged:s,valid:!a||s}}function J(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}function We(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function Ee(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function pe(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,i="";for(t+=1;t<e.length;t+=1){let a=e[t];if(a===n)return{value:i,offset:r,excerpt:e.slice(r,t+1)};a==="\\"&&t+1<e.length?(i+=e[t+1],t+=1):i+=a}}function W(e,t,n){return e.startsWith(t,n)&&!We(e[n-1])&&!We(e[n+t.length])}function Vt(e,t){return t=Ee(e,t+6),e[t]==="("?pe(e,Ee(e,t+1)):Qe(e,t,!0)}function jt(e,t){return Qe(e,t+6,!1)}function Qe(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(W(e,"from",t))return pe(e,Ee(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return pe(e,t);if(t>0&&(W(e,"import",t)||W(e,"export",t)))return}}function Gt(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
5
- `,n+2),n<0)break;continue}if(r==="/"&&e[n+1]==="*"){let a=e.indexOf("*/",n+2);if(a<0)break;n=a+1;continue}if(r==="'"||r==='"'||r==="`"){let a=pe(e,n);a&&(n=a.offset+a.excerpt.length-1);continue}let i=W(e,"import",n)?Vt(e,n):W(e,"export",n)?jt(e,n):void 0;i&&t.push(i)}return t}function Ut(e,t){let n=[];for(let r of Gt(e.content)){let i=r.value;if(!i.startsWith("."))continue;let a=e.content.slice(0,r.offset).split(`
6
- `).length,s={kind:"import",file:e.path,line:a,excerpt:r.excerpt},c=Bt(e.path,i,t);n.push({from:e.path,specifier:i,to:c?.path??null,resolution:c?"resolved":"unresolved",fromLayer:e.layer,toLayer:c?.layer??null,evidence:s})}return n}function Bt(e,t,n){let r=e.split("/");r.pop();for(let a of t.split("/"))a==="."||a===""||(a===".."?r.pop():r.push(a));let i=r.join("/");for(let a of[i,`${i}.ts`,`${i}.tsx`,`${i}.mts`,`${i}.cts`,`${i}/index.ts`,`${i}/index.tsx`]){let s=n.get(a);if(s)return s}}function Kt(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let i=v(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});i&&n.push({ruleId:`layer-dependency:${i.from}->${i.to}`,message:i.message??`${i.from} must not depend on ${i.to}.`,edge:r,evidence:r.evidence})}return n}function fe(e){let t=e.files.map(s=>{let c=J(s.path);return{path:c,content:s.content,contentHash:P(s.content),layer:X(c,e.contract.config.layers)??null}}).sort((s,c)=>s.path.localeCompare(c.path)),n=new Map(t.map(s=>[s.path,s])),r=t.flatMap(s=>Ut(s,n)),i=[],a=Kt(r,e.contract.config);return{ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:P(L(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(s=>s.name),edges:r,capabilityUses:i,violations:a}}}function Le(e){let t=new Map(e.files.map(n=>[J(n.path),n]));for(let n of e.changes){let r=J(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return fe({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function Xe(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}function we(e){let t=0,n=new Map,r=new Map,i=new Set,a=[],s=[],c=d=>{n.set(d,t),r.set(d,t),t+=1,a.push(d),i.add(d);for(let h of[...e.get(d)??[]].sort())e.has(h)&&(n.has(h)?i.has(h)&&r.set(d,Math.min(r.get(d)??0,n.get(h)??0)):(c(h),r.set(d,Math.min(r.get(d)??0,r.get(h)??0))));if(r.get(d)!==n.get(d))return;let u=[],g;do{if(g=a.pop(),g===void 0)break;i.delete(g),u.push(g)}while(g!==d);u.length>1&&s.push(u.sort())};for(let d of[...e.keys()].sort())n.has(d)||c(d);return s.sort((d,u)=>d[0].localeCompare(u[0])).map(d=>({ruleId:"CIRCULAR_DEPENDENCY",file:d[0],line:1,target:d.join(" \u2192 "),message:`Circular dependency among ${d.length} files: ${d.join(" \u2192 ")} \u2192 ${d[0]}.`,cycleKind:"value"}))}function Pe(e){let t=e.contentViolations.map(a=>({...a})),n=(e.warnings??[]).map(a=>({...a})),r=new Map(e.files.map(a=>[a,new Set]));for(let a of e.edges){if(a.to&&a.to!==a.from&&!a.typeOnly&&r.has(a.from)&&r.get(a.from)?.add(a.to),!a.to||!a.toLayer)continue;let s=v(e.rules,a.fromLayer,a.toLayer,{fromPath:a.from,toPath:a.to,layers:e.config.layers});if(!s)continue;let c=!!s.peerIsolation;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:a.from,line:a.line,fromLayer:a.fromLayer,toLayer:a.toLayer,target:a.to,...a.typeOnly?{typeOnly:!0}:{},...a.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...a.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...a.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&a.portProofEligible?{portProofEligible:!0}:{},...a.kind?{edgeKind:a.kind}:{},...c?{peerIsolation:!0}:{},message:s.message??(c?`${a.fromLayer} must not ${a.kind} another slice of ${a.toLayer} (${a.from} \u2192 ${a.to}). Extract shared code or use events/ports across slices.`:`${a.fromLayer} must not ${a.kind} ${a.toLayer}.`)})}let i=String(e.config.cyclePolicy??"strict").toLowerCase();if(i!=="off"){let a=we(r);i==="soft"||i==="framework-soft"?n.push(...a.map(s=>({...s,message:`${s.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...a)}return{violations:t,warnings:n,safety:e.safety}}function Je(e){return P(L(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function et(e){let t=fe(e),n=new Map(t.ir.files.map(o=>[o.path,o])),r=[],i=new Set,a=[];for(let o of e.changes){let l=o.path.replace(/\\/g,"/"),f=J(o.path);if(!f||f===".."||f.startsWith("../")||l.startsWith("/")||/^[A-Za-z]:\//.test(l)||l.includes("\0")){a.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(i.has(f)){a.push({ruleId:"DUPLICATE_CHANGE_PATH",file:f,line:1,message:`The atomic change set contains more than one operation for ${f}.`});continue}i.add(f),"delete"in o&&o.delete&&!n.has(f)&&a.push({ruleId:"DELETE_TARGET_MISSING",file:f,line:1,message:`Cannot delete ${f} because it is not present in the supplied base tree.`}),r.push("delete"in o&&o.delete?{path:f,delete:!0}:{path:f,content:"content"in o?o.content:""})}e.changes.length===0&&a.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let s=Le({...e,changes:r}),c=new Map(s.ir.files.map(o=>[o.path,o])),d=Pe({config:e.contract.config,rules:e.contract.config.rules,files:s.ir.files.map(o=>o.path),contentViolations:[],edges:s.ir.edges.filter(o=>!!o.fromLayer).map(o=>({from:o.from,fromLayer:o.fromLayer,...o.to?{to:o.to}:{},...o.toLayer?{toLayer:o.toLayer}:{},line:o.evidence.line,kind:"import"}))}),u=r.map(o=>{let l=J(o.path),f=n.get(l),y=c.get(l);return{path:l,operation:"delete"in o&&o.delete?"delete":f?"update":"create",...f?{beforeContentHash:f.contentHash}:{},...y?{candidateContentHash:y.contentHash}:{}}}).sort((o,l)=>o.path.localeCompare(l.path)),g=[...a,...d.violations].map(o=>({...o,nextAction:Ye(o)})),h=e.changeMap?Y({changeMap:e.changeMap,changes:u,baseDependencies:t.ir.edges.flatMap(o=>o.to?[{from:o.from,to:o.to}]:[]),candidateDependencies:s.ir.edges.flatMap(o=>o.to?[{from:o.from,to:o.to}]:[])}):void 0;return{schemaVersion:"1.0",valid:g.length===0&&(h?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:s.ir.compilerOptionsHash,baseTreeHash:Je(t.ir.files),candidateTreeHash:Je(s.ir.files),...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...h?{convergence:h}:{},changes:u,violations:g,warnings:d.warnings}}function x(e,t,n={}){return{ruleId:e,message:t,...n}}function tt(e){let{config:t,rules:n,files:r,manifest:i}=e,a=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(l=>typeof l!="string"))&&a.push(x("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))a.push(x("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let l of["maxTsSuppressions","maxAnyCasts"]){let f=t.safety[l];f!==void 0&&(!Number.isInteger(f)||f<0)&&a.push(x("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${l} must be a non-negative integer.`))}let s=Array.isArray(t.layers)?t.layers:[],c=Array.isArray(i?.architecture?.layers)?i.architecture.layers:[],d=new Set([...s.map(l=>l.name).filter(Boolean),...c.map(l=>l.name).filter(l=>!!l)]);s.length===0&&a.push(x("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,g=new Set;for(let l of s){if(!l.name){a.push(x("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(l.name)&&g.add(l.name),u.add(l.name),l.forbiddenGlobals!==void 0&&(!Array.isArray(l.forbiddenGlobals)||l.forbiddenGlobals.some(y=>typeof y!="string"))&&a.push(x("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${l.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:l.name}));let f=Array.isArray(l.patterns)?l.patterns:[];if(f.length===0){a.push(x("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${l.name}" has no file patterns and will never classify files.`,{layer:l.name}));continue}for(let y of f){let k;try{k=F(y)}catch(b){a.push(x("CONFIG_INVALID_LAYER_PATTERN",`Layer "${l.name}" has an invalid pattern "${y}": ${b instanceof Error?b.message:String(b)}`,{layer:l.name,pattern:y}));continue}!r.some(b=>k.test(b))&&!l.optional&&a.push(x("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${l.name}" pattern "${y}" matched no included files.`,{layer:l.name,pattern:y,failsStrict:!1}))}}for(let l of g)a.push(x("CONFIG_DUPLICATE_LAYER",`Layer "${l}" is configured more than once.`,{layer:l}));if(d.size>0)for(let l of n??[])l.from&&!d.has(l.from)&&a.push(x("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${l.from}".`,{fromLayer:l.from,toLayer:l.to})),l.to&&!d.has(l.to)&&a.push(x("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${l.to}".`,{fromLayer:l.from,toLayer:l.to}));let h=new Set;if(s.length>1)for(let l of r){let f=-1,y=[];for(let k of s)for(let b of k.patterns??[]){if(!F(b).test(l))continue;let p=he(b);p>f?(f=p,y=[k.name]):p===f&&!y.includes(k.name)&&y.push(k.name)}y.length>1&&h.add([...y].sort().join(" + "))}h.size>0&&a.push(x("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...h].join(", ")}.`,{pairs:[...h]}));let o=r.filter(l=>!X(l,s));return o.length>0&&a.push(x("CONFIG_UNCLASSIFIED_FILES",`${o.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:o.length,samples:o.slice(0,5)})),a}0&&(module.exports={ANALYSIS_IR_SCHEMA_VERSION,ARK_ANALYSIS_RESULT_SCHEMA,ARK_ANALYSIS_RESULT_SCHEMA_VERSION,ARK_CONFIG_SCHEMA,ARK_CONFIG_SCHEMA_VERSION,POLICY_DELTA_SCHEMA_VERSION,analyzeArchitectureConvergence,analyzeChange,analyzePolicyDelta,analyzeProject,classifyArkPolicyDelta,collectAnalysisConfigWarnings,collectForbiddenCapabilityUses,createAICodeGate,createAdapterResult,createArchitectureProfile,createArchitectureProfileFromArkConfig,createElevenLayerArkConfig,detectArchitectureCycles,deterministicHash,elevenLayerProfile,evaluateArchitectureGraph,explainViolation,extractSemanticDependencies,loadArkConfigContract,loadContract,parseArkConfigJson,policyDeltaAcknowledgementMatches,preflightChange,stableSerialize,toAdapterDiagnostic,version});
1
+ "use strict";var Ce=Object.defineProperty;var st=Object.getOwnPropertyDescriptor;var ct=Object.getOwnPropertyNames;var lt=Object.prototype.hasOwnProperty;var pt=(e,t)=>{for(var n in t)Ce(e,n,{get:t[n],enumerable:!0})},dt=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ct(t))!lt.call(e,r)&&r!==n&&Ce(e,r,{get:()=>t[r],enumerable:!(i=st(t,r))||i.enumerable});return e};var ft=e=>dt(Ce({},"__esModule",{value:!0}),e);var Qt={};pt(Qt,{ANALYSIS_IR_SCHEMA_VERSION:()=>pe,ARK_ANALYSIS_RESULT_SCHEMA:()=>je,ARK_ANALYSIS_RESULT_SCHEMA_VERSION:()=>De,ARK_CONFIG_SCHEMA:()=>se,ARK_CONFIG_SCHEMA_VERSION:()=>Je,POLICY_DELTA_SCHEMA_VERSION:()=>et,analyzeArchitectureConvergence:()=>X,analyzeChange:()=>te,analyzePolicyDelta:()=>$e,analyzeProject:()=>U,classifyArkPolicyDelta:()=>ye,collectAnalysisConfigWarnings:()=>Ne,collectForbiddenCapabilityUses:()=>D,createAICodeGate:()=>we,createAdapterResult:()=>Fe,createArchitectureProfile:()=>Z,createArchitectureProfileFromArkConfig:()=>Pe,createElevenLayerArkConfig:()=>Re,detectArchitectureCycles:()=>he,deterministicHash:()=>L,elevenLayerProfile:()=>J,evaluateArchitectureGraph:()=>ne,explainViolation:()=>ve,extractSemanticDependencies:()=>T,loadArkConfigContract:()=>W,loadContract:()=>ee,parseArkConfigJson:()=>le,policyDeltaAcknowledgementMatches:()=>ge,preflightChange:()=>_e,stableSerialize:()=>w,toAdapterDiagnostic:()=>ie,version:()=>Me});module.exports=ft(Qt);var Me="3.3.0";var De="1.1";function E(e){return typeof e=="string"&&e.length>0?e:void 0}function Te(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}function ut(e,t,n){return e==="LAYER_IMPORT_VIOLATION"?t.typeOnly||n.targetTypeOnlyExports===!0||n.namedBindingsTypeOnly===!0?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":n.peerIsolation===!0?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${t.fromLayer??"the source layer"}, inject the ${t.toLayer??"outer-layer"} implementation, then preflight again.`:e==="FORBIDDEN_GLOBAL"?`Inject ${t.target??"the capability"} through a port, then preflight again.`:e==="CIRCULAR_DEPENDENCY"?"Extract the shared dependency into a third module, then preflight again.":e==="RAW_EVENT_PUBLISH"?"Publish through a registered intent creator, then run Ark again.":e==="PUBLISH_MISSING_SOURCE"?"Add metadata.source to the publish call, then run Ark again.":`Resolve ${e} without weakening ark.config.json, then run Ark again.`}function ie(e,t="error"){let n=E(e.ruleId)??E(e.code)??"ARK_UNKNOWN",i=e.severity==="warning"?"warning":t,r={...E(e.target)?{target:E(e.target)}:{},...E(e.fromLayer)?{fromLayer:E(e.fromLayer)}:{},...E(e.toLayer)?{toLayer:E(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{}};return{ruleId:n,severity:i,message:E(e.message)??n,location:{file:E(e.file)??"<unknown>",line:Te(e.line,1),column:Te(e.column,1)},evidence:r,nextAction:E(e.nextAction)??ut(n,r,e)}}function Fe(e){return{schemaVersion:"1.1",valid:e.valid,diagnostics:[...(e.violations??[]).map(t=>ie(t,"error")),...(e.warnings??[]).map(t=>ie(t,"warning"))]}}var je={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@2/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","valid","diagnostics"],properties:{schemaVersion:{const:"1.1"},valid:{type:"boolean"},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"}}},nextAction:{type:"string",minLength:1}}}}}};var Ve=new Map;function He(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}function be(e){let t="";for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="\\"&&n+1<e.length){let r=e[n+1];if("*?{}[],".includes(r)||r==="\\"){t+="\\"+r,n+=1;continue}t+="/";continue}t+=i}return t}function yt(e){let t=0;for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="\\"){n+=1;continue}if(i==="{")t+=1;else if(i==="}"&&(t-=1,t<0))return!1}return t===0}function z(e){let t=Ve.get(e);if(t)return t;let n=be(e),i=yt(n),r="",a=0;for(let c=0;c<n.length;c+=1){let p=n[c];p==="\\"&&c+1<n.length?(r+=He(n[c+1]),c+=1):p==="*"?n[c+1]==="*"?n[c+2]==="/"?(r+="(?:.*/)?",c+=2):(r+=".*",c+=1):r+="[^/]*":p==="?"?r+="[^/]":p==="{"&&i?(r+="(?:",a+=1):p==="}"&&i&&a>0?(r+=")",a-=1):p===","&&i&&a>0?r+="|":r+=He(p)}let s=new RegExp(`^${r}$`);return Ve.set(e,s),s}function Ie(e){let t=be(String(e)),i=t.split("*")[0].split("/").filter(Boolean).length,r=t.replace(/\*/g,"").length;return i*1e4+r}function B(e,t){let n=String(e).split(/[/\\]/).join("/"),i,r=-1;for(let a of t??[])if(!(a.exclude??[]).some(s=>z(s).test(n))){for(let s of a.patterns??[])if(z(s).test(n)){let c=Ie(s);c>r&&(r=c,i=a.name)}}return i}function Ge(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),i=new Set(t.map(r=>String(r).toLowerCase()));for(let r=0;r<n.length-1;r+=1)if(i.has(n[r].toLowerCase()))return`${n[r]}/${n[r+1]}`}function gt(e){let t=new Set;for(let n of e??[]){let r=be(String(n)).split("/").filter(Boolean);for(let a=0;a<r.length;a+=1){let s=r[a];if((s==="**"||s==="*")&&a>0){let c=r[a-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&t.add(c)}}}return[...t]}function mt(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(r=>typeof r=="string"&&r.length>0);let i=(n??[]).find(r=>r.name===t);return gt(i?.patterns)}function $(e,t,n,i){for(let r of e??[])if(!(r.from!==t||r.to!==n)&&r.allowed===!1){if(r.peerIsolation){let a=i?.fromPath,s=i?.toPath;if(!a||!s)continue;let c=mt(r,t,i?.layers);if(c.length===0)continue;let p=Ge(a,c),u=Ge(s,c);if(!p||!u)continue;if(p!==u)return r;continue}if(t!==n)return r}}var xe={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."};function v(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}function Se(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&v(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:xe.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:xe.PUBLISH_MISSING_SOURCE}),t}function M(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function Be(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}function Ue(e,t){if(e.isImportDeclaration(t)){let n=t.importClause;if(!n)return!1;if(n.isTypeOnly)return!0;let i=n.namedBindings;return!!(i&&e.isNamedImports(i)&&i.elements.length>0&&i.elements.every(r=>r.isTypeOnly))}if(e.isExportDeclaration(t)){if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(i=>i.isTypeOnly))}return!1}function Ke(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},i=e.createCompilerHost(n,!0);return i.getSourceFile=r=>r===t.fileName?t:void 0,i.fileExists=r=>r===t.fileName,i.readFile=r=>r===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,i).getTypeChecker()}function ke(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}function Ee(e,t,n,i){let r=i.parent&&e.isShorthandPropertyAssignment(i.parent)&&i.parent.name===i,a;try{a=r?t.getShorthandAssignmentValueSymbol(i.parent):ke(t,i)}catch{a=void 0}return!!a?.declarations?.some(s=>s.getSourceFile().fileName===n.fileName)}function T(e,t){let n,i=[],r=(s,c,p,u=!1)=>i.push({specifier:p,kind:c,line:Be(t,s),typeOnly:u,unresolved:p===void 0,node:s}),a=s=>{if(e.isImportDeclaration(s))r(s,"import",M(e,s.moduleSpecifier),Ue(e,s));else if(e.isExportDeclaration(s)&&s.moduleSpecifier)r(s,"export",M(e,s.moduleSpecifier),Ue(e,s));else if(e.isImportEqualsDeclaration(s)&&e.isExternalModuleReference(s.moduleReference))r(s,"require",M(e,s.moduleReference.expression));else if(e.isCallExpression(s)){let c=s.expression.kind===e.SyntaxKind.ImportKeyword,u=e.isIdentifier(s.expression)&&s.expression.text==="require"&&!Ee(e,n??(n=Ke(e,t)),t,s.expression);(c||u)&&r(s,u?"require":"dynamic-import",M(e,s.arguments[0]))}e.forEachChild(s,a)};return a(t),i}function ht(e,t){let n=[],i=t;for(;e.isPropertyAccessExpression(i)||e.isElementAccessExpression(i);){if(e.isPropertyAccessExpression(i))n.unshift(i.name.text);else{let r=M(e,i.argumentExpression);if(r===void 0)return;n.unshift(r)}i=i.expression}if(e.isIdentifier(i))return n.unshift(i.text),{root:i,segments:n}}function At(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}function ze(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let i=n.length;i>=1;i-=1){let r=n.slice(0,i).join(".");if(e.has(r))return r}}function D(e,t,n){if(n.length===0)return[];let i=new Set(n),r=Ke(e,t),a=new Map,s=new Set;for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations)e.isIdentifier(l.name)&&s.add(l.name.text);let c=o=>{let l=ht(e,o);if(!l)return;let f=ke(r,l.root),g=f?a.get(f):void 0;return g?[...g,...l.segments.slice(1)]:Ee(e,r,t,l.root)||s.has(l.root.text)?void 0:l.segments};for(let o of t.statements)if(e.isVariableStatement(o))for(let l of o.declarationList.declarations){if(!l.initializer||!e.isIdentifier(l.name))continue;let f=c(l.initializer),g=ke(r,l.name);!f||!g||a.set(g,f)}let p=[],u=new Set,y=(o,l)=>{let f=Be(t,l),g=`${o}:${l.getStart(t)}`;u.has(g)||(u.add(g),p.push({name:o,line:f,node:l}))},m=o=>{let l=o.parent&&(e.isPropertyAccessExpression(o.parent)||e.isElementAccessExpression(o.parent))&&o.parent.expression===o;if((e.isPropertyAccessExpression(o)||e.isElementAccessExpression(o))&&!l){let f=c(o),g=f?ze(i,f):void 0;g&&y(g,o)}else e.isIdentifier(o)&&i.has(o.text)&&At(e,o)&&!Ee(e,r,t,o)&&y(o.text,o);if(e.isVariableDeclaration(o)&&e.isObjectBindingPattern(o.name)&&o.initializer){let f=c(o.initializer);if(f)for(let g of o.name.elements){if(!e.isIdentifier(g.name))continue;let k=g.propertyName?M(e,g.propertyName)??g.propertyName.text:g.name.text,b=ze(i,[...f,k]);b&&y(b,o.initializer)}}e.forEachChild(o,m)};return m(t),p}function A(e,t,n){return{ruleId:e,code:e,message:t,...n}}function F(e,t){return e.slice(0,t).split(`
2
+ `).length}function Ct(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,i;for(;(i=n.exec(e))!==null;)t.push({value:i[1],index:i.index});return t}function bt(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let i of n){let r;for(;(r=i.re.exec(e))!==null;){let a=r.index+r[0].indexOf(r[1]),s=r[0],c=i.kind==="import"&&/\bimport\s+type\b/.test(s)||i.kind==="export"&&/\bexport\s+type\b/.test(s);t.push({value:r[1],index:a,kind:i.kind,typeOnly:c})}}return t.sort((i,r)=>i.index-r.index)}function It(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),i=[],r=a=>{e.isStringLiteralLike(a)&&i.push({value:a.text,index:a.getStart(n)}),e.forEachChild(a,r)};return r(n),i}function xt(e){let t=e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return["adapter","adapters","infra","infrastructure","persistence","repository","repositories","integration","database","db"].some(n=>t.includes(n))}function St(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}function kt(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}function Y(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}function Et(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}function Ye(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(i=>!e.isPropertyAssignment(i)&&!e.isShorthandPropertyAssignment(i)?!1:Et(e,i.name)===n)}function q(e,t,n){return Ye(e,t,n)!==void 0}function K(e,t,n){let i=Ye(e,t,n);return i&&e.isPropertyAssignment(i)?i.initializer:void 0}function wt(e,t){let n=K(e,t,"metadata");return q(e,n,"source")}function qe(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?qe(e,t.name):!1:!1}function Lt(e,t){if(!e.isCallExpression(t))return!1;let n=t.expression;return e.isPropertyAccessExpression(n)?n.name.text==="publish":e.isIdentifier(n)&&n.text==="publish"}function Pt(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],i=Y(e,n);return i!==void 0&&v(i)||q(e,n,"intent")||qe(e,n)}function Rt(e,t){if(!e.isCallExpression(t))return!1;let[n,i,r]=t.arguments;return wt(e,n)||q(e,i,"source")||q(e,r,"source")}function Ot(e,t){if(!e.isCallExpression(t))return;let[n,i,r]=t.arguments,a=K(e,n,"metadata");return Y(e,K(e,a,"source"))??Y(e,K(e,i,"source"))??Y(e,K(e,r,"source"))}function $t(e,t,n,i){let r=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),a=n,s=a?.filePath,c=a?.layer,p=[],u=m=>r.getLineAndCharacterOfPosition(m.getStart(r)).line+1,y=m=>{if(Lt(e,m)){let o=m.arguments[0],l=Y(e,o);for(let g of Se({publishCall:!0,rawIntentName:l,objectHasIntent:q(e,o,"intent"),arkPublishCandidate:Pt(e,m),hasSource:Rt(e,m)}))p.push(A(g.ruleId,g.message,{line:u(m),filePath:s}));let f=Ot(e,m);if(i&&c&&f&&v(f)){let g=i.resolveLayer(f);g&&g!==c&&p.push(A("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${f}" resolves to ${g}, but the target file is classified as ${c}.`,{line:u(m),filePath:s,target:f,fromLayer:c,toLayer:g}))}}e.forEachChild(m,y)};return y(r),p}function we(e={}){let t=new Set((e.intents||[]).map(a=>typeof a=="string"?a:a.name)),n=e.forbiddenPatterns||[],i=new Set(e.infrastructureLayers??[]),r=e.enforceIntentAllowlist??t.size>0;return{validate(a,s){let c=[],p=s,u=p?.filePath,y=p?.layer,m=e.typescript,o=m?m.createSourceFile(u??"generated.ts",a,m.ScriptTarget.Latest,!0):void 0,l=o?T(e.typescript,o):void 0,f=l?l.filter(d=>d.specifier!==void 0).map(d=>({value:d.specifier,index:d.node.getStart(o),kind:d.kind,typeOnly:d.typeOnly})):bt(a),g=e.typescript?It(e.typescript,a):Ct(a);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(u))for(let d of l?.filter(({unresolved:h})=>h)??[]){let h=d.kind==="require";c.push(A(h?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${h?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:d.line,filePath:u}))}let k=y!==void 0&&(i.has(y)||kt(y)),b=y!==void 0?` If "${y}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let d of n)if(d instanceof RegExp){d.lastIndex=0;let h=d.exec(a);d.lastIndex=0,h&&c.push(A("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${d}`,{line:h.index===void 0?void 0:F(a,h.index),filePath:u,suggestion:"Remove infrastructure imports from domain/application layers."+b}))}else a.includes(d)&&c.push(A("FORBIDDEN_SUBSTRING",`Forbidden substring: ${d}`,{line:F(a,a.indexOf(d)),filePath:u}));for(let d of f){let h=e.resolveImportTarget?.(d.value,u)??(e.resolveImportLayer?{layer:e.resolveImportLayer(d.value,u)}:void 0),O=typeof u=="string"?e.resolveImportTarget?.(u)??(e.resolveImportLayer?{layer:y,relPath:void 0}:void 0):void 0,N=h?.layer;if(N&&y){let re=$(e.architectureProfile?.rules,y,N,{fromPath:O?.relPath,toPath:h?.relPath,layers:e.architectureLayers});if(re){if(d.typeOnly&&!re.peerIsolation)continue;let Ae=!!re.peerIsolation;c.push(A("LAYER_IMPORT_VIOLATION",re.message??(Ae?`Layer "${y}" must not import across slices into "${N}".`:`Layer "${y}" must not import "${N}".`),{line:F(a,d.index),source:d.value,target:d.value,filePath:u,fromLayer:y,toLayer:N,suggestion:Ae?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:d.kind,peerIsolation:Ae,...d.typeOnly?{typeOnly:!0}:{}}}));continue}if(N!==y)continue}k||d.typeOnly||!xt(d.value)&&!St(d.value)||c.push(A("FORBIDDEN_IMPORT",`Forbidden ${d.kind} target: "${d.value}".`,{line:F(a,d.index),source:d.value,target:d.value,filePath:u,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+b,details:{importKind:d.kind}}))}if(e.policies)for(let d of e.policies){let h=d.check({source:a,context:s});if(h!==!0)if(Array.isArray(h))for(let O of h)c.push(A("POLICY_VIOLATION",O.message,{filePath:u,suggestion:`Fix violation of policy "${d.name}".`}));else h===!1?c.push(A("POLICY_VIOLATION",`Policy ${d.name} failed on generated code`)):c.push(A("POLICY_VIOLATION",h.message))}if(r&&t.size>0)for(let d of g)v(d.value)&&!t.has(d.value)&&c.push(A("UNKNOWN_INTENT",`Unknown intent reference: "${d.value}"`,{line:F(a,d.index),filePath:u,target:d.value,suggestion:`Register intent "${d.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&y)for(let d of g){if(!v(d.value))continue;let h=e.architectureProfile.resolveLayer(d.value);if(!h)continue;let O=$(e.architectureProfile.rules,y,h);O&&c.push(A("LAYER_REFERENCE_VIOLATION",O.message??`Layer "${y}" must not reference "${h}" through "${d.value}".`,{line:F(a,d.index),filePath:u,target:d.value,fromLayer:y,toLayer:h,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:O}}))}if(e.extensions)for(let d of e.extensions)try{let h=d.analyze(a,s);c.push(...h)}catch(h){c.push(A("EXTENSION_ERROR",`Extension "${d.name}" failed: ${h instanceof Error?h.message:String(h)}`))}if(e.typescript&&o&&y&&e.forbiddenGlobals?.[y]?.length)try{c.push(...D(e.typescript,o,e.forbiddenGlobals[y]).map(d=>A("FORBIDDEN_GLOBAL",`${y} must not use the ambient global "${d.name}".`,{line:d.line,filePath:u,target:d.name,fromLayer:y,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})))}catch(d){c.push(A("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${d instanceof Error?d.message:String(d)}`))}if(e.typescript)try{c.push(...$t(e.typescript,a,s,e.architectureProfile))}catch(d){c.push(A("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${d instanceof Error?d.message:String(d)}`))}return{valid:c.length===0,violations:c}}}}var Je="1.0",oe="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",We=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],vt=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function _t(){let e=[];for(let t of We)for(let n of We)t===n||vt.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}var ce=_t();var P={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},se={$schema:"https://json-schema.org/draft/2020-12/schema",$id:oe,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:oe,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:"1.0",default:"1.0"},name:{type:"string",minLength:1},include:{...P,minItems:1,default:["src"]},exclude:{...P,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:ce,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...P,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...P,minItems:1},exclude:P,intentPrefixes:P,description:{type:"string",minLength:1},forbiddenGlobals:P,mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...P,minItems:1}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}}}},V=class extends Error{issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
3
+ ${n.map(i=>`- ${i.path}: ${i.message}`).join(`
4
+ `)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Ze(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Le(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function j(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Nt(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}function ae(e,t,n,i,r){if(t.$ref){let a=Nt(t.$ref,i);if(!a){r.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}ae(e,a,n,i,r);return}if(t.const!==void 0&&!Object.is(e,t.const)){r.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(a=>Object.is(a,e))){r.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Ze(e)){r.push({path:n,message:`must be an object; received ${j(e)}`});return}let a=t.properties??{};for(let s of t.required??[])e[s]===void 0&&r.push({path:Le(n,s),message:"is required"});if(t.additionalProperties===!1)for(let s of Object.keys(e))s in a||r.push({path:Le(n,s),message:"unknown field"});for(let[s,c]of Object.entries(a))e[s]!==void 0&&ae(e[s],c,Le(n,s),i,r);return}if(t.type==="array"){if(!Array.isArray(e)){r.push({path:n,message:`must be an array; received ${j(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&r.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let a=e.map(s=>JSON.stringify(s));new Set(a).size!==a.length&&r.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((a,s)=>ae(a,t.items,`${n}[${s}]`,i,r));return}if(t.type==="string"){if(typeof e!="string"){r.push({path:n,message:`must be a string; received ${j(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&r.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&r.push({path:n,message:`must be a boolean; received ${j(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){r.push({path:n,message:`must be an integer; received ${j(e)}`});return}t.minimum!==void 0&&e<t.minimum&&r.push({path:n,message:`must be at least ${t.minimum}`})}}function Mt(e){return{...e,$schema:e.$schema===void 0?oe:e.$schema,schemaVersion:e.schemaVersion===void 0?"1.0":e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?ce.map(t=>({...t})):e.rules}}function Tt(e,t="ark.config.json"){if(!Ze(e))throw new V(t,[{path:"$",message:`must be an object; received ${j(e)}`}]);let n=e.schemaVersion===void 0?"unversioned":null;if(e.schemaVersion!==void 0&&e.schemaVersion!=="1.0")throw new V(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected 1.0`}]);return{candidate:Mt(e),migratedFrom:n}}function W(e,t="ark.config.json"){let{candidate:n,migratedFrom:i}=Tt(e,t),r=[];if(ae(n,se,"$",se,r),r.length>0)throw new V(t,r);return{config:n,migratedFrom:i}}function le(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(i){throw new V(t,[{path:"$",message:`invalid JSON: ${i instanceof Error?i.message:String(i)}`}])}return W(n,t)}function Qe(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:oe,schemaVersion:"1.0"};for(let[n,i]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=i);return t}function Dt(e){return e.endsWith(".")?e:`${e}.`}function Ft(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(r=>r.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(r=>r.length)):0)-n}function Z(e){let t=e.layers.map(r=>({...r,prefixes:r.prefixes.map(Dt)})),n=[...t].sort(Ft),i=[...e.rules??[]];return{name:e.name,layers:t,rules:i,resolveLayer(r){return t.find(a=>a.match?.(r))?.name??n.find(a=>a.prefixes.some(s=>r.startsWith(s)))?.name}}}function Pe(e,t={}){return Z({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,i)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:i+1})),rules:e.rules??[]})}var jt=[{name:"DomainModel",prefixes:["Domain"],description:"Rich domain model, business rules, and domain events.",order:1},{name:"ApplicationOrchestration",prefixes:["Application"],description:"Use cases and command orchestration.",order:2},{name:"PersistenceAdapters",prefixes:["Adapter.Persistence","Adapter.Repository"],description:"Database, repository, and storage adapters.",order:3},{name:"IntegrationAdapters",prefixes:["Adapter.Integration","Adapter.External"],description:"External systems, APIs, and integration adapters.",order:4},{name:"WorkflowSagaEngine",prefixes:["Workflow"],description:"Sagas, workflows, and long-running processes.",order:5},{name:"BackgroundJobsScheduling",prefixes:["Job"],description:"Background jobs, scheduled work, and async processors.",order:6},{name:"PresentationAdapters",prefixes:["Presentation","Adapter.Presentation","Adapter.Api"],description:"API, UI, controller, and presentation adapters.",order:7},{name:"ReportingReadModels",prefixes:["Reporting"],description:"Read models, projections, and reporting surfaces.",order:8},{name:"ExtensibilityMetadata",prefixes:["Metadata"],description:"Metadata, extensions, and schema contracts.",order:9},{name:"SecurityAuditObservability",prefixes:["Security","Audit","Observability"],description:"Security, audit, and observability concerns.",order:10},{name:"Kernel",prefixes:["Kernel"],description:"Ark-owned governance and kernel signals.",order:11}],J=Z({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:jt,rules:ce.map(e=>({...e}))}),Vt={DomainModel:["domain"],ApplicationOrchestration:["application","app"],PersistenceAdapters:["adapters/persistence","adapters/repository","repositories","infra/persistence"],IntegrationAdapters:["adapters/integration","adapters/external","integrations"],WorkflowSagaEngine:["workflows","sagas"],BackgroundJobsScheduling:["jobs","schedules"],PresentationAdapters:["presentation","adapters/presentation","adapters/api"],ReportingReadModels:["reporting","read-models","projections"],ExtensibilityMetadata:["metadata","extensions"],SecurityAuditObservability:["security","audit","observability"],Kernel:["kernel"]};function Re(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,i=t==="."?"":`${t}/`;return Qe({include:e.include??[t],layers:J.layers.map(r=>({name:r.name,patterns:(Vt[r.name]??[r.name]).map(a=>`${i}${a}/**`),intentPrefixes:r.prefixes,optional:n})),rules:[...J.rules]})}var pe="1.0";function L(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}function w(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(w).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${w(t[n])}`).join(",")}}`}function x(e){return`${e.from}->${e.to}`}function Q(e,t,n,i="dependency"){return{id:`${e}:${i}:${x(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${x(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${x(t)}, then preflight again.`}:e==="unplanned"?{nextAction:`Remove the unplanned dependency ${x(t)} from the candidate, then preflight again.`}:{}}}function X(e){let t=[],n=new Map(e.changeMap.map.files.map(o=>[o.path,o])),i=new Map(e.changes.map(o=>[o.path,o])),r=new Map(e.changeMap.map.dependencies.map(o=>[x(o),o])),a=new Map(e.baseDependencies.map(o=>[x(o),o])),s=new Map(e.candidateDependencies.map(o=>[x(o),o]));for(let o of[...n.values()].sort((l,f)=>l.path.localeCompare(f.path))){let l=i.get(o.path);l?l.operation!==o.operation?t.push({id:`contradictory:file:${o.path}`,classification:"contradictory",subject:"file",path:o.path,expectedOperation:o.operation,actualOperation:l.operation,message:`${o.path} was planned as ${o.operation} but the actual operation is ${l.operation}.`,nextAction:`Change ${o.path} to the planned ${o.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${o.path}`,classification:"satisfied",subject:"file",path:o.path,expectedOperation:o.operation,actualOperation:l.operation,message:`${o.path} matches the planned ${o.operation} operation.`}):t.push({id:`missing:file:${o.path}`,classification:"missing",subject:"file",path:o.path,expectedOperation:o.operation,message:`${o.path} was planned as ${o.operation} but is absent from the actual change.`,nextAction:`${o.operation[0].toUpperCase()}${o.operation.slice(1)} ${o.path} in the complete change set, then preflight again.`})}for(let o of[...i.values()].sort((l,f)=>l.path.localeCompare(f.path)))n.has(o.path)||t.push({id:`unplanned:file:${o.path}`,classification:"unplanned",subject:"file",path:o.path,actualOperation:o.operation,message:`${o.path} has an unplanned ${o.operation} operation.`,nextAction:`Remove ${o.path} from the change set, then preflight again.`});let c=new Set;for(let o of[...r.values()].sort((l,f)=>x(l).localeCompare(x(f)))){if(s.has(x(o))){t.push(Q("satisfied",o,`${o.from} -> ${o.to} exists in the candidate architecture.`));continue}let l={from:o.to,to:o.from};s.has(x(l))?(c.add(x(l)),t.push(Q("contradictory",o,`${o.from} -> ${o.to} was planned, but the candidate contains the reverse edge.`))):t.push(Q("missing",o,`${o.from} -> ${o.to} is absent from the candidate architecture.`))}let p=new Set([...n.keys(),...i.keys()]);for(let[o,l]of[...s].sort(([f],[g])=>f.localeCompare(g)))a.has(o)||r.has(o)||c.has(o)||!p.has(l.from)&&!p.has(l.to)||t.push({...Q("unplanned",l,`${l.from} -> ${l.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let u=new Set(e.changeMap.map.files.filter(o=>o.operation==="delete").map(o=>o.path));for(let[o,l]of[...a].sort(([f],[g])=>f.localeCompare(g)))s.has(o)||u.has(l.from)||u.has(l.to)||!p.has(l.from)&&!p.has(l.to)||t.push({...Q("unplanned",l,`${l.from} -> ${l.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let y={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((o,l)=>y[o.classification]-y[l.classification]||(o.subject===l.subject?0:o.subject==="file"?-1:1)||o.id.localeCompare(l.id));let m={satisfied:t.filter(o=>o.classification==="satisfied").length,missing:t.filter(o=>o.classification==="missing").length,contradictory:t.filter(o=>o.classification==="contradictory").length,unplanned:t.filter(o=>o.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:m.missing===0&&m.contradictory===0&&m.unplanned===0,behavioralCompletion:"not-evaluated",summary:m,findings:t}}var Ht=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),Gt=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Xe=Object.freeze(Object.keys(Gt).sort()),Oe=Object.freeze({fs:"filesystem","node:fs":"filesystem","fs/promises":"filesystem","node:fs/promises":"filesystem","fs-extra":"filesystem","graceful-fs":"filesystem",memfs:"filesystem",chokidar:"filesystem",http:"network",https:"network",http2:"network",net:"network",tls:"network",dgram:"network",dns:"network","node:http":"network","node:https":"network","node:http2":"network","node:net":"network","node:tls":"network","node:dgram":"network","node:dns":"network",axios:"network",undici:"network","node-fetch":"network",got:"network",ky:"network",superagent:"network",ws:"network",process:"process","node:process":"process",child_process:"process","node:child_process":"process","@prisma/client":"persistence",prisma:"persistence",pg:"persistence",mysql:"persistence",mysql2:"persistence",mongodb:"persistence",mongoose:"persistence",sqlite3:"persistence","better-sqlite3":"persistence",redis:"persistence",ioredis:"persistence",typeorm:"persistence",knex:"persistence","drizzle-orm":"persistence",sequelize:"persistence",kysely:"persistence","@supabase/supabase-js":"persistence"});function de(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Oe[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let i=e.slice(0,n),r=Oe[i];if(r)return r;let a=e.indexOf("/",n+1);return a<0?null:Oe[e.slice(0,a)]??null}var et="1.0";function C(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}function S(e){return[...new Set(e??[])].sort()}function H(e,t,n,i,r){let a=S(n),s=S(i),c=new Set(a),p=new Set(s),u=s.filter(m=>!c.has(m)),y=a.filter(m=>!p.has(m));u.length===0&&y.length===0||(u.length>0&&C(e,{kind:"added",path:t,classification:r.added,message:r.addedMessage,before:a,after:s}),y.length>0&&C(e,{kind:"removed",path:t,classification:r.removed,message:r.removedMessage,before:a,after:s}))}function fe(e,t,n,i,r,a,s){if(n===i)return;C(e,{kind:i?"enabled":"disabled",path:t,classification:i?r:r==="strengthening"?"weakening":"strengthening",message:i?a:s,before:n,after:i})}function ue(e,t){let n=new Map,i=new Set;for(let r of e){let a=t(r);n.has(a)?i.add(a):n.set(a,r)}return{values:n,duplicates:[...i].sort()}}function zt(e,t,n){let i=ue(t,a=>a.name),r=ue(n,a=>a.name);(i.duplicates.length>0||r.duplicates.length>0)&&C(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:i.duplicates,after:r.duplicates});for(let a of[...new Set([...i.values.keys(),...r.values.keys()])].sort()){let s=i.values.get(a),c=r.values.get(a),p=`$.layers[${a}]`;if(!s&&c){C(e,{kind:"layer-added",path:p,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:c});continue}if(s&&!c){C(e,{kind:"layer-removed",path:p,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:s});continue}!s||!c||(H(e,`${p}.patterns`,s.patterns,c.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),H(e,`${p}.exclude`,s.exclude,c.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."}),H(e,`${p}.forbiddenGlobals`,s.forbiddenGlobals,c.forbiddenGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),S(s.intentPrefixes).join("\0")!==S(c.intentPrefixes).join("\0")&&C(e,{kind:"intent-prefixes-changed",path:`${p}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:S(s.intentPrefixes),after:S(c.intentPrefixes)}),fe(e,`${p}.mayImportInfrastructure`,s.mayImportInfrastructure===!0,c.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),fe(e,`${p}.optional`,s.optional===!0,c.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active."))}}function Bt(e,t,n){let i=s=>`${s.from}->${s.to}`,r=ue(t,i),a=ue(n,i);(r.duplicates.length>0||a.duplicates.length>0)&&C(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:r.duplicates,after:a.duplicates});for(let s of[...new Set([...r.values.keys(),...a.values.keys()])].sort()){let c=r.values.get(s),p=a.values.get(s),u=`$.rules[${s}]`;if(!c&&p){p.allowed===!1&&C(e,{kind:"deny-added",path:u,classification:"strengthening",message:"A denied dependency edge was added.",after:p});continue}if(c&&!p){c.allowed===!1&&C(e,{kind:"deny-removed",path:u,classification:"weakening",message:"A denied dependency edge was removed.",before:c});continue}if(!c||!p)continue;c.allowed!==p.allowed&&C(e,{kind:p.allowed?"deny-disabled":"deny-enabled",path:`${u}.allowed`,classification:p.allowed?"weakening":"strengthening",message:p.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:c.allowed,after:p.allowed});let y=c.peerIsolation===!0,m=p.peerIsolation===!0;if(y!==m){let o=c.from===c.to&&p.from===p.to;C(e,{kind:m?"peer-isolation-enabled":"peer-isolation-disabled",path:`${u}.peerIsolation`,classification:o?m?"strengthening":"weakening":"judgment-required",message:o?m?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:y,after:m})}S(c.sliceFolders).join("\0")!==S(p.sliceFolders).join("\0")&&C(e,{kind:"slice-folders-changed",path:`${u}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:S(c.sliceFolders),after:S(p.sliceFolders)})}}function Kt(e,t,n){let i=t.safety??{},r=n.safety??{};for(let a of["maxTsSuppressions","maxAnyCasts"]){let s=i[a]??0,c=r[a]??0;s!==c&&C(e,{kind:c>s?"threshold-raised":"threshold-lowered",path:`$.safety.${a}`,classification:c>s?"weakening":"strengthening",message:c>s?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:s,after:c})}for(let a of["allowInMemory","allowDisabledPeerIsolation"])fe(e,`$.safety.${a}`,i[a]===!0,r[a]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}function Yt(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}function ye(e,t){let n=[];H(n,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),H(n,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),H(n,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),fe(n,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let i={off:0,soft:1,"framework-soft":1,strict:2},r=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(r!==a){let s=i[a]===i[r]?"judgment-required":i[a]>i[r]?"strengthening":"weakening";C(n,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:s,message:"The cycle enforcement level changed.",before:r,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&C(n,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),zt(n,e.layers,t.layers),Bt(n,e.rules,t.rules),Kt(n,e,t),n.sort((s,c)=>s.path.localeCompare(c.path)||s.id.localeCompare(c.id)),{schemaVersion:"1.0",classification:Yt(n),findings:n}}function ge(e,t){if(!e||e.schemaVersion!=="1.0"||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(r=>typeof r!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=S(e.findingIds),i=S(t.findingIds);return n.length===i.length&&n.every((r,a)=>r===i[a])}function _(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}function tt(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}function G(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}function me(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let i=t,r="";for(t+=1;t<e.length;t+=1){let a=e[t];if(a===n)return{value:r,offset:i,excerpt:e.slice(i,t+1)};a==="\\"&&t+1<e.length?(r+=e[t+1],t+=1):r+=a}}function R(e,t,n){return e.startsWith(t,n)&&!tt(e[n-1])&&!tt(e[n+t.length])}function qt(e,t){if(t=G(e,t+6),e[t]==="(")return me(e,G(e,t+1));let n=!1;if(R(e,"type",t)){let r=G(e,t+4);e[r]!==","&&!R(e,"from",r)&&(n=!0)}let i=nt(e,t,!0);return i&&n?{...i,typeOnly:!0}:i}function Wt(e,t){t=t+6;let n=G(e,t),i=!1;if(R(e,"type",n)){let a=G(e,n+4);(e[a]==="{"||e[a]==="*")&&(i=!0)}let r=nt(e,t,!1);return r&&i?{...r,typeOnly:!0}:r}function nt(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(R(e,"from",t))return me(e,G(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return me(e,t);if(t>0&&(R(e,"import",t)||R(e,"export",t)))return}}function Jt(e){let t=[];for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
5
+ `,n+2),n<0)break;continue}if(i==="/"&&e[n+1]==="*"){let a=e.indexOf("*/",n+2);if(a<0)break;n=a+1;continue}if(i==="'"||i==='"'||i==="`"){let a=me(e,n);a&&(n=a.offset+a.excerpt.length-1);continue}let r=R(e,"import",n)?qt(e,n):R(e,"export",n)?Wt(e,n):void 0;r&&t.push(r)}return t}function rt(e,t){let n=[],i=[];for(let r of Jt(e.content)){let a=r.value;if(!a.startsWith(".")){if(r.typeOnly)continue;let u=de(a);if(!u)continue;let y=e.content.slice(0,r.offset).split(`
6
+ `).length;i.push({file:e.path,symbol:a,capability:u,evidence:{kind:"import",file:e.path,line:y,excerpt:r.excerpt}});continue}let s=e.content.slice(0,r.offset).split(`
7
+ `).length,c={kind:"import",file:e.path,line:s,excerpt:r.excerpt},p=Zt(e.path,a,t);n.push({from:e.path,specifier:a,to:p?.path??null,resolution:p?"resolved":"unresolved",fromLayer:e.layer,toLayer:p?.layer??null,evidence:c})}return{edges:n,capabilityUses:i}}function Zt(e,t,n){let i=e.split("/");i.pop();for(let a of t.split("/"))a==="."||a===""||(a===".."?i.pop():i.push(a));let r=i.join("/");for(let a of[r,`${r}.ts`,`${r}.tsx`,`${r}.mts`,`${r}.cts`,`${r}/index.ts`,`${r}/index.tsx`]){let s=n.get(a);if(s)return s}}function it(e,t){let n=[];for(let i of e){if(!i.to||!i.fromLayer||!i.toLayer)continue;let r=$(t.rules,i.fromLayer,i.toLayer,{fromPath:i.from,toPath:i.to,layers:t.layers});r&&n.push({ruleId:`layer-dependency:${r.from}->${r.to}`,message:r.message??`${r.from} must not depend on ${r.to}.`,edge:i,evidence:i.evidence})}return n}function ee(e,t){let n=typeof e=="string"?le(e,t):W(e,t);return{...n,policyHash:L(w(n.config))}}function $e(e){let t=ee(e.baseConfig,e.baseSource??"base ark.config.json"),n=ee(e.candidateConfig,e.candidateSource??"candidate ark.config.json"),i=ye(t.config,n.config),r=i.findings.filter(c=>c.classification==="weakening"||c.classification==="judgment-required").map(c=>c.id).sort(),a=r.length>0,s=a&&ge(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:r});return{schemaVersion:i.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:i.classification,findings:i.findings,blockingFindingIds:r,requiresAcknowledgement:a,acknowledged:s,valid:!a||s}}function U(e){let t=e.files.map(s=>{let c=_(s.path);return{path:c,content:s.content,contentHash:L(s.content),layer:B(c,e.contract.config.layers)??null}}).sort((s,c)=>s.path.localeCompare(c.path)),n=new Map(t.map(s=>[s.path,s])),i=[],r=[];for(let s of t){let c=rt(s,n);i.push(...c.edges),r.push(...c.capabilityUses)}let a=it(i,e.contract.config);return{ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:L(w(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(s=>s.name),edges:i,capabilityUses:r,violations:a}}}function te(e){let t=new Map(e.files.map(n=>[_(n.path),n]));for(let n of e.changes){let i=_(n.path);"delete"in n&&n.delete?t.delete(i):"content"in n&&t.set(i,{path:i,content:n.content})}return U({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}function ve(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}function he(e){let t=0,n=new Map,i=new Map,r=new Set,a=[],s=[],c=p=>{n.set(p,t),i.set(p,t),t+=1,a.push(p),r.add(p);for(let m of[...e.get(p)??[]].sort())e.has(m)&&(n.has(m)?r.has(m)&&i.set(p,Math.min(i.get(p)??0,n.get(m)??0)):(c(m),i.set(p,Math.min(i.get(p)??0,i.get(m)??0))));if(i.get(p)!==n.get(p))return;let u=[],y;do{if(y=a.pop(),y===void 0)break;r.delete(y),u.push(y)}while(y!==p);u.length>1&&s.push(u.sort())};for(let p of[...e.keys()].sort())n.has(p)||c(p);return s.sort((p,u)=>p[0].localeCompare(u[0])).map(p=>({ruleId:"CIRCULAR_DEPENDENCY",file:p[0],line:1,target:p.join(" \u2192 "),message:`Circular dependency among ${p.length} files: ${p.join(" \u2192 ")} \u2192 ${p[0]}.`,cycleKind:"value"}))}function ne(e){let t=e.contentViolations.map(a=>({...a})),n=(e.warnings??[]).map(a=>({...a})),i=new Map(e.files.map(a=>[a,new Set]));for(let a of e.edges){if(a.to&&a.to!==a.from&&!a.typeOnly&&i.has(a.from)&&i.get(a.from)?.add(a.to),!a.to||!a.toLayer)continue;let s=$(e.rules,a.fromLayer,a.toLayer,{fromPath:a.from,toPath:a.to,layers:e.config.layers});if(!s)continue;let c=!!s.peerIsolation;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:a.from,line:a.line,fromLayer:a.fromLayer,toLayer:a.toLayer,target:a.to,...a.typeOnly?{typeOnly:!0}:{},...a.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...a.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...a.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&a.portProofEligible?{portProofEligible:!0}:{},...a.kind?{edgeKind:a.kind}:{},...c?{peerIsolation:!0}:{},message:s.message??(c?`${a.fromLayer} must not ${a.kind} another slice of ${a.toLayer} (${a.from} \u2192 ${a.to}). Extract shared code or use events/ports across slices.`:`${a.fromLayer} must not ${a.kind} ${a.toLayer}.`)})}let r=String(e.config.cyclePolicy??"strict").toLowerCase();if(r!=="off"){let a=he(i);r==="soft"||r==="framework-soft"?n.push(...a.map(s=>({...s,message:`${s.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...a)}return{violations:t,warnings:n,safety:e.safety}}function at(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly?"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.":e.peerIsolation?"Extract the shared dependency to a shared layer, then preflight again.":`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, then preflight again.`;case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}function ot(e){return L(w(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}function _e(e){let t=U(e),n=new Map(t.ir.files.map(o=>[o.path,o])),i=[],r=new Set,a=[];for(let o of e.changes){let l=o.path.replace(/\\/g,"/"),f=_(o.path);if(!f||f===".."||f.startsWith("../")||l.startsWith("/")||/^[A-Za-z]:\//.test(l)||l.includes("\0")){a.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(r.has(f)){a.push({ruleId:"DUPLICATE_CHANGE_PATH",file:f,line:1,message:`The atomic change set contains more than one operation for ${f}.`});continue}r.add(f),"delete"in o&&o.delete&&!n.has(f)&&a.push({ruleId:"DELETE_TARGET_MISSING",file:f,line:1,message:`Cannot delete ${f} because it is not present in the supplied base tree.`}),i.push("delete"in o&&o.delete?{path:f,delete:!0}:{path:f,content:"content"in o?o.content:""})}e.changes.length===0&&a.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let s=te({...e,changes:i}),c=new Map(s.ir.files.map(o=>[o.path,o])),p=ne({config:e.contract.config,rules:e.contract.config.rules,files:s.ir.files.map(o=>o.path),contentViolations:[],edges:s.ir.edges.filter(o=>!!o.fromLayer).map(o=>({from:o.from,fromLayer:o.fromLayer,...o.to?{to:o.to}:{},...o.toLayer?{toLayer:o.toLayer}:{},line:o.evidence.line,kind:"import"}))}),u=i.map(o=>{let l=_(o.path),f=n.get(l),g=c.get(l);return{path:l,operation:"delete"in o&&o.delete?"delete":f?"update":"create",...f?{beforeContentHash:f.contentHash}:{},...g?{candidateContentHash:g.contentHash}:{}}}).sort((o,l)=>o.path.localeCompare(l.path)),y=[...a,...p.violations].map(o=>({...o,nextAction:at(o)})),m=e.changeMap?X({changeMap:e.changeMap,changes:u,baseDependencies:t.ir.edges.flatMap(o=>o.to?[{from:o.from,to:o.to}]:[]),candidateDependencies:s.ir.edges.flatMap(o=>o.to?[{from:o.from,to:o.to}]:[])}):void 0;return{schemaVersion:"1.0",valid:y.length===0&&(m?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:s.ir.compilerOptionsHash,baseTreeHash:ot(t.ir.files),candidateTreeHash:ot(s.ir.files),...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...m?{convergence:m}:{},changes:u,violations:y,warnings:p.warnings}}function I(e,t,n={}){return{ruleId:e,message:t,...n}}function Ne(e){let{config:t,rules:n,files:i,manifest:r}=e,a=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(l=>typeof l!="string"))&&a.push(I("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))a.push(I("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let l of["maxTsSuppressions","maxAnyCasts"]){let f=t.safety[l];f!==void 0&&(!Number.isInteger(f)||f<0)&&a.push(I("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${l} must be a non-negative integer.`))}let s=Array.isArray(t.layers)?t.layers:[],c=Array.isArray(r?.architecture?.layers)?r.architecture.layers:[],p=new Set([...s.map(l=>l.name).filter(Boolean),...c.map(l=>l.name).filter(l=>!!l)]);s.length===0&&a.push(I("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let u=new Set,y=new Set;for(let l of s){if(!l.name){a.push(I("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}u.has(l.name)&&y.add(l.name),u.add(l.name),l.forbiddenGlobals!==void 0&&(!Array.isArray(l.forbiddenGlobals)||l.forbiddenGlobals.some(g=>typeof g!="string"))&&a.push(I("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${l.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:l.name}));let f=Array.isArray(l.patterns)?l.patterns:[];if(f.length===0){a.push(I("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${l.name}" has no file patterns and will never classify files.`,{layer:l.name}));continue}for(let g of f){let k;try{k=z(g)}catch(b){a.push(I("CONFIG_INVALID_LAYER_PATTERN",`Layer "${l.name}" has an invalid pattern "${g}": ${b instanceof Error?b.message:String(b)}`,{layer:l.name,pattern:g}));continue}!i.some(b=>k.test(b))&&!l.optional&&a.push(I("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${l.name}" pattern "${g}" matched no included files.`,{layer:l.name,pattern:g,failsStrict:!1}))}}for(let l of y)a.push(I("CONFIG_DUPLICATE_LAYER",`Layer "${l}" is configured more than once.`,{layer:l}));if(p.size>0)for(let l of n??[])l.from&&!p.has(l.from)&&a.push(I("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${l.from}".`,{fromLayer:l.from,toLayer:l.to})),l.to&&!p.has(l.to)&&a.push(I("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${l.to}".`,{fromLayer:l.from,toLayer:l.to}));let m=new Set;if(s.length>1)for(let l of i){let f=-1,g=[];for(let k of s)for(let b of k.patterns??[]){if(!z(b).test(l))continue;let d=Ie(b);d>f?(f=d,g=[k.name]):d===f&&!g.includes(k.name)&&g.push(k.name)}g.length>1&&m.add([...g].sort().join(" + "))}m.size>0&&a.push(I("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...m].join(", ")}.`,{pairs:[...m]}));let o=i.filter(l=>!B(l,s));return o.length>0&&a.push(I("CONFIG_UNCLASSIFIED_FILES",`${o.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:o.length,samples:o.slice(0,5)})),a}0&&(module.exports={ANALYSIS_IR_SCHEMA_VERSION,ARK_ANALYSIS_RESULT_SCHEMA,ARK_ANALYSIS_RESULT_SCHEMA_VERSION,ARK_CONFIG_SCHEMA,ARK_CONFIG_SCHEMA_VERSION,POLICY_DELTA_SCHEMA_VERSION,analyzeArchitectureConvergence,analyzeChange,analyzePolicyDelta,analyzeProject,classifyArkPolicyDelta,collectAnalysisConfigWarnings,collectForbiddenCapabilityUses,createAICodeGate,createAdapterResult,createArchitectureProfile,createArchitectureProfileFromArkConfig,createElevenLayerArkConfig,detectArchitectureCycles,deterministicHash,elevenLayerProfile,evaluateArchitectureGraph,explainViolation,extractSemanticDependencies,loadArkConfigContract,loadContract,parseArkConfigJson,policyDeltaAcknowledgementMatches,preflightChange,stableSerialize,toAdapterDiagnostic,version});