@domain-first/project-structure 4.0.0 → 4.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.
package/dist/lint.cjs ADDED
@@ -0,0 +1,864 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __webpack_require__ = {};
4
+ (()=>{
5
+ __webpack_require__.n = (module)=>{
6
+ var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
7
+ __webpack_require__.d(getter, {
8
+ a: getter
9
+ });
10
+ return getter;
11
+ };
12
+ })();
13
+ (()=>{
14
+ __webpack_require__.d = (exports1, getters, values)=>{
15
+ var define = (defs, kind)=>{
16
+ for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
17
+ enumerable: true,
18
+ [kind]: defs[key]
19
+ });
20
+ };
21
+ define(getters, "get");
22
+ define(values, "value");
23
+ };
24
+ })();
25
+ (()=>{
26
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
27
+ })();
28
+ var __webpack_exports__ = {};
29
+ const external_node_util_namespaceObject = require("node:util");
30
+ const external_node_path_namespaceObject = require("node:path");
31
+ var external_node_path_default = /*#__PURE__*/ __webpack_require__.n(external_node_path_namespaceObject);
32
+ const external_zod_namespaceObject = require("zod");
33
+ var external_zod_default = /*#__PURE__*/ __webpack_require__.n(external_zod_namespaceObject);
34
+ const moduleKinds = [
35
+ 'repositories',
36
+ 'domain-services',
37
+ 'application-ports',
38
+ 'application-services',
39
+ 'use-cases',
40
+ 'execution-commands',
41
+ 'execution-queries',
42
+ 'orchestration-commands',
43
+ 'orchestration-queries',
44
+ 'infrastructure-services',
45
+ 'presentation-services'
46
+ ];
47
+ const domain = [
48
+ 'repositories',
49
+ 'domain-services'
50
+ ];
51
+ const commandsAndQueries = [
52
+ 'execution-commands',
53
+ 'execution-queries',
54
+ 'orchestration-commands',
55
+ 'orchestration-queries'
56
+ ];
57
+ const infrastructure = [
58
+ ...domain,
59
+ 'application-ports',
60
+ 'infrastructure-services'
61
+ ];
62
+ const defaultDependencies = {
63
+ 'domain-services': domain,
64
+ repositories: [
65
+ 'domain-services',
66
+ 'application-ports',
67
+ 'infrastructure-services'
68
+ ],
69
+ 'application-ports': infrastructure,
70
+ 'application-services': [
71
+ ...domain,
72
+ 'application-ports'
73
+ ],
74
+ 'use-cases': [
75
+ ...domain,
76
+ 'application-ports',
77
+ 'application-services',
78
+ ...commandsAndQueries
79
+ ],
80
+ 'execution-commands': infrastructure,
81
+ 'execution-queries': infrastructure,
82
+ 'orchestration-commands': [
83
+ ...domain,
84
+ 'execution-commands',
85
+ 'execution-queries'
86
+ ],
87
+ 'orchestration-queries': [
88
+ ...domain,
89
+ 'execution-queries'
90
+ ],
91
+ 'infrastructure-services': infrastructure,
92
+ 'presentation-services': [
93
+ 'application-ports',
94
+ 'application-services',
95
+ 'use-cases',
96
+ ...commandsAndQueries,
97
+ 'presentation-services'
98
+ ]
99
+ };
100
+ const kindSchema = external_zod_default()["enum"](moduleKinds);
101
+ const dependencyRulesSchema = external_zod_default().partialRecord(kindSchema, external_zod_default().union([
102
+ external_zod_default().array(kindSchema),
103
+ external_zod_default().object({
104
+ add: external_zod_default().array(kindSchema).optional(),
105
+ remove: external_zod_default().array(kindSchema).optional()
106
+ })
107
+ ]));
108
+ const resolveDependencyRules = (config = {})=>{
109
+ const entries = moduleKinds.map((kind)=>{
110
+ const override = config[kind];
111
+ if (Array.isArray(override)) return [
112
+ kind,
113
+ new Set(override)
114
+ ];
115
+ const kinds = new Set([
116
+ ...defaultDependencies[kind],
117
+ ...override?.add ?? []
118
+ ]);
119
+ for (const removed of override?.remove ?? [])kinds.delete(removed);
120
+ return [
121
+ kind,
122
+ kinds
123
+ ];
124
+ });
125
+ return Object.fromEntries(entries);
126
+ };
127
+ const defaultDependencyRules = resolveDependencyRules();
128
+ const isModuleKind = (value)=>moduleKinds.includes(value);
129
+ const wiredModuleKind = (wiringKind, typeFile)=>{
130
+ const kind = 'commands' === wiringKind || 'queries' === wiringKind ? `${'execution' === external_node_path_default().basename(external_node_path_default().dirname(typeFile)) ? 'execution' : 'orchestration'}-${wiringKind}` : wiringKind;
131
+ return isModuleKind(kind) ? kind : void 0;
132
+ };
133
+ const fileModuleKind = (segments)=>{
134
+ const [layer, folder, mode] = segments;
135
+ const file = segments.at(-1) ?? '';
136
+ if (/^index(\.tsx?)?$/.test(file)) return;
137
+ if ('domain' === layer) {
138
+ if ('services' === folder) return 'domain-services';
139
+ return 'aggregates' === folder && /-repository(\.tsx?)?$/.test(file) ? 'repositories' : void 0;
140
+ }
141
+ if ('application' === layer) {
142
+ if ('commands' === folder || 'queries' === folder) return 'execution' === mode || 'orchestration' === mode ? `${mode}-${folder}` : void 0;
143
+ return ({
144
+ ports: 'application-ports',
145
+ services: 'application-services',
146
+ 'use-cases': 'use-cases'
147
+ })[folder];
148
+ }
149
+ if ('infrastructure' === layer) return ({
150
+ repositories: 'repositories',
151
+ commands: 'execution-commands',
152
+ queries: 'execution-queries',
153
+ 'application-adapters': 'application-ports',
154
+ services: 'infrastructure-services'
155
+ })[folder];
156
+ return 'presentation' === layer && 'services' === folder ? 'presentation-services' : void 0;
157
+ };
158
+ const external_node_fs_namespaceObject = require("node:fs");
159
+ var external_node_fs_default = /*#__PURE__*/ __webpack_require__.n(external_node_fs_namespaceObject);
160
+ const pendingFiles = new Map();
161
+ new Set();
162
+ const pendingMoves = new Map();
163
+ const pendingDeletions = new Map();
164
+ class FileSystemItem {
165
+ path;
166
+ constructor(path){
167
+ this.path = path;
168
+ }
169
+ subitem = (relativePath)=>new this.constructor(external_node_path_default().resolve(this.path, ...relativePath));
170
+ get exists() {
171
+ return external_node_fs_default().existsSync(this.path);
172
+ }
173
+ }
174
+ class file_system_File extends FileSystemItem {
175
+ get exists() {
176
+ return pendingFiles.has(this.path) || pendingMoves.has(this.path) || external_node_fs_default().existsSync(this.path) && !pendingDeletions.has(this.path);
177
+ }
178
+ delete = (stopAt)=>{
179
+ pendingDeletions.set(this.path, stopAt);
180
+ };
181
+ moveTo = (targetPath, stopAt)=>{
182
+ pendingMoves.set(targetPath, {
183
+ sourcePath: this.path,
184
+ stopAt
185
+ });
186
+ };
187
+ get data() {
188
+ const pendingFile = pendingFiles.get(this.path);
189
+ if (pendingFile) return pendingFile.content;
190
+ if (!this.exists) throw new Error('File does not exist');
191
+ return external_node_fs_default().readFileSync(this.path, 'utf-8');
192
+ }
193
+ set data(content) {
194
+ pendingFiles.set(this.path, {
195
+ content,
196
+ replacesFile: true
197
+ });
198
+ }
199
+ update = (content)=>{
200
+ pendingFiles.set(this.path, {
201
+ content,
202
+ replacesFile: pendingFiles.get(this.path)?.replacesFile ?? false
203
+ });
204
+ };
205
+ addLine = (newLine, separator = '\n')=>{
206
+ const content = this.exists ? this.data : '';
207
+ pendingFiles.set(this.path, {
208
+ content: [
209
+ content.trim(),
210
+ newLine.trim()
211
+ ].filter((x)=>!!x).join(separator),
212
+ replacesFile: pendingFiles.get(this.path)?.replacesFile ?? false
213
+ });
214
+ };
215
+ addLineIfMissing = (newLine, separator = '\n')=>{
216
+ const alreadyAdded = this.exists && this.data.split('\n').some((line)=>line.trim() === newLine.trim());
217
+ if (!alreadyAdded) this.addLine(newLine, separator);
218
+ };
219
+ }
220
+ class ProjectRoot {
221
+ path;
222
+ constructor(){
223
+ let dir = process.cwd();
224
+ while(dir !== external_node_path_default().parse(dir).root){
225
+ if (external_node_fs_default().existsSync(external_node_path_default().join(dir, 'package.json'))) {
226
+ this.path = dir;
227
+ return;
228
+ }
229
+ dir = external_node_path_default().dirname(dir);
230
+ }
231
+ throw new Error('No package.json was found');
232
+ }
233
+ }
234
+ const lintChecks = [
235
+ 'context-isolation',
236
+ 'shared-layer',
237
+ 'layers',
238
+ 'dependencies',
239
+ 'react',
240
+ 'clock'
241
+ ];
242
+ const configFileName = 'domain-first.project-structure.config.json';
243
+ const configSchema = external_zod_default().object({
244
+ rootFolder: external_zod_default().string(),
245
+ domainFirstPackages: external_zod_default().array(external_zod_default()["enum"]([
246
+ '@domain-first/types',
247
+ '@domain-first/errors',
248
+ '@domain-first/handlers',
249
+ '@domain-first/wire',
250
+ '@domain-first/handlers-rest'
251
+ ])),
252
+ defaultPersistenceLayerImplementation: external_zod_default().string(),
253
+ withInMemoryDb: external_zod_default().boolean().optional(),
254
+ useReact: external_zod_default().boolean(),
255
+ storybookFramework: external_zod_default().string().optional(),
256
+ testingLibrary: external_zod_default().string().optional(),
257
+ rules: external_zod_default().object({
258
+ dependencies: dependencyRulesSchema.optional(),
259
+ lint: external_zod_default().partialRecord(external_zod_default()["enum"](lintChecks), external_zod_default().boolean()).optional()
260
+ }).optional()
261
+ });
262
+ class ConfigFile {
263
+ data;
264
+ constructor(){
265
+ const filePath = ConfigFile.path;
266
+ const file = new file_system_File(filePath);
267
+ const configObject = JSON.parse(file.data);
268
+ this.data = configSchema.parse(configObject);
269
+ }
270
+ static get Instance() {
271
+ return new ConfigFile();
272
+ }
273
+ static get path() {
274
+ const { path: root } = new ProjectRoot();
275
+ return external_node_path_default().resolve(root, configFileName);
276
+ }
277
+ static get exists() {
278
+ return new file_system_File(ConfigFile.path).exists;
279
+ }
280
+ static write = (config)=>{
281
+ new file_system_File(ConfigFile.path).data = JSON.stringify(config, null, '\t');
282
+ };
283
+ }
284
+ const config_file_configuredDependencyRules = ()=>resolveDependencyRules(ConfigFile.exists ? ConfigFile.Instance.data.rules?.dependencies : void 0);
285
+ const external_node_module_namespaceObject = require("node:module");
286
+ const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
287
+ const resolveExtends = (fromFile, target)=>{
288
+ if (target.startsWith('.') || external_node_path_default().isAbsolute(target)) {
289
+ const resolved = external_node_path_default().resolve(external_node_path_default().dirname(fromFile), target);
290
+ return resolved.endsWith('.json') ? resolved : `${resolved}.json`;
291
+ }
292
+ const require1 = (0, external_node_module_namespaceObject.createRequire)(fromFile);
293
+ for (const candidate of [
294
+ target,
295
+ `${target}/tsconfig.json`
296
+ ])try {
297
+ return require1.resolve(candidate);
298
+ } catch {}
299
+ };
300
+ const compilerOption = (configFile, name, seen = new Set())=>{
301
+ if (seen.has(configFile) || !external_node_fs_default().existsSync(configFile)) return null;
302
+ seen.add(configFile);
303
+ let config;
304
+ try {
305
+ config = JSON.parse(stripJsonComments(external_node_fs_default().readFileSync(configFile, 'utf8')));
306
+ } catch {
307
+ return null;
308
+ }
309
+ if (config.compilerOptions && name in config.compilerOptions) return config.compilerOptions[name];
310
+ const parents = [
311
+ config.extends ?? []
312
+ ].flat().reverse();
313
+ for (const parent of parents){
314
+ const parentFile = resolveExtends(configFile, parent);
315
+ const value = parentFile ? compilerOption(parentFile, name, seen) : null;
316
+ if (void 0 !== value) return value;
317
+ }
318
+ };
319
+ class UnknownFormatNaming {
320
+ rawSource;
321
+ camelCase;
322
+ PascalCase;
323
+ constructor(rawSource){
324
+ this.rawSource = rawSource;
325
+ const source = rawSource.trim();
326
+ if (!source.includes('-')) {
327
+ this.camelCase = source.substring(0, 1).toLowerCase() + source.substring(1);
328
+ this.PascalCase = source.substring(0, 1).toUpperCase() + source.substring(1);
329
+ }
330
+ const words = source.split('-').filter((word)=>!!word);
331
+ this.camelCase = words.map((word, index)=>0 === index ? word.toLowerCase() : word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
332
+ this.PascalCase = words.map((word)=>word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
333
+ }
334
+ get fileName() {
335
+ return this.rawSource;
336
+ }
337
+ get variableName() {
338
+ return this.camelCase;
339
+ }
340
+ get ClassName() {
341
+ return this.PascalCase;
342
+ }
343
+ get withSpaces() {
344
+ return this.fileName.replaceAll('-', ' ');
345
+ }
346
+ }
347
+ const wiring_layers = [
348
+ 'domain',
349
+ 'application',
350
+ 'infrastructure',
351
+ 'presentation'
352
+ ];
353
+ const visibleLayers = {
354
+ domain: [
355
+ 'domain'
356
+ ],
357
+ application: [
358
+ 'domain',
359
+ 'application'
360
+ ],
361
+ infrastructure: [
362
+ 'domain',
363
+ 'application',
364
+ 'infrastructure'
365
+ ],
366
+ presentation: [
367
+ 'application',
368
+ 'presentation'
369
+ ]
370
+ };
371
+ const branchedTypeFiles = {
372
+ repositories: (fileBase)=>[
373
+ 'domain',
374
+ 'aggregates',
375
+ fileBase.replace(/-repository$/, ''),
376
+ `${fileBase}.ts`
377
+ ],
378
+ commands: (fileBase)=>[
379
+ 'application',
380
+ 'commands',
381
+ 'execution',
382
+ `${fileBase}.ts`
383
+ ],
384
+ queries: (fileBase)=>[
385
+ 'application',
386
+ 'queries',
387
+ 'execution',
388
+ `${fileBase}.ts`
389
+ ],
390
+ 'application-ports': (fileBase)=>[
391
+ 'application',
392
+ 'ports',
393
+ `${fileBase}.ts`
394
+ ]
395
+ };
396
+ const layerOf = (file, contextPath)=>{
397
+ const [firstSegment] = external_node_path_default().relative(contextPath, file).split(external_node_path_default().sep);
398
+ return wiring_layers.find((layer)=>layer === firstSegment);
399
+ };
400
+ const namedImports = (source, fromFile)=>{
401
+ const result = new Map();
402
+ for (const [, names, importPath] of source.matchAll(/import\s*(?:type\s*)?\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g))for (const name of names.split(',')){
403
+ const cleanName = name.replace(/^\s*type\s+/, '').trim();
404
+ if (cleanName) result.set(cleanName, `${external_node_path_default().resolve(external_node_path_default().dirname(fromFile), importPath)}.ts`);
405
+ }
406
+ return result;
407
+ };
408
+ const isEndpointWire = (wiringRelativePath)=>wiringRelativePath.startsWith([
409
+ 'presentation',
410
+ 'rest'
411
+ ].join(external_node_path_default().sep));
412
+ const wireClassDefinitions = (source)=>[
413
+ ...codeOnly(source).matchAll(/(?:export\s+)?const\s+(\w+)\s*=\s*(?:\w+\(\s*)*wireClass\(\s*(\w+)\s*,/g)
414
+ ].map(([, wireName, className])=>({
415
+ wireName,
416
+ className
417
+ }));
418
+ const wiredClassNames = (source, wireName, initializerStart, branched)=>{
419
+ const definitions = wireClassDefinitions(source);
420
+ if (!branched) return definitions.filter((x)=>x.wireName === wireName).map((x)=>x.className);
421
+ const openIndex = source.indexOf('(', initializerStart);
422
+ const branches = codeOnly(source).slice(openIndex, closingIndex(source, openIndex));
423
+ const referenced = new Set(branches.match(/\w+/g));
424
+ return definitions.filter((x)=>referenced.has(x.wireName)).map((x)=>x.className);
425
+ };
426
+ const readWiredModule = (wireFile, contextPath)=>{
427
+ const wiringRelativePath = external_node_path_default().relative(external_node_path_default().join(contextPath, 'wiring'), wireFile);
428
+ if (isEndpointWire(wiringRelativePath)) return;
429
+ const source = new file_system_File(wireFile).data;
430
+ const wireName = `wire${new UnknownFormatNaming(external_node_path_default().basename(wireFile, '.ts').replace(/^wire-/, '')).ClassName}`;
431
+ const exportMatch = new RegExp(`export\\s+const\\s+${wireName}\\s*=\\s*`).exec(source);
432
+ if (!exportMatch) return;
433
+ const branched = source.slice(exportMatch.index + exportMatch[0].length).startsWith('envBranchedWire(');
434
+ const imports = namedImports(source, wireFile);
435
+ const implementations = wiredClassNames(source, wireName, exportMatch.index + exportMatch[0].length, branched).flatMap((className)=>{
436
+ const file = imports.get(className);
437
+ return file ? [
438
+ {
439
+ className,
440
+ file
441
+ }
442
+ ] : [];
443
+ });
444
+ if (!implementations.length) return;
445
+ const typeName = wireName.slice(4);
446
+ const [wiringFolder] = wiringRelativePath.split(external_node_path_default().sep);
447
+ const typeFileSegments = branchedTypeFiles[wiringFolder]?.(external_node_path_default().basename(wireFile, '.ts').replace(/^wire-/, ''));
448
+ const typeFile = branched ? typeFileSegments && external_node_path_default().join(contextPath, ...typeFileSegments) : implementations[0].file;
449
+ const layer = typeFile && layerOf(typeFile, contextPath);
450
+ const implementationsLayer = layerOf(implementations[0].file, contextPath);
451
+ if (!typeFile || !layer || !implementationsLayer) return;
452
+ return {
453
+ wireName,
454
+ typeName,
455
+ wireFile,
456
+ typeFile,
457
+ layer,
458
+ implementations,
459
+ branched,
460
+ implementationsLayer,
461
+ kind: wiringFolder
462
+ };
463
+ };
464
+ const findWiredModules = (contextPath)=>{
465
+ const result = [];
466
+ const walk = (folderPath)=>{
467
+ if (!external_node_fs_default().existsSync(folderPath)) return;
468
+ for (const entry of external_node_fs_default().readdirSync(folderPath, {
469
+ withFileTypes: true
470
+ })){
471
+ const entryPath = external_node_path_default().join(folderPath, entry.name);
472
+ if (entry.isDirectory()) walk(entryPath);
473
+ else if (/^wire-.*(?<!\.spec)\.ts$/.test(entry.name)) {
474
+ const wiredModule = readWiredModule(entryPath, contextPath);
475
+ if (wiredModule) result.push(wiredModule);
476
+ }
477
+ }
478
+ };
479
+ walk(external_node_path_default().join(contextPath, 'wiring'));
480
+ return result.sort((a, b)=>a.typeName.localeCompare(b.typeName));
481
+ };
482
+ const moduleKindOf = (module)=>wiredModuleKind(module.kind, module.typeFile);
483
+ const wiring_layerRule = (consumer, candidate)=>visibleLayers[consumer.implementationsLayer].includes(candidate.layer) && ('infrastructure' !== consumer.implementationsLayer || 'application' !== candidate.layer || 'application-ports' === candidate.kind);
484
+ const canDependOn = (consumer, candidate, rules = defaultDependencyRules)=>{
485
+ const consumerKind = moduleKindOf(consumer);
486
+ const candidateKind = moduleKindOf(candidate);
487
+ return consumerKind && candidateKind ? rules[consumerKind].has(candidateKind) : wiring_layerRule(consumer, candidate);
488
+ };
489
+ const codeOnly = (source)=>{
490
+ let result = '';
491
+ let index = 0;
492
+ const blank = (text)=>text.replace(/[^\n]/g, ' ');
493
+ while(index < source.length){
494
+ const pair = source.slice(index, index + 2);
495
+ const char = source[index];
496
+ let end = index + 1;
497
+ if ('//' === pair) {
498
+ const lineEnd = source.indexOf('\n', index);
499
+ end = -1 === lineEnd ? source.length : lineEnd;
500
+ result += blank(source.slice(index, end));
501
+ } else if ('/*' === pair) {
502
+ const commentEnd = source.indexOf('*/', index + 2);
503
+ end = -1 === commentEnd ? source.length : commentEnd + 2;
504
+ result += blank(source.slice(index, end));
505
+ } else if ('=>' === pair) {
506
+ end = index + 2;
507
+ result += ' ';
508
+ } else if ("'" === char || '"' === char || '`' === char) {
509
+ while(end < source.length && source[end] !== char)end += '\\' === source[end] ? 2 : 1;
510
+ end = Math.min(end + 1, source.length);
511
+ result += char + blank(source.slice(index + 1, end - 1));
512
+ result += end - 1 > index ? source[end - 1] : '';
513
+ } else result += char;
514
+ index = end;
515
+ }
516
+ return result;
517
+ };
518
+ const brackets = {
519
+ '(': ')',
520
+ '[': ']',
521
+ '{': '}',
522
+ '<': '>'
523
+ };
524
+ const closingIndex = (source, openIndex)=>{
525
+ const code = codeOnly(source);
526
+ let depth = 0;
527
+ for(let index = openIndex; index < code.length; index++){
528
+ const char = code[index];
529
+ if (char === code[openIndex]) depth++;
530
+ else if (char === brackets[code[openIndex]]) {
531
+ depth--;
532
+ if (0 === depth) return index;
533
+ }
534
+ }
535
+ return -1;
536
+ };
537
+ const splitTopLevel = (content)=>{
538
+ const code = codeOnly(content);
539
+ const items = [];
540
+ let depth = 0;
541
+ let itemStart = 0;
542
+ for(let index = 0; index <= code.length; index++){
543
+ const char = code[index];
544
+ if (void 0 !== char && char in brackets) depth++;
545
+ else if (Object.values(brackets).includes(char)) depth--;
546
+ if (index === code.length || ',' === char && 0 === depth) {
547
+ const item = content.slice(itemStart, index);
548
+ const itemCode = code.slice(itemStart, index);
549
+ const first = itemCode.search(/\S/);
550
+ const last = itemCode.search(/\S\s*$/);
551
+ if (-1 !== first) items.push(item.slice(first, last + 1));
552
+ itemStart = index + 1;
553
+ }
554
+ }
555
+ return items;
556
+ };
557
+ const wireListRange = (source, className)=>{
558
+ const match = new RegExp(`wireClass\\(\\s*${className}\\s*,\\s*\\[`).exec(codeOnly(source));
559
+ if (!match) throw new Error(`wireClass(${className}, [...]) not found`);
560
+ const openIndex = match.index + match[0].length - 1;
561
+ return {
562
+ openIndex,
563
+ closeIndex: closingIndex(source, openIndex)
564
+ };
565
+ };
566
+ const wiredDependencyNames = (source, className)=>{
567
+ const { openIndex, closeIndex } = wireListRange(source, className);
568
+ return splitTopLevel(source.slice(openIndex + 1, closeIndex));
569
+ };
570
+ const readAliases = (projectRoot)=>{
571
+ const tsconfig = external_node_path_default().join(projectRoot, 'tsconfig.json');
572
+ const paths = compilerOption(tsconfig, 'paths');
573
+ if (!paths || 'object' != typeof paths) return [];
574
+ const baseUrl = compilerOption(tsconfig, 'baseUrl');
575
+ const base = external_node_path_default().resolve(projectRoot, 'string' == typeof baseUrl ? baseUrl : '.');
576
+ return Object.entries(paths).filter(([, targets])=>targets.length).map(([key, [target]])=>{
577
+ const wildcard = key.endsWith('*');
578
+ return {
579
+ prefix: wildcard ? key.slice(0, -1) : key,
580
+ wildcard,
581
+ target: external_node_path_default().resolve(base, wildcard ? target.replace(/\*$/, '') : target)
582
+ };
583
+ }).sort((a, b)=>b.prefix.length - a.prefix.length);
584
+ };
585
+ const resolveSpecifier = (specifier, fromFile, aliases)=>{
586
+ if (specifier.startsWith('.')) return external_node_path_default().resolve(external_node_path_default().dirname(fromFile), specifier);
587
+ for (const { prefix, wildcard, target } of aliases)if (wildcard ? specifier.startsWith(prefix) : specifier === prefix) return external_node_path_default().join(target, wildcard ? specifier.slice(prefix.length) : '');
588
+ };
589
+ const inside = (folder, file)=>{
590
+ const relativePath = external_node_path_default().relative(folder, file);
591
+ return !relativePath || relativePath.startsWith('..') || external_node_path_default().isAbsolute(relativePath) ? void 0 : relativePath.split(external_node_path_default().sep);
592
+ };
593
+ const sourceFiles = (folder)=>{
594
+ if (!external_node_fs_default().existsSync(folder)) return [];
595
+ return external_node_fs_default().readdirSync(folder, {
596
+ withFileTypes: true
597
+ }).flatMap((entry)=>{
598
+ const entryPath = external_node_path_default().join(folder, entry.name);
599
+ if (entry.isDirectory()) return 'node_modules' === entry.name ? [] : sourceFiles(entryPath);
600
+ return /\.(c|m)?tsx?$/.test(entry.name) && !entry.name.endsWith('.d.ts') ? [
601
+ entryPath
602
+ ] : [];
603
+ });
604
+ };
605
+ const importPattern = /\b(?:(import|export)\s+(type\s+)?(?:(?!\b(?:import|export)\b)[\w*{}\s,$])*?\s*from\s*|import\s*\(\s*|require\s*\(\s*|import\s*)(['"])([^'"\n]+)\3/g;
606
+ const lineAt = (source, index)=>source.slice(0, index).split('\n').length;
607
+ const importsOf = (source, file, aliases)=>[
608
+ ...source.matchAll(importPattern)
609
+ ].map((match)=>({
610
+ typeOnly: 'import' === match[1] && Boolean(match[2]),
611
+ target: resolveSpecifier(match[4], file, aliases),
612
+ line: lineAt(source, match.index),
613
+ statement: match[0].replace(/\s+/g, ' ')
614
+ }));
615
+ const isSpec = (file)=>/\.(spec|test)\.(c|m)?tsx?$/.test(file);
616
+ const layerImportRules = {
617
+ domain: {
618
+ allows: ([layer])=>'domain' === layer,
619
+ rule: 'domain imports outside the domain layer:'
620
+ },
621
+ application: {
622
+ allows: ([layer])=>'domain' === layer || 'application' === layer,
623
+ rule: 'application imports outside domain and application:'
624
+ },
625
+ infrastructure: {
626
+ allows: ([layer, part, mode])=>'domain' === layer || 'infrastructure' === layer || 'application' === layer && ('ports' === part || ('commands' === part || 'queries' === part) && 'execution' === mode),
627
+ rule: 'infrastructure imports outside domain, infrastructure, application ports and execution contracts:'
628
+ },
629
+ presentation: {
630
+ allows: ([layer])=>'infrastructure' !== layer,
631
+ rule: 'presentation imports infrastructure (only wiring knows concrete classes):'
632
+ }
633
+ };
634
+ const baseName = (file)=>external_node_path_default().basename(file).replace(/\.[^.]+$/, '');
635
+ const isOwnContract = (file, target)=>baseName(file).endsWith(`-${baseName(target)}`);
636
+ const importViolations = (projectRoot, rootFolder, rules)=>{
637
+ const root = external_node_path_default().resolve(projectRoot, rootFolder);
638
+ const contextsFolder = external_node_path_default().join(root, 'bounded-contexts');
639
+ const sharedFolder = external_node_path_default().join(root, 'shared');
640
+ const reactFolder = external_node_path_default().join(root, 'presentation', 'react');
641
+ const uiKitFolder = external_node_path_default().join(reactFolder, 'ui-kit');
642
+ const widgetsFolder = external_node_path_default().join(reactFolder, 'widgets');
643
+ const hooksFolder = external_node_path_default().join(reactFolder, 'hooks');
644
+ const inMemoryDbFile = external_node_path_default().join(sharedFolder, 'infrastructure', 'services', 'in-memory-db-infrastructure-service.ts');
645
+ const aliases = readAliases(projectRoot);
646
+ const violations = [];
647
+ const locate = (file)=>{
648
+ const inContext = inside(contextsFolder, file);
649
+ if (inContext && inContext.length > 1) {
650
+ const [owner, ...segments] = inContext;
651
+ return {
652
+ owner,
653
+ segments
654
+ };
655
+ }
656
+ const inShared = inside(sharedFolder, file);
657
+ return inShared && {
658
+ owner: 'shared',
659
+ segments: inShared
660
+ };
661
+ };
662
+ const isDomainModel = ([layer, part], target)=>'domain' === layer && [
663
+ 'aggregates',
664
+ 'entities',
665
+ 'value-objects'
666
+ ].includes(part) && !/-repository(\.tsx?)?$/.test(external_node_path_default().basename(target));
667
+ const widgetFolders = new Map();
668
+ const isWidgetFolder = (folder)=>{
669
+ if (!widgetFolders.has(folder)) widgetFolders.set(folder, external_node_fs_default().existsSync(folder) && external_node_fs_default().statSync(folder).isDirectory() && external_node_fs_default().readdirSync(folder).some((name)=>name.endsWith('-widget.tsx')));
670
+ return widgetFolders.get(folder);
671
+ };
672
+ const widgetOf = (file)=>{
673
+ for(let folder = file; inside(widgetsFolder, folder); folder = external_node_path_default().dirname(folder))if (isWidgetFolder(folder)) return folder;
674
+ };
675
+ const files = [
676
+ contextsFolder,
677
+ sharedFolder,
678
+ reactFolder
679
+ ].flatMap(sourceFiles);
680
+ for (const file of files){
681
+ const source = external_node_fs_default().readFileSync(file, 'utf8');
682
+ const from = locate(file);
683
+ const ownContext = inside(contextsFolder, file)?.[0];
684
+ const report = (check, rule, imported)=>violations.push({
685
+ check,
686
+ rule,
687
+ file,
688
+ line: imported.line,
689
+ text: imported.statement
690
+ });
691
+ for (const imported of importsOf(source, file, aliases)){
692
+ const target = imported.target;
693
+ if (!target) continue;
694
+ const to = locate(target);
695
+ const targetContext = inside(contextsFolder, target)?.[0];
696
+ if (ownContext) {
697
+ if (targetContext && targetContext !== ownContext) report('context-isolation', `[${ownContext}] imports another context:`, imported);
698
+ } else if (inside(sharedFolder, file)) {
699
+ const allowed = !to || 'shared' === to.owner || 'domain' === to.segments[0] && 'errors' === to.segments[1] || file === inMemoryDbFile && isDomainModel(to.segments, target);
700
+ if (!allowed) report('shared-layer', '[shared] imports a bounded context outside its domain/errors (and domain models for the in-memory DB):', imported);
701
+ } else if (inside(uiKitFolder, file) || inside(hooksFolder, file)) {
702
+ const [area] = inside(reactFolder, target) ?? [];
703
+ const forbidden = inside(uiKitFolder, file) ? [
704
+ 'widgets',
705
+ 'pages'
706
+ ] : [
707
+ 'ui-kit',
708
+ 'widgets',
709
+ 'pages'
710
+ ];
711
+ if (targetContext || forbidden.includes(area)) report('react', inside(uiKitFolder, file) ? '[presentation/react/ui-kit] imports a bounded context, widget or page:' : '[presentation/react/hooks] a shared hook imports a bounded context, UI-kit, widget or page:', imported);
712
+ } else if (targetContext && !(imported.typeOnly && to?.segments[0] === 'presentation' && 'rest' === to.segments[1])) report('react', '[presentation/react] imports a context other than `import type` from presentation/rest:', imported);
713
+ const ownWidget = widgetOf(file);
714
+ const targetWidget = widgetOf(target);
715
+ if (ownWidget && targetWidget && targetWidget !== ownWidget) report('react', '[presentation/react/widgets] a widget imports another widget:', imported);
716
+ if (!from || !to) continue;
717
+ if (isSpec(file)) continue;
718
+ const fromKind = fileModuleKind(from.segments);
719
+ const toKind = fileModuleKind(to.segments);
720
+ if (fromKind && toKind) {
721
+ if (!rules[fromKind].has(toKind) && !(fromKind === toKind && isOwnContract(file, target))) report('dependencies', `[${from.owner}] ${fromKind} may not use ${toKind} (dependency rules):`, imported);
722
+ if ('infrastructure' !== to.segments[0]) continue;
723
+ }
724
+ const layerRule = layerImportRules[from.segments[0]];
725
+ if (layerRule && !layerRule.allows(to.segments)) report('layers', `[${from.owner}] ${layerRule.rule}`, imported);
726
+ }
727
+ }
728
+ return violations;
729
+ };
730
+ const wiringViolations = (projectRoot, rootFolder, rules)=>{
731
+ const root = external_node_path_default().resolve(projectRoot, rootFolder);
732
+ const sharedFolder = external_node_path_default().join(root, 'shared');
733
+ const contextsFolder = external_node_path_default().join(root, 'bounded-contexts');
734
+ const sharedModules = findWiredModules(sharedFolder);
735
+ const owners = [
736
+ {
737
+ name: 'shared',
738
+ modules: sharedModules
739
+ },
740
+ ...external_node_fs_default().existsSync(contextsFolder) ? external_node_fs_default().readdirSync(contextsFolder, {
741
+ withFileTypes: true
742
+ }).filter((entry)=>entry.isDirectory()).map((entry)=>({
743
+ name: entry.name,
744
+ modules: findWiredModules(external_node_path_default().join(contextsFolder, entry.name))
745
+ })) : []
746
+ ];
747
+ const violations = [];
748
+ for (const { name, modules } of owners){
749
+ const visible = new Map([
750
+ ...sharedModules,
751
+ ...modules
752
+ ].map((x)=>[
753
+ x.wireName,
754
+ x
755
+ ]));
756
+ for (const consumer of modules){
757
+ const source = external_node_fs_default().readFileSync(consumer.wireFile, 'utf8');
758
+ for (const implementation of consumer.implementations){
759
+ let dependencies;
760
+ try {
761
+ dependencies = wiredDependencyNames(source, implementation.className);
762
+ } catch {
763
+ continue;
764
+ }
765
+ const listStart = source.search(new RegExp(`wireClass\\(\\s*${implementation.className}\\b`));
766
+ for (const dependency of dependencies){
767
+ const candidate = visible.get(dependency);
768
+ if (!candidate || canDependOn(consumer, candidate, rules)) continue;
769
+ const index = source.indexOf(dependency, listStart);
770
+ violations.push({
771
+ check: 'dependencies',
772
+ rule: `[${name}] wiring: a dependency the dependency rules don't allow:`,
773
+ file: consumer.wireFile,
774
+ line: lineAt(source, index),
775
+ text: `${implementation.className} (${moduleKindOf(consumer) ?? consumer.kind}) ← ${candidate.typeName} (${moduleKindOf(candidate) ?? candidate.kind})`
776
+ });
777
+ }
778
+ }
779
+ }
780
+ }
781
+ return violations;
782
+ };
783
+ const clockViolations = (projectRoot, rootFolder)=>{
784
+ const root = external_node_path_default().resolve(projectRoot, rootFolder);
785
+ const folders = [
786
+ external_node_path_default().join(root, 'shared'),
787
+ ...external_node_fs_default().existsSync(external_node_path_default().join(root, 'bounded-contexts')) ? external_node_fs_default().readdirSync(external_node_path_default().join(root, 'bounded-contexts')).map((name)=>external_node_path_default().join(root, 'bounded-contexts', name)) : []
788
+ ].flatMap((folder)=>[
789
+ external_node_path_default().join(folder, 'domain'),
790
+ external_node_path_default().join(folder, 'application')
791
+ ]);
792
+ return folders.flatMap(sourceFiles).filter((file)=>!isSpec(file)).flatMap((file)=>{
793
+ const source = external_node_fs_default().readFileSync(file, 'utf8');
794
+ return [
795
+ ...source.matchAll(/\bnew\s+Date\s*\(\s*\)|\bDate\.now\s*\(/g)
796
+ ].map((match)=>({
797
+ check: 'clock',
798
+ rule: 'domain or application reads the current time directly (use the clock port):',
799
+ file,
800
+ line: lineAt(source, match.index),
801
+ text: match[0]
802
+ }));
803
+ });
804
+ };
805
+ const lintProject = (projectRoot, rootFolder, { rules = defaultDependencyRules, checks = {} } = {})=>[
806
+ ...importViolations(projectRoot, rootFolder, rules),
807
+ ...wiringViolations(projectRoot, rootFolder, rules),
808
+ ...clockViolations(projectRoot, rootFolder)
809
+ ].filter((x)=>false !== checks[x.check]);
810
+ const formatViolations = (violations, projectRoot)=>{
811
+ const groups = new Map();
812
+ for (const { rule, file, line, text } of violations)groups.set(rule, [
813
+ ...groups.get(rule) ?? [],
814
+ ` ${external_node_path_default().relative(projectRoot, file)}:${line}: ${text}`
815
+ ]);
816
+ return [
817
+ ...groups
818
+ ].map(([rule, lines])=>[
819
+ rule,
820
+ ...lines
821
+ ].join('\n')).join('\n\n');
822
+ };
823
+ const help = `Usage: df-lint [rootFolder]
824
+
825
+ Reports what breaks the Domain-First rules in the project:
826
+ bounded context isolation, layers, dependency rules (imports and wiring),
827
+ React modules, and reading the time without the clock port.
828
+ rootFolder defaults to the one in domain-first.project-structure.config.json,
829
+ whose optional \`rules\` change the dependency rules and turn checks off.
830
+ Exits with 1 when something is found.
831
+
832
+ Options:
833
+ -h, --help show this help`;
834
+ const { values, positionals } = (0, external_node_util_namespaceObject.parseArgs)({
835
+ allowPositionals: true,
836
+ options: {
837
+ help: {
838
+ type: 'boolean',
839
+ short: 'h',
840
+ default: false
841
+ }
842
+ }
843
+ });
844
+ if (values.help) {
845
+ console.log(help);
846
+ process.exit(0);
847
+ }
848
+ const lint_projectRoot = new ProjectRoot().path;
849
+ const lint_config = ConfigFile.exists ? ConfigFile.Instance.data : void 0;
850
+ const lint_rootFolder = positionals[0] ?? lint_config?.rootFolder ?? 'src';
851
+ const lint_violations = lintProject(lint_projectRoot, lint_rootFolder, {
852
+ rules: config_file_configuredDependencyRules(),
853
+ checks: lint_config?.rules?.lint
854
+ });
855
+ if (lint_violations.length) {
856
+ console.log(formatViolations(lint_violations, lint_projectRoot));
857
+ console.log(`\n${lint_violations.length} problem(s) found.`);
858
+ process.exit(1);
859
+ }
860
+ console.log('OK: no Domain-First rule violations.');
861
+ for(var __rspack_i in __webpack_exports__)exports[__rspack_i] = __webpack_exports__[__rspack_i];
862
+ Object.defineProperty(exports, '__esModule', {
863
+ value: true
864
+ });