arkgate 3.0.5 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +92 -1
  2. package/README.md +58 -21
  3. package/bin/ark-check.mjs +46 -4
  4. package/bin/ark-mcp.mjs +267 -26
  5. package/bin/ark.mjs +47 -0
  6. package/bin/lib/adapter-contract.mjs +27 -1
  7. package/bin/lib/analysis-engine.mjs +7 -1169
  8. package/bin/lib/ci-and-commands.mjs +4 -0
  9. package/bin/lib/contract-smells.mjs +514 -0
  10. package/bin/lib/doctor-plan.mjs +15 -4
  11. package/bin/lib/host-support-matrix.mjs +6 -2
  12. package/bin/lib/policy-delta-io.mjs +161 -0
  13. package/bin/lib/prepare-change.mjs +186 -0
  14. package/bin/lib/remediation.mjs +24 -0
  15. package/bin/lib/violations.mjs +2 -2
  16. package/bin/lib/write-path-capabilities.mjs +67 -1
  17. package/bin/lib/write-path-detect.mjs +4 -3
  18. package/dist/eslint/index.cjs +3 -977
  19. package/dist/eslint/index.js +3 -931
  20. package/dist/index.cjs +6 -1960
  21. package/dist/index.d.cts +152 -5
  22. package/dist/index.d.ts +152 -5
  23. package/dist/index.js +6 -1908
  24. package/docs/agent-guide.md +39 -5
  25. package/docs/ai-gates.md +17 -15
  26. package/docs/configuration.md +44 -0
  27. package/docs/demos/01-write-gate-self-correction.md +2 -2
  28. package/docs/enthusiast/README.md +5 -1
  29. package/docs/enthusiast/how-to-agent-gates.md +3 -5
  30. package/docs/enthusiast/how-to-policy-pack.md +4 -1
  31. package/docs/enthusiast/reference-archetypes.md +8 -1
  32. package/docs/enthusiast/reference-commands.md +8 -2
  33. package/docs/package-surface.md +12 -2
  34. package/docs/threat-model.md +10 -6
  35. package/package.json +7 -6
  36. package/schemas/ark.analysis-result.schema.json +5 -1
  37. package/schemas/ark.change-map.schema.json +77 -0
  38. package/server.json +3 -3
  39. package/docs/ark-check-example.json +0 -87
  40. package/docs/demos/03-copilot-autopilot.md +0 -93
  41. package/docs/migrate-from-ark-runtime-kernel.md +0 -174
  42. package/docs/production-hardening.md +0 -100
@@ -1,977 +1,3 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/eslint/index.ts
31
- var eslint_exports = {};
32
- __export(eslint_exports, {
33
- default: () => eslint_default,
34
- findConfigPath: () => findConfigPath,
35
- globToRegExp: () => globToRegExp,
36
- isEdgeDenied: () => isEdgeDenied,
37
- layerForRelativePath: () => layerForRelativePath,
38
- loadArkConfig: () => loadArkConfig,
39
- noDomainInfraImports: () => noDomainInfraImports,
40
- noForbiddenGlobals: () => noForbiddenGlobals,
41
- noRawEventPublish: () => noRawEventPublish,
42
- patternSpecificity: () => patternSpecificity,
43
- plugin: () => plugin,
44
- requirePublishSource: () => requirePublishSource,
45
- resolveRelativeImport: () => resolveRelativeImport
46
- });
47
- module.exports = __toCommonJS(eslint_exports);
48
- var import_node_fs = __toESM(require("fs"), 1);
49
- var import_node_path = __toESM(require("path"), 1);
50
-
51
- // src/domain/layerMatch.ts
52
- var regexpCache = /* @__PURE__ */ new Map();
53
- function escapeLiteral(ch) {
54
- return /[.*+?^${}()|[\]\\]/.test(ch) ? `\\${ch}` : ch;
55
- }
56
- function normalizeGlobSeparators(pattern) {
57
- let out = "";
58
- for (let i = 0; i < pattern.length; i += 1) {
59
- const c = pattern[i];
60
- if (c === "\\" && i + 1 < pattern.length) {
61
- const next = pattern[i + 1];
62
- if ("*?{}[],".includes(next) || next === "\\") {
63
- out += "\\" + next;
64
- i += 1;
65
- continue;
66
- }
67
- out += "/";
68
- continue;
69
- }
70
- out += c;
71
- }
72
- return out;
73
- }
74
- function bracesBalanced(glob) {
75
- let depth = 0;
76
- for (let i = 0; i < glob.length; i += 1) {
77
- const c = glob[i];
78
- if (c === "\\") {
79
- i += 1;
80
- continue;
81
- }
82
- if (c === "{") depth += 1;
83
- else if (c === "}") {
84
- depth -= 1;
85
- if (depth < 0) return false;
86
- }
87
- }
88
- return depth === 0;
89
- }
90
- function globToRegExp(pattern) {
91
- const cached = regexpCache.get(pattern);
92
- if (cached) return cached;
93
- const glob = normalizeGlobSeparators(pattern);
94
- const useBraces = bracesBalanced(glob);
95
- let out = "";
96
- let braceDepth = 0;
97
- for (let i = 0; i < glob.length; i += 1) {
98
- const c = glob[i];
99
- if (c === "\\" && i + 1 < glob.length) {
100
- out += escapeLiteral(glob[i + 1]);
101
- i += 1;
102
- } else if (c === "*") {
103
- if (glob[i + 1] === "*") {
104
- if (glob[i + 2] === "/") {
105
- out += "(?:.*/)?";
106
- i += 2;
107
- } else {
108
- out += ".*";
109
- i += 1;
110
- }
111
- } else {
112
- out += "[^/]*";
113
- }
114
- } else if (c === "?") {
115
- out += "[^/]";
116
- } else if (c === "{" && useBraces) {
117
- out += "(?:";
118
- braceDepth += 1;
119
- } else if (c === "}" && useBraces && braceDepth > 0) {
120
- out += ")";
121
- braceDepth -= 1;
122
- } else if (c === "," && useBraces && braceDepth > 0) {
123
- out += "|";
124
- } else {
125
- out += escapeLiteral(c);
126
- }
127
- }
128
- const re = new RegExp(`^${out}$`);
129
- regexpCache.set(pattern, re);
130
- return re;
131
- }
132
- function patternSpecificity(pattern) {
133
- const glob = normalizeGlobSeparators(String(pattern));
134
- const beforeWildcard = glob.split("*")[0];
135
- const literalSegments = beforeWildcard.split("/").filter(Boolean).length;
136
- const literalLength = glob.replace(/\*/g, "").length;
137
- return literalSegments * 1e4 + literalLength;
138
- }
139
- function layerForRelativePath(relPath, layers) {
140
- const rel = String(relPath).split(/[/\\]/).join("/");
141
- let bestName;
142
- let bestScore = -1;
143
- for (const layer of layers ?? []) {
144
- if ((layer.exclude ?? []).some((pattern) => globToRegExp(pattern).test(rel))) {
145
- continue;
146
- }
147
- for (const pattern of layer.patterns ?? []) {
148
- if (globToRegExp(pattern).test(rel)) {
149
- const score = patternSpecificity(pattern);
150
- if (score > bestScore) {
151
- bestScore = score;
152
- bestName = layer.name;
153
- }
154
- }
155
- }
156
- }
157
- return bestName;
158
- }
159
- function sliceIdForPath(relPath, sliceFolders) {
160
- if (!sliceFolders?.length) return void 0;
161
- const parts = String(relPath).split(/[/\\]/).filter(Boolean);
162
- const folders = new Set(sliceFolders.map((s) => String(s).toLowerCase()));
163
- for (let i = 0; i < parts.length - 1; i += 1) {
164
- if (folders.has(parts[i].toLowerCase())) {
165
- return `${parts[i]}/${parts[i + 1]}`;
166
- }
167
- }
168
- return void 0;
169
- }
170
- function inferSliceFoldersFromPatterns(patterns) {
171
- const out = /* @__PURE__ */ new Set();
172
- for (const pattern of patterns ?? []) {
173
- const glob = normalizeGlobSeparators(String(pattern));
174
- const parts = glob.split("/").filter(Boolean);
175
- for (let i = 0; i < parts.length; i += 1) {
176
- const part = parts[i];
177
- if ((part === "**" || part === "*") && i > 0) {
178
- const prev = parts[i - 1];
179
- if (prev && !prev.includes("*") && !prev.includes("{") && !prev.includes("}")) {
180
- out.add(prev);
181
- }
182
- }
183
- }
184
- }
185
- return [...out];
186
- }
187
- function resolveSliceFolders(rule, layerName, layers) {
188
- if (Array.isArray(rule.sliceFolders) && rule.sliceFolders.length > 0) {
189
- return rule.sliceFolders.filter((s) => typeof s === "string" && s.length > 0);
190
- }
191
- const layer = (layers ?? []).find((l) => l.name === layerName);
192
- return inferSliceFoldersFromPatterns(layer?.patterns);
193
- }
194
- function findDeniedEdgeRule(rules2, from, to, options) {
195
- for (const rule of rules2 ?? []) {
196
- if (rule.from !== from || rule.to !== to) continue;
197
- if (rule.allowed !== false) continue;
198
- if (rule.peerIsolation) {
199
- const fromPath = options?.fromPath;
200
- const toPath = options?.toPath;
201
- if (!fromPath || !toPath) continue;
202
- const folders = resolveSliceFolders(rule, from, options?.layers);
203
- if (folders.length === 0) continue;
204
- const fromSlice = sliceIdForPath(fromPath, folders);
205
- const toSlice = sliceIdForPath(toPath, folders);
206
- if (!fromSlice || !toSlice) continue;
207
- if (fromSlice !== toSlice) return rule;
208
- continue;
209
- }
210
- if (from === to) continue;
211
- return rule;
212
- }
213
- return void 0;
214
- }
215
- function isEdgeDenied(rules2, from, to, options) {
216
- return findDeniedEdgeRule(rules2, from, to, options) !== void 0;
217
- }
218
-
219
- // src/domain/configContract.ts
220
- var ARK_CONFIG_SCHEMA_VERSION = "1.0";
221
- var ARK_CONFIG_SCHEMA_URL = "https://unpkg.com/arkgate@2/schemas/ark.config.schema.json";
222
- var DEFAULT_LAYER_NAMES = [
223
- "DomainModel",
224
- "ApplicationOrchestration",
225
- "PersistenceAdapters",
226
- "IntegrationAdapters",
227
- "WorkflowSagaEngine",
228
- "BackgroundJobsScheduling",
229
- "PresentationAdapters",
230
- "ReportingReadModels",
231
- "ExtensibilityMetadata",
232
- "SecurityAuditObservability",
233
- "Kernel"
234
- ];
235
- var DEFAULT_ALLOWED_FLOWS = /* @__PURE__ */ new Set([
236
- "PresentationAdapters->ApplicationOrchestration",
237
- "ApplicationOrchestration->DomainModel",
238
- "WorkflowSagaEngine->ApplicationOrchestration",
239
- "WorkflowSagaEngine->DomainModel",
240
- "BackgroundJobsScheduling->ApplicationOrchestration"
241
- ]);
242
- function createDefaultRules() {
243
- const rules2 = [];
244
- for (const from of DEFAULT_LAYER_NAMES) {
245
- for (const to of DEFAULT_LAYER_NAMES) {
246
- if (from === to || DEFAULT_ALLOWED_FLOWS.has(`${from}->${to}`)) continue;
247
- rules2.push({ from, to, allowed: false });
248
- }
249
- }
250
- return rules2;
251
- }
252
- var DEFAULT_ARK_CONFIG_RULES = createDefaultRules();
253
- var stringArraySchema = {
254
- type: "array",
255
- items: { type: "string", minLength: 1 },
256
- uniqueItems: true
257
- };
258
- var ARK_CONFIG_SCHEMA = {
259
- $schema: "https://json-schema.org/draft/2020-12/schema",
260
- $id: ARK_CONFIG_SCHEMA_URL,
261
- title: "ArkGate architecture contract",
262
- description: "Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",
263
- type: "object",
264
- additionalProperties: false,
265
- required: ["$schema", "schemaVersion", "include", "layers", "rules"],
266
- properties: {
267
- $schema: {
268
- type: "string",
269
- minLength: 1,
270
- default: ARK_CONFIG_SCHEMA_URL,
271
- description: "Editor-facing URL or local path for this JSON Schema."
272
- },
273
- schemaVersion: {
274
- type: "string",
275
- const: ARK_CONFIG_SCHEMA_VERSION,
276
- default: ARK_CONFIG_SCHEMA_VERSION
277
- },
278
- name: { type: "string", minLength: 1 },
279
- include: { ...stringArraySchema, minItems: 1, default: ["src"] },
280
- exclude: { ...stringArraySchema, default: [] },
281
- excludeGenerated: { type: "boolean", default: true },
282
- frameworkOverlay: { type: "string", minLength: 1 },
283
- layers: {
284
- type: "array",
285
- default: [],
286
- items: { $ref: "#/$defs/layer" }
287
- },
288
- rules: {
289
- type: "array",
290
- default: DEFAULT_ARK_CONFIG_RULES,
291
- items: { $ref: "#/$defs/rule" }
292
- },
293
- cyclePolicy: {
294
- type: "string",
295
- enum: ["strict", "soft", "framework-soft", "off"],
296
- default: "strict"
297
- },
298
- dynamicImportAllowlist: { ...stringArraySchema, default: [] },
299
- safety: {
300
- $ref: "#/$defs/safety",
301
- default: {
302
- maxTsSuppressions: 0,
303
- maxAnyCasts: 0,
304
- allowInMemory: false,
305
- allowDisabledPeerIsolation: false
306
- }
307
- }
308
- },
309
- $defs: {
310
- layer: {
311
- type: "object",
312
- additionalProperties: false,
313
- required: ["name", "patterns"],
314
- properties: {
315
- name: { type: "string", minLength: 1 },
316
- patterns: { ...stringArraySchema, minItems: 1 },
317
- exclude: stringArraySchema,
318
- intentPrefixes: stringArraySchema,
319
- description: { type: "string", minLength: 1 },
320
- forbiddenGlobals: stringArraySchema,
321
- mayImportInfrastructure: { type: "boolean" },
322
- optional: { type: "boolean" }
323
- }
324
- },
325
- rule: {
326
- type: "object",
327
- additionalProperties: false,
328
- required: ["from", "to", "allowed"],
329
- properties: {
330
- from: { type: "string", minLength: 1 },
331
- to: { type: "string", minLength: 1 },
332
- allowed: { type: "boolean" },
333
- message: { type: "string", minLength: 1 },
334
- peerIsolation: { type: "boolean" },
335
- sliceFolders: { ...stringArraySchema, minItems: 1 }
336
- }
337
- },
338
- safety: {
339
- type: "object",
340
- additionalProperties: false,
341
- properties: {
342
- maxTsSuppressions: { type: "integer", minimum: 0, default: 0 },
343
- maxAnyCasts: { type: "integer", minimum: 0, default: 0 },
344
- allowInMemory: { type: "boolean", default: false },
345
- allowDisabledPeerIsolation: { type: "boolean", default: false }
346
- }
347
- }
348
- }
349
- };
350
- var ArkConfigValidationError = class extends Error {
351
- issues;
352
- source;
353
- constructor(source, issues) {
354
- super(
355
- `Invalid ArkGate config (${source}):
356
- ${issues.map((issue) => `- ${issue.path}: ${issue.message}`).join("\n")}`
357
- );
358
- this.name = "ArkConfigValidationError";
359
- this.source = source;
360
- this.issues = issues;
361
- }
362
- };
363
- function isObject(value) {
364
- return value !== null && typeof value === "object" && !Array.isArray(value);
365
- }
366
- function propertyPath(parent, key) {
367
- return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? `${parent}.${key}` : `${parent}[${JSON.stringify(key)}]`;
368
- }
369
- function valueType(value) {
370
- if (value === null) return "null";
371
- if (Array.isArray(value)) return "array";
372
- return typeof value;
373
- }
374
- function resolveSchemaRef(ref, root) {
375
- const prefix = "#/$defs/";
376
- if (!ref.startsWith(prefix)) return void 0;
377
- return root.$defs[ref.slice(prefix.length)];
378
- }
379
- function validateNode(value, schema, path2, root, issues) {
380
- if (schema.$ref) {
381
- const referenced = resolveSchemaRef(schema.$ref, root);
382
- if (!referenced) {
383
- issues.push({ path: path2, message: `schema reference ${schema.$ref} cannot be resolved` });
384
- return;
385
- }
386
- validateNode(value, referenced, path2, root, issues);
387
- return;
388
- }
389
- if (schema.const !== void 0 && !Object.is(value, schema.const)) {
390
- issues.push({ path: path2, message: `must equal ${JSON.stringify(schema.const)}` });
391
- return;
392
- }
393
- if (schema.enum && !schema.enum.some((candidate) => Object.is(candidate, value))) {
394
- issues.push({ path: path2, message: `must be one of ${schema.enum.map(String).join(", ")}` });
395
- return;
396
- }
397
- if (schema.type === "object") {
398
- if (!isObject(value)) {
399
- issues.push({ path: path2, message: `must be an object; received ${valueType(value)}` });
400
- return;
401
- }
402
- const properties = schema.properties ?? {};
403
- for (const key of schema.required ?? []) {
404
- if (value[key] === void 0) {
405
- issues.push({ path: propertyPath(path2, key), message: "is required" });
406
- }
407
- }
408
- if (schema.additionalProperties === false) {
409
- for (const key of Object.keys(value)) {
410
- if (!(key in properties)) {
411
- issues.push({ path: propertyPath(path2, key), message: "unknown field" });
412
- }
413
- }
414
- }
415
- for (const [key, childSchema] of Object.entries(properties)) {
416
- if (value[key] !== void 0) {
417
- validateNode(value[key], childSchema, propertyPath(path2, key), root, issues);
418
- }
419
- }
420
- return;
421
- }
422
- if (schema.type === "array") {
423
- if (!Array.isArray(value)) {
424
- issues.push({ path: path2, message: `must be an array; received ${valueType(value)}` });
425
- return;
426
- }
427
- if (schema.minItems !== void 0 && value.length < schema.minItems) {
428
- issues.push({ path: path2, message: `must contain at least ${schema.minItems} item(s)` });
429
- }
430
- if (schema.uniqueItems) {
431
- const serialized = value.map((entry) => JSON.stringify(entry));
432
- if (new Set(serialized).size !== serialized.length) {
433
- issues.push({ path: path2, message: "must not contain duplicate items" });
434
- }
435
- }
436
- if (schema.items) {
437
- value.forEach(
438
- (entry, index) => validateNode(entry, schema.items, `${path2}[${index}]`, root, issues)
439
- );
440
- }
441
- return;
442
- }
443
- if (schema.type === "string") {
444
- if (typeof value !== "string") {
445
- issues.push({ path: path2, message: `must be a string; received ${valueType(value)}` });
446
- return;
447
- }
448
- if (schema.minLength !== void 0 && value.length < schema.minLength) {
449
- issues.push({ path: path2, message: `must contain at least ${schema.minLength} character(s)` });
450
- }
451
- return;
452
- }
453
- if (schema.type === "boolean") {
454
- if (typeof value !== "boolean") {
455
- issues.push({ path: path2, message: `must be a boolean; received ${valueType(value)}` });
456
- }
457
- return;
458
- }
459
- if (schema.type === "integer") {
460
- if (!Number.isInteger(value)) {
461
- issues.push({ path: path2, message: `must be an integer; received ${valueType(value)}` });
462
- return;
463
- }
464
- if (schema.minimum !== void 0 && value < schema.minimum) {
465
- issues.push({ path: path2, message: `must be at least ${schema.minimum}` });
466
- }
467
- }
468
- }
469
- function defaultedConfig(input) {
470
- return {
471
- ...input,
472
- $schema: input.$schema === void 0 ? ARK_CONFIG_SCHEMA_URL : input.$schema,
473
- schemaVersion: input.schemaVersion === void 0 ? ARK_CONFIG_SCHEMA_VERSION : input.schemaVersion,
474
- include: input.include === void 0 ? ["src"] : input.include,
475
- layers: input.layers === void 0 ? [] : input.layers,
476
- rules: input.rules === void 0 ? DEFAULT_ARK_CONFIG_RULES.map((rule) => ({ ...rule })) : input.rules
477
- };
478
- }
479
- function migrateArkConfig(input, source = "ark.config.json") {
480
- if (!isObject(input)) {
481
- throw new ArkConfigValidationError(source, [
482
- { path: "$", message: `must be an object; received ${valueType(input)}` }
483
- ]);
484
- }
485
- const migratedFrom = input.schemaVersion === void 0 ? "unversioned" : null;
486
- if (input.schemaVersion !== void 0 && input.schemaVersion !== ARK_CONFIG_SCHEMA_VERSION) {
487
- throw new ArkConfigValidationError(source, [
488
- {
489
- path: "$.schemaVersion",
490
- message: `unsupported version ${JSON.stringify(input.schemaVersion)}; expected ${ARK_CONFIG_SCHEMA_VERSION}`
491
- }
492
- ]);
493
- }
494
- return { candidate: defaultedConfig(input), migratedFrom };
495
- }
496
- function loadArkConfigContract(input, source = "ark.config.json") {
497
- const { candidate, migratedFrom } = migrateArkConfig(input, source);
498
- const issues = [];
499
- validateNode(
500
- candidate,
501
- ARK_CONFIG_SCHEMA,
502
- "$",
503
- ARK_CONFIG_SCHEMA,
504
- issues
505
- );
506
- if (issues.length > 0) throw new ArkConfigValidationError(source, issues);
507
- return { config: candidate, migratedFrom };
508
- }
509
- function parseArkConfigJson(json, source = "ark.config.json") {
510
- let input;
511
- try {
512
- input = JSON.parse(json);
513
- } catch (error) {
514
- throw new ArkConfigValidationError(source, [
515
- {
516
- path: "$",
517
- message: `invalid JSON: ${error instanceof Error ? error.message : String(error)}`
518
- }
519
- ]);
520
- }
521
- return loadArkConfigContract(input, source);
522
- }
523
-
524
- // src/domain/adapterContract.ts
525
- function text(value) {
526
- return typeof value === "string" && value.length > 0 ? value : void 0;
527
- }
528
- function positiveInteger(value, fallback) {
529
- return Number.isInteger(value) && Number(value) > 0 ? Number(value) : fallback;
530
- }
531
- function toAdapterDiagnostic(violation, fallbackSeverity = "error") {
532
- const ruleId = text(violation.ruleId) ?? text(violation.code) ?? "ARK_UNKNOWN";
533
- const severity = violation.severity === "warning" ? "warning" : fallbackSeverity;
534
- const evidence = {
535
- ...text(violation.target) ? { target: text(violation.target) } : {},
536
- ...text(violation.fromLayer) ? { fromLayer: text(violation.fromLayer) } : {},
537
- ...text(violation.toLayer) ? { toLayer: text(violation.toLayer) } : {},
538
- ...typeof violation.typeOnly === "boolean" ? { typeOnly: violation.typeOnly } : {}
539
- };
540
- return {
541
- ruleId,
542
- severity,
543
- message: text(violation.message) ?? ruleId,
544
- location: {
545
- file: text(violation.file) ?? "<unknown>",
546
- line: positiveInteger(violation.line, 1),
547
- column: positiveInteger(violation.column, 1)
548
- },
549
- evidence
550
- };
551
- }
552
-
553
- // src/domain/sourcePolicy.ts
554
- var SOURCE_POLICY_MESSAGES = {
555
- RAW_EVENT_PUBLISH: "Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",
556
- PUBLISH_MISSING_SOURCE: "Strict Ark publish calls must include metadata.source."
557
- };
558
- function looksLikeArkIntent(value) {
559
- return /^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(
560
- value
561
- );
562
- }
563
- function classifyPublishFacts(facts) {
564
- if (!facts.publishCall) return [];
565
- const findings = [];
566
- if (facts.rawIntentName !== void 0 && looksLikeArkIntent(facts.rawIntentName) || facts.objectHasIntent) {
567
- findings.push({
568
- ruleId: "RAW_EVENT_PUBLISH",
569
- message: SOURCE_POLICY_MESSAGES.RAW_EVENT_PUBLISH
570
- });
571
- }
572
- if (facts.arkPublishCandidate && !facts.hasSource) {
573
- findings.push({
574
- ruleId: "PUBLISH_MISSING_SOURCE",
575
- message: SOURCE_POLICY_MESSAGES.PUBLISH_MISSING_SOURCE
576
- });
577
- }
578
- return findings;
579
- }
580
-
581
- // src/eslint/index.ts
582
- function lintedFilename(context) {
583
- if (typeof context.physicalFilename === "string" && context.physicalFilename.length > 0) {
584
- return context.physicalFilename;
585
- }
586
- if (typeof context.filename === "string" && context.filename.length > 0) {
587
- return context.filename;
588
- }
589
- if (typeof context.getFilename === "function") {
590
- try {
591
- const name = context.getFilename();
592
- if (typeof name === "string" && name.length > 0) return name;
593
- } catch {
594
- }
595
- }
596
- return "";
597
- }
598
- function reportAdapterDiagnostic(context, node, messageId, violation, data) {
599
- const diagnostic = toAdapterDiagnostic({
600
- ...violation,
601
- line: violation.line ?? node.loc?.start?.line,
602
- column: violation.column ?? (typeof node.loc?.start?.column === "number" ? node.loc.start.column + 1 : void 0)
603
- });
604
- context.report({ node, messageId, ...data ? { data } : {}, diagnostic });
605
- return diagnostic;
606
- }
607
- function findConfigPath(startFile) {
608
- if (!startFile || startFile === "<input>" || startFile.startsWith("stdin")) return null;
609
- let dir = import_node_path.default.dirname(import_node_path.default.resolve(startFile));
610
- for (; ; ) {
611
- const candidate = import_node_path.default.join(dir, "ark.config.json");
612
- if (import_node_fs.default.existsSync(candidate)) return candidate;
613
- const parent = import_node_path.default.dirname(dir);
614
- if (parent === dir) return null;
615
- dir = parent;
616
- }
617
- }
618
- var _configCache = /* @__PURE__ */ new Map();
619
- function loadArkConfig(configPath) {
620
- if (_configCache.has(configPath)) return _configCache.get(configPath) ?? null;
621
- if (!import_node_fs.default.existsSync(configPath)) return null;
622
- const config = parseArkConfigJson(import_node_fs.default.readFileSync(configPath, "utf8"), configPath).config;
623
- _configCache.set(configPath, config);
624
- return config;
625
- }
626
- function resolveRelativeImport(fromFile, specifier) {
627
- if (!specifier.startsWith(".")) return null;
628
- const base = import_node_path.default.resolve(import_node_path.default.dirname(fromFile), specifier);
629
- const candidates = [
630
- base,
631
- `${base}.ts`,
632
- `${base}.tsx`,
633
- `${base}.mts`,
634
- `${base}.cts`,
635
- `${base}.js`,
636
- `${base}.jsx`,
637
- import_node_path.default.join(base, "index.ts"),
638
- import_node_path.default.join(base, "index.tsx"),
639
- import_node_path.default.join(base, "index.js")
640
- ];
641
- for (const c of candidates) {
642
- try {
643
- if (import_node_fs.default.existsSync(c) && import_node_fs.default.statSync(c).isFile()) return c;
644
- } catch {
645
- }
646
- }
647
- return `${base}.ts`;
648
- }
649
- function stringValue(node) {
650
- return typeof node?.value === "string" ? node.value : void 0;
651
- }
652
- function propertyName(node) {
653
- return node?.name ?? stringValue(node);
654
- }
655
- function sourceCodeFor(context) {
656
- return context.sourceCode ?? context.getSourceCode?.();
657
- }
658
- function referenceFor(context, node) {
659
- let scope = sourceCodeFor(context)?.getScope?.(node);
660
- while (scope) {
661
- const reference = scope.references?.find((candidate) => candidate.identifier === node);
662
- if (reference) return reference;
663
- scope = scope.upper ?? void 0;
664
- }
665
- return void 0;
666
- }
667
- function isLocallyBound(context, node, name) {
668
- const reference = referenceFor(context, node);
669
- if (reference?.resolved) return (reference.resolved.defs?.length ?? 0) > 0;
670
- let scope = sourceCodeFor(context)?.getScope?.(node);
671
- while (scope) {
672
- const variable = scope.set?.get(name);
673
- if (variable) return (variable.defs?.length ?? 0) > 0;
674
- scope = scope.upper ?? void 0;
675
- }
676
- return false;
677
- }
678
- function isValueIdentifierReference(context, node) {
679
- const reference = referenceFor(context, node);
680
- if (reference) return reference.isValueReference !== false;
681
- return node.parent?.type === "VariableDeclarator" && node.parent.init === node;
682
- }
683
- function memberExpressionPath(node) {
684
- if (node?.type === "Identifier" && node.name) {
685
- return { root: node, segments: [node.name] };
686
- }
687
- if (!node) return void 0;
688
- const memberLike = node.type === "MemberExpression" || Boolean(node.object && node.property);
689
- if (!memberLike || node.computed === true) return void 0;
690
- const base = memberExpressionPath(node.object);
691
- const property = propertyName(node.property);
692
- if (!base || !property) return void 0;
693
- return { root: base.root, segments: [...base.segments, property] };
694
- }
695
- function calleePropertyName(node) {
696
- return propertyName(node.callee?.property);
697
- }
698
- function objectProperty(node, name) {
699
- return node?.properties?.find((property) => propertyName(property.key) === name);
700
- }
701
- function objectHasProperty(node, name) {
702
- return objectProperty(node, name) !== void 0;
703
- }
704
- function objectHasMetadataSource(node) {
705
- const metadata = objectProperty(node, "metadata")?.value;
706
- return objectHasProperty(metadata, "source");
707
- }
708
- function isPublishCall(node) {
709
- return calleePropertyName(node) === "publish";
710
- }
711
- var noDomainInfraImports = {
712
- meta: {
713
- type: "problem",
714
- docs: {
715
- description: "Disallow imports that violate ark.config.json layer rules (same contract as arkgate-check)."
716
- },
717
- messages: {
718
- forbiddenImport: "Architecture: {{fromLayer}} must not import {{toLayer}} (ark.config.json). Specifier: {{specifier}}",
719
- forbiddenImportHeuristic: "Domain code must not import infrastructure, adapters, repositories, or database modules."
720
- },
721
- schema: []
722
- },
723
- create(context) {
724
- const filename = lintedFilename(context);
725
- const configPath = findConfigPath(filename);
726
- const config = configPath ? loadArkConfig(configPath) : null;
727
- const root = configPath ? import_node_path.default.dirname(configPath) : null;
728
- const check = (node) => {
729
- const source = stringValue(node.source);
730
- if (!source) return;
731
- if (config && root && filename) {
732
- const absFile = import_node_path.default.isAbsolute(filename) ? filename : import_node_path.default.resolve(filename);
733
- const relFile = import_node_path.default.relative(root, absFile).split(import_node_path.default.sep).join("/");
734
- const fromLayer = layerForRelativePath(relFile, config.layers);
735
- if (!fromLayer) return;
736
- const targetAbs = resolveRelativeImport(absFile, source);
737
- if (!targetAbs) return;
738
- const relTarget = import_node_path.default.relative(root, targetAbs).split(import_node_path.default.sep).join("/");
739
- if (relTarget.startsWith("..")) return;
740
- const toLayer = layerForRelativePath(relTarget, config.layers);
741
- if (!toLayer) return;
742
- if (isEdgeDenied(config.rules, fromLayer, toLayer, {
743
- fromPath: relFile,
744
- toPath: relTarget,
745
- layers: config.layers
746
- })) {
747
- reportAdapterDiagnostic(
748
- context,
749
- node,
750
- "forbiddenImport",
751
- {
752
- ruleId: "LAYER_IMPORT_VIOLATION",
753
- file: relFile,
754
- fromLayer,
755
- toLayer,
756
- target: relTarget,
757
- ...node.importKind === "type" ? { typeOnly: true } : {},
758
- message: `${fromLayer} must not import ${toLayer}.`
759
- },
760
- { fromLayer, toLayer, specifier: source }
761
- );
762
- }
763
- return;
764
- }
765
- };
766
- return {
767
- ImportDeclaration: check,
768
- ExportNamedDeclaration: check,
769
- ExportAllDeclaration: check
770
- };
771
- }
772
- };
773
- var noRawEventPublish = {
774
- meta: {
775
- type: "problem",
776
- docs: {
777
- description: "Require event bus publish calls to use registered intent creators instead of raw event objects or intent strings."
778
- },
779
- messages: {
780
- rawPublish: "Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts."
781
- },
782
- schema: []
783
- },
784
- create(context) {
785
- return {
786
- CallExpression(node) {
787
- const firstArg = node.arguments?.[0];
788
- const firstValue = stringValue(firstArg);
789
- const findings = classifyPublishFacts({
790
- publishCall: isPublishCall(node),
791
- rawIntentName: firstValue,
792
- objectHasIntent: objectHasProperty(firstArg, "intent"),
793
- arkPublishCandidate: false,
794
- hasSource: true
795
- });
796
- if (findings.some((finding) => finding.ruleId === "RAW_EVENT_PUBLISH")) {
797
- const finding = findings.find((item) => item.ruleId === "RAW_EVENT_PUBLISH");
798
- reportAdapterDiagnostic(context, node, "rawPublish", {
799
- ...finding,
800
- file: lintedFilename(context)
801
- });
802
- }
803
- }
804
- };
805
- }
806
- };
807
- var requirePublishSource = {
808
- meta: {
809
- type: "problem",
810
- docs: {
811
- description: "Require event bus publish calls to include source metadata."
812
- },
813
- messages: {
814
- missingSource: "Strict Ark publish calls must include metadata.source."
815
- },
816
- schema: []
817
- },
818
- create(context) {
819
- return {
820
- CallExpression(node) {
821
- const firstArg = node.arguments?.[0];
822
- const metadataArg = node.arguments?.[2];
823
- const findings = classifyPublishFacts({
824
- publishCall: isPublishCall(node),
825
- rawIntentName: stringValue(firstArg),
826
- objectHasIntent: objectHasProperty(firstArg, "intent"),
827
- arkPublishCandidate: true,
828
- hasSource: objectHasMetadataSource(firstArg) || objectHasProperty(metadataArg, "source")
829
- });
830
- const finding = findings.find((item) => item.ruleId === "PUBLISH_MISSING_SOURCE");
831
- if (finding) {
832
- reportAdapterDiagnostic(context, node, "missingSource", {
833
- ...finding,
834
- file: lintedFilename(context)
835
- });
836
- }
837
- }
838
- };
839
- }
840
- };
841
- var noForbiddenGlobals = {
842
- meta: {
843
- type: "problem",
844
- docs: {
845
- description: "Disallow ambient globals from the layer\u2019s forbiddenGlobals in ark.config.json (same purity surface as ark-check). Option `globals` explicitly overrides."
846
- },
847
- messages: {
848
- forbiddenGlobal: 'Ambient global "{{name}}" is forbidden in {{layer}} (ark.config.json); inject the capability through a port instead.',
849
- forbiddenGlobalDefault: 'Ambient global "{{name}}" is forbidden here; inject the capability through a port instead.'
850
- },
851
- schema: [
852
- {
853
- type: "object",
854
- properties: {
855
- globals: { type: "array", items: { type: "string" } }
856
- },
857
- additionalProperties: false
858
- }
859
- ]
860
- },
861
- create(context) {
862
- const filename = lintedFilename(context);
863
- const option = context.options?.[0];
864
- const configPath = findConfigPath(filename);
865
- const config = configPath ? loadArkConfig(configPath) : null;
866
- const root = configPath ? import_node_path.default.dirname(configPath) : null;
867
- let globals = null;
868
- let layerName = "this layer";
869
- if (option?.globals) {
870
- globals = new Set(option.globals);
871
- } else if (config && root && filename) {
872
- const absFile = import_node_path.default.isAbsolute(filename) ? filename : import_node_path.default.resolve(filename);
873
- const relFile = import_node_path.default.relative(root, absFile).split(import_node_path.default.sep).join("/");
874
- const layer = config.layers?.find(
875
- (l) => l.name === layerForRelativePath(relFile, config.layers)
876
- );
877
- if (layer?.forbiddenGlobals?.length) {
878
- globals = new Set(layer.forbiddenGlobals);
879
- layerName = layer.name;
880
- } else {
881
- globals = null;
882
- }
883
- }
884
- if (!globals) {
885
- return {};
886
- }
887
- const scopeAware = typeof sourceCodeFor(context)?.getScope === "function";
888
- const report = (node, name) => {
889
- const absFile = import_node_path.default.isAbsolute(filename) ? filename : import_node_path.default.resolve(filename);
890
- const reportFile = root ? import_node_path.default.relative(root, absFile).split(import_node_path.default.sep).join("/") : filename;
891
- reportAdapterDiagnostic(
892
- context,
893
- node,
894
- config ? "forbiddenGlobal" : "forbiddenGlobalDefault",
895
- {
896
- ruleId: "FORBIDDEN_GLOBAL",
897
- file: reportFile,
898
- fromLayer: layerName,
899
- target: name,
900
- message: `${layerName} must not use the ambient global "${name}".`
901
- },
902
- { name, layer: layerName }
903
- );
904
- };
905
- return {
906
- MemberExpression(node) {
907
- if (node.parent?.type === "MemberExpression" && node.parent.object === node) return;
908
- const path2 = memberExpressionPath(node);
909
- if (!path2 || isLocallyBound(context, path2.root, path2.segments[0])) return;
910
- const explicitGlobalThis = path2.segments[0] === "globalThis";
911
- const normalized = explicitGlobalThis ? path2.segments.slice(1) : path2.segments;
912
- let match;
913
- for (let length = normalized.length; length >= (explicitGlobalThis ? 1 : 2); length -= 1) {
914
- const candidate = normalized.slice(0, length).join(".");
915
- if (globals.has(candidate)) {
916
- match = candidate;
917
- break;
918
- }
919
- }
920
- if (match) report(node, match);
921
- else if (!scopeAware && globals.has(path2.segments[0])) {
922
- report(node, path2.segments[0]);
923
- }
924
- },
925
- CallExpression(node) {
926
- if (scopeAware) return;
927
- const callee = node.callee?.type === "Identifier" ? node.callee.name : void 0;
928
- if (callee && globals.has(callee)) report(node, callee);
929
- },
930
- NewExpression(node) {
931
- if (scopeAware) return;
932
- const callee = node.callee?.type === "Identifier" ? node.callee.name : void 0;
933
- if (callee && globals.has(callee)) report(node, callee);
934
- },
935
- Identifier(node) {
936
- if (!scopeAware || !node.name || !globals.has(node.name) || !isValueIdentifierReference(context, node) || isLocallyBound(context, node, node.name)) {
937
- return;
938
- }
939
- report(node, node.name);
940
- }
941
- };
942
- }
943
- };
944
- var rules = {
945
- "no-domain-infra-imports": noDomainInfraImports,
946
- "no-raw-event-publish": noRawEventPublish,
947
- "require-publish-source": requirePublishSource,
948
- "no-forbidden-globals": noForbiddenGlobals
949
- };
950
- var plugin = { rules };
951
- plugin.configs = {
952
- recommended: {
953
- plugins: { ark: plugin },
954
- rules: {
955
- "ark/no-domain-infra-imports": "error",
956
- "ark/no-raw-event-publish": "error",
957
- "ark/require-publish-source": "error",
958
- "ark/no-forbidden-globals": "error"
959
- }
960
- }
961
- };
962
- var eslint_default = plugin;
963
- // Annotate the CommonJS export names for ESM import in node:
964
- 0 && (module.exports = {
965
- findConfigPath,
966
- globToRegExp,
967
- isEdgeDenied,
968
- layerForRelativePath,
969
- loadArkConfig,
970
- noDomainInfraImports,
971
- noForbiddenGlobals,
972
- noRawEventPublish,
973
- patternSpecificity,
974
- plugin,
975
- requirePublishSource,
976
- resolveRelativeImport
977
- });
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});