@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/README.md +27 -2
- package/dist/201.js +699 -0
- package/dist/config-file.d.ts +71 -0
- package/dist/dependency-rules.d.ts +82 -0
- package/dist/dependency-rules.spec.d.ts +1 -0
- package/dist/index.cjs +122 -17
- package/dist/index.js +19 -584
- package/dist/lint.cjs +864 -0
- package/dist/lint.d.ts +2 -0
- package/dist/lint.js +296 -0
- package/dist/project-lint.d.ts +27 -0
- package/dist/project-lint.spec.d.ts +1 -0
- package/dist/wiring.d.ts +10 -5
- package/package.json +3 -2
- package/skills/df-ps-implement/SKILL.md +12 -3
- package/skills/df-ps-scaffold/SKILL.md +3 -3
- package/skills/df-ps-scaffold/references/choosing-components.md +3 -3
- package/skills/df-ps-scaffold/references/generators.md +1 -1
- package/skills/df-ps-implement/scripts/check-context-isolation.mjs +0 -204
package/dist/201.js
ADDED
|
@@ -0,0 +1,699 @@
|
|
|
1
|
+
import node_path from "node:path";
|
|
2
|
+
import zod from "zod";
|
|
3
|
+
import node_fs from "node:fs";
|
|
4
|
+
import { createRequire } from "node:module";
|
|
5
|
+
const moduleKinds = [
|
|
6
|
+
'repositories',
|
|
7
|
+
'domain-services',
|
|
8
|
+
'application-ports',
|
|
9
|
+
'application-services',
|
|
10
|
+
'use-cases',
|
|
11
|
+
'execution-commands',
|
|
12
|
+
'execution-queries',
|
|
13
|
+
'orchestration-commands',
|
|
14
|
+
'orchestration-queries',
|
|
15
|
+
'infrastructure-services',
|
|
16
|
+
'presentation-services'
|
|
17
|
+
];
|
|
18
|
+
const domain = [
|
|
19
|
+
'repositories',
|
|
20
|
+
'domain-services'
|
|
21
|
+
];
|
|
22
|
+
const commandsAndQueries = [
|
|
23
|
+
'execution-commands',
|
|
24
|
+
'execution-queries',
|
|
25
|
+
'orchestration-commands',
|
|
26
|
+
'orchestration-queries'
|
|
27
|
+
];
|
|
28
|
+
const infrastructure = [
|
|
29
|
+
...domain,
|
|
30
|
+
'application-ports',
|
|
31
|
+
'infrastructure-services'
|
|
32
|
+
];
|
|
33
|
+
const defaultDependencies = {
|
|
34
|
+
'domain-services': domain,
|
|
35
|
+
repositories: [
|
|
36
|
+
'domain-services',
|
|
37
|
+
'application-ports',
|
|
38
|
+
'infrastructure-services'
|
|
39
|
+
],
|
|
40
|
+
'application-ports': infrastructure,
|
|
41
|
+
'application-services': [
|
|
42
|
+
...domain,
|
|
43
|
+
'application-ports'
|
|
44
|
+
],
|
|
45
|
+
'use-cases': [
|
|
46
|
+
...domain,
|
|
47
|
+
'application-ports',
|
|
48
|
+
'application-services',
|
|
49
|
+
...commandsAndQueries
|
|
50
|
+
],
|
|
51
|
+
'execution-commands': infrastructure,
|
|
52
|
+
'execution-queries': infrastructure,
|
|
53
|
+
'orchestration-commands': [
|
|
54
|
+
...domain,
|
|
55
|
+
'execution-commands',
|
|
56
|
+
'execution-queries'
|
|
57
|
+
],
|
|
58
|
+
'orchestration-queries': [
|
|
59
|
+
...domain,
|
|
60
|
+
'execution-queries'
|
|
61
|
+
],
|
|
62
|
+
'infrastructure-services': infrastructure,
|
|
63
|
+
'presentation-services': [
|
|
64
|
+
'application-ports',
|
|
65
|
+
'application-services',
|
|
66
|
+
'use-cases',
|
|
67
|
+
...commandsAndQueries,
|
|
68
|
+
'presentation-services'
|
|
69
|
+
]
|
|
70
|
+
};
|
|
71
|
+
const kindSchema = zod["enum"](moduleKinds);
|
|
72
|
+
const dependencyRulesSchema = zod.partialRecord(kindSchema, zod.union([
|
|
73
|
+
zod.array(kindSchema),
|
|
74
|
+
zod.object({
|
|
75
|
+
add: zod.array(kindSchema).optional(),
|
|
76
|
+
remove: zod.array(kindSchema).optional()
|
|
77
|
+
})
|
|
78
|
+
]));
|
|
79
|
+
const resolveDependencyRules = (config = {})=>{
|
|
80
|
+
const entries = moduleKinds.map((kind)=>{
|
|
81
|
+
const override = config[kind];
|
|
82
|
+
if (Array.isArray(override)) return [
|
|
83
|
+
kind,
|
|
84
|
+
new Set(override)
|
|
85
|
+
];
|
|
86
|
+
const kinds = new Set([
|
|
87
|
+
...defaultDependencies[kind],
|
|
88
|
+
...override?.add ?? []
|
|
89
|
+
]);
|
|
90
|
+
for (const removed of override?.remove ?? [])kinds.delete(removed);
|
|
91
|
+
return [
|
|
92
|
+
kind,
|
|
93
|
+
kinds
|
|
94
|
+
];
|
|
95
|
+
});
|
|
96
|
+
return Object.fromEntries(entries);
|
|
97
|
+
};
|
|
98
|
+
const defaultDependencyRules = resolveDependencyRules();
|
|
99
|
+
const isModuleKind = (value)=>moduleKinds.includes(value);
|
|
100
|
+
const wiredModuleKind = (wiringKind, typeFile)=>{
|
|
101
|
+
const kind = 'commands' === wiringKind || 'queries' === wiringKind ? `${'execution' === node_path.basename(node_path.dirname(typeFile)) ? 'execution' : 'orchestration'}-${wiringKind}` : wiringKind;
|
|
102
|
+
return isModuleKind(kind) ? kind : void 0;
|
|
103
|
+
};
|
|
104
|
+
const fileModuleKind = (segments)=>{
|
|
105
|
+
const [layer, folder, mode] = segments;
|
|
106
|
+
const file = segments.at(-1) ?? '';
|
|
107
|
+
if (/^index(\.tsx?)?$/.test(file)) return;
|
|
108
|
+
if ('domain' === layer) {
|
|
109
|
+
if ('services' === folder) return 'domain-services';
|
|
110
|
+
return 'aggregates' === folder && /-repository(\.tsx?)?$/.test(file) ? 'repositories' : void 0;
|
|
111
|
+
}
|
|
112
|
+
if ('application' === layer) {
|
|
113
|
+
if ('commands' === folder || 'queries' === folder) return 'execution' === mode || 'orchestration' === mode ? `${mode}-${folder}` : void 0;
|
|
114
|
+
return ({
|
|
115
|
+
ports: 'application-ports',
|
|
116
|
+
services: 'application-services',
|
|
117
|
+
'use-cases': 'use-cases'
|
|
118
|
+
})[folder];
|
|
119
|
+
}
|
|
120
|
+
if ('infrastructure' === layer) return ({
|
|
121
|
+
repositories: 'repositories',
|
|
122
|
+
commands: 'execution-commands',
|
|
123
|
+
queries: 'execution-queries',
|
|
124
|
+
'application-adapters': 'application-ports',
|
|
125
|
+
services: 'infrastructure-services'
|
|
126
|
+
})[folder];
|
|
127
|
+
return 'presentation' === layer && 'services' === folder ? 'presentation-services' : void 0;
|
|
128
|
+
};
|
|
129
|
+
const pendingFiles = new Map();
|
|
130
|
+
const pendingFolders = new Set();
|
|
131
|
+
const pendingMoves = new Map();
|
|
132
|
+
const pendingDeletions = new Map();
|
|
133
|
+
const filesToOverwrite = ()=>[
|
|
134
|
+
...pendingFiles
|
|
135
|
+
].filter(([filePath, { replacesFile }])=>replacesFile && node_fs.existsSync(filePath)).map(([filePath])=>filePath);
|
|
136
|
+
const discardPendingChanges = ()=>{
|
|
137
|
+
pendingFolders.clear();
|
|
138
|
+
pendingFiles.clear();
|
|
139
|
+
pendingMoves.clear();
|
|
140
|
+
pendingDeletions.clear();
|
|
141
|
+
};
|
|
142
|
+
const removeEmptyFolders = (folderPath, stopAt)=>{
|
|
143
|
+
let current = folderPath;
|
|
144
|
+
while(current.startsWith(`${stopAt}${node_path.sep}`) && node_fs.existsSync(current) && !node_fs.readdirSync(current).length){
|
|
145
|
+
node_fs.rmdirSync(current);
|
|
146
|
+
current = node_path.dirname(current);
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
const writePendingChanges = ()=>{
|
|
150
|
+
for (const folderPath of pendingFolders)node_fs.mkdirSync(folderPath, {
|
|
151
|
+
recursive: true
|
|
152
|
+
});
|
|
153
|
+
for (const [filePath, { content }] of pendingFiles){
|
|
154
|
+
node_fs.mkdirSync(node_path.dirname(filePath), {
|
|
155
|
+
recursive: true
|
|
156
|
+
});
|
|
157
|
+
node_fs.writeFileSync(filePath, content, 'utf8');
|
|
158
|
+
}
|
|
159
|
+
for (const [targetPath, { sourcePath }] of pendingMoves){
|
|
160
|
+
node_fs.mkdirSync(node_path.dirname(targetPath), {
|
|
161
|
+
recursive: true
|
|
162
|
+
});
|
|
163
|
+
node_fs.renameSync(sourcePath, targetPath);
|
|
164
|
+
}
|
|
165
|
+
for (const filePath of pendingDeletions.keys())node_fs.rmSync(filePath, {
|
|
166
|
+
force: true
|
|
167
|
+
});
|
|
168
|
+
for (const [filePath, stopAt] of pendingDeletions)removeEmptyFolders(node_path.dirname(filePath), stopAt);
|
|
169
|
+
for (const { sourcePath, stopAt } of pendingMoves.values())removeEmptyFolders(node_path.dirname(sourcePath), stopAt);
|
|
170
|
+
discardPendingChanges();
|
|
171
|
+
};
|
|
172
|
+
class FileSystemItem {
|
|
173
|
+
path;
|
|
174
|
+
constructor(path){
|
|
175
|
+
this.path = path;
|
|
176
|
+
}
|
|
177
|
+
subitem = (relativePath)=>new this.constructor(node_path.resolve(this.path, ...relativePath));
|
|
178
|
+
get exists() {
|
|
179
|
+
return node_fs.existsSync(this.path);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
class Folder extends FileSystemItem {
|
|
183
|
+
createIfNotExisted = ()=>{
|
|
184
|
+
pendingFolders.add(this.path);
|
|
185
|
+
};
|
|
186
|
+
get content() {
|
|
187
|
+
if (!this.exists) return {
|
|
188
|
+
subfolderNames: [],
|
|
189
|
+
fileNames: []
|
|
190
|
+
};
|
|
191
|
+
const content = node_fs.readdirSync(this.path, {
|
|
192
|
+
withFileTypes: true
|
|
193
|
+
});
|
|
194
|
+
return {
|
|
195
|
+
subfolderNames: content.filter((x)=>x.isDirectory()).map((x)=>x.name),
|
|
196
|
+
fileNames: content.filter((x)=>!x.isDirectory()).map((x)=>node_path.parse(x.name).name)
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
get name() {
|
|
200
|
+
return node_path.basename(this.path);
|
|
201
|
+
}
|
|
202
|
+
createFile = (name, content)=>{
|
|
203
|
+
this.createIfNotExisted();
|
|
204
|
+
const file = new File(this.path).subitem([
|
|
205
|
+
name
|
|
206
|
+
]);
|
|
207
|
+
file.data = content;
|
|
208
|
+
return file;
|
|
209
|
+
};
|
|
210
|
+
file = (name)=>{
|
|
211
|
+
this.createIfNotExisted();
|
|
212
|
+
const file = new File(this.path).subitem([
|
|
213
|
+
name
|
|
214
|
+
]);
|
|
215
|
+
return file;
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
class File extends FileSystemItem {
|
|
219
|
+
get exists() {
|
|
220
|
+
return pendingFiles.has(this.path) || pendingMoves.has(this.path) || node_fs.existsSync(this.path) && !pendingDeletions.has(this.path);
|
|
221
|
+
}
|
|
222
|
+
delete = (stopAt)=>{
|
|
223
|
+
pendingDeletions.set(this.path, stopAt);
|
|
224
|
+
};
|
|
225
|
+
moveTo = (targetPath, stopAt)=>{
|
|
226
|
+
pendingMoves.set(targetPath, {
|
|
227
|
+
sourcePath: this.path,
|
|
228
|
+
stopAt
|
|
229
|
+
});
|
|
230
|
+
};
|
|
231
|
+
get data() {
|
|
232
|
+
const pendingFile = pendingFiles.get(this.path);
|
|
233
|
+
if (pendingFile) return pendingFile.content;
|
|
234
|
+
if (!this.exists) throw new Error('File does not exist');
|
|
235
|
+
return node_fs.readFileSync(this.path, 'utf-8');
|
|
236
|
+
}
|
|
237
|
+
set data(content) {
|
|
238
|
+
pendingFiles.set(this.path, {
|
|
239
|
+
content,
|
|
240
|
+
replacesFile: true
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
update = (content)=>{
|
|
244
|
+
pendingFiles.set(this.path, {
|
|
245
|
+
content,
|
|
246
|
+
replacesFile: pendingFiles.get(this.path)?.replacesFile ?? false
|
|
247
|
+
});
|
|
248
|
+
};
|
|
249
|
+
addLine = (newLine, separator = '\n')=>{
|
|
250
|
+
const content = this.exists ? this.data : '';
|
|
251
|
+
pendingFiles.set(this.path, {
|
|
252
|
+
content: [
|
|
253
|
+
content.trim(),
|
|
254
|
+
newLine.trim()
|
|
255
|
+
].filter((x)=>!!x).join(separator),
|
|
256
|
+
replacesFile: pendingFiles.get(this.path)?.replacesFile ?? false
|
|
257
|
+
});
|
|
258
|
+
};
|
|
259
|
+
addLineIfMissing = (newLine, separator = '\n')=>{
|
|
260
|
+
const alreadyAdded = this.exists && this.data.split('\n').some((line)=>line.trim() === newLine.trim());
|
|
261
|
+
if (!alreadyAdded) this.addLine(newLine, separator);
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
class ProjectRoot {
|
|
265
|
+
path;
|
|
266
|
+
constructor(){
|
|
267
|
+
let dir = process.cwd();
|
|
268
|
+
while(dir !== node_path.parse(dir).root){
|
|
269
|
+
if (node_fs.existsSync(node_path.join(dir, 'package.json'))) {
|
|
270
|
+
this.path = dir;
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
dir = node_path.dirname(dir);
|
|
274
|
+
}
|
|
275
|
+
throw new Error('No package.json was found');
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
const lintChecks = [
|
|
279
|
+
'context-isolation',
|
|
280
|
+
'shared-layer',
|
|
281
|
+
'layers',
|
|
282
|
+
'dependencies',
|
|
283
|
+
'react',
|
|
284
|
+
'clock'
|
|
285
|
+
];
|
|
286
|
+
const configFileName = 'domain-first.project-structure.config.json';
|
|
287
|
+
const configSchema = zod.object({
|
|
288
|
+
rootFolder: zod.string(),
|
|
289
|
+
domainFirstPackages: zod.array(zod["enum"]([
|
|
290
|
+
'@domain-first/types',
|
|
291
|
+
'@domain-first/errors',
|
|
292
|
+
'@domain-first/handlers',
|
|
293
|
+
'@domain-first/wire',
|
|
294
|
+
'@domain-first/handlers-rest'
|
|
295
|
+
])),
|
|
296
|
+
defaultPersistenceLayerImplementation: zod.string(),
|
|
297
|
+
withInMemoryDb: zod.boolean().optional(),
|
|
298
|
+
useReact: zod.boolean(),
|
|
299
|
+
storybookFramework: zod.string().optional(),
|
|
300
|
+
testingLibrary: zod.string().optional(),
|
|
301
|
+
rules: zod.object({
|
|
302
|
+
dependencies: dependencyRulesSchema.optional(),
|
|
303
|
+
lint: zod.partialRecord(zod["enum"](lintChecks), zod.boolean()).optional()
|
|
304
|
+
}).optional()
|
|
305
|
+
});
|
|
306
|
+
class ConfigFile {
|
|
307
|
+
data;
|
|
308
|
+
constructor(){
|
|
309
|
+
const filePath = ConfigFile.path;
|
|
310
|
+
const file = new File(filePath);
|
|
311
|
+
const configObject = JSON.parse(file.data);
|
|
312
|
+
this.data = configSchema.parse(configObject);
|
|
313
|
+
}
|
|
314
|
+
static get Instance() {
|
|
315
|
+
return new ConfigFile();
|
|
316
|
+
}
|
|
317
|
+
static get path() {
|
|
318
|
+
const { path: root } = new ProjectRoot();
|
|
319
|
+
return node_path.resolve(root, configFileName);
|
|
320
|
+
}
|
|
321
|
+
static get exists() {
|
|
322
|
+
return new File(ConfigFile.path).exists;
|
|
323
|
+
}
|
|
324
|
+
static write = (config)=>{
|
|
325
|
+
new File(ConfigFile.path).data = JSON.stringify(config, null, '\t');
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
const configuredDependencyRules = ()=>resolveDependencyRules(ConfigFile.exists ? ConfigFile.Instance.data.rules?.dependencies : void 0);
|
|
329
|
+
const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
|
|
330
|
+
const resolveExtends = (fromFile, target)=>{
|
|
331
|
+
if (target.startsWith('.') || node_path.isAbsolute(target)) {
|
|
332
|
+
const resolved = node_path.resolve(node_path.dirname(fromFile), target);
|
|
333
|
+
return resolved.endsWith('.json') ? resolved : `${resolved}.json`;
|
|
334
|
+
}
|
|
335
|
+
const require = createRequire(fromFile);
|
|
336
|
+
for (const candidate of [
|
|
337
|
+
target,
|
|
338
|
+
`${target}/tsconfig.json`
|
|
339
|
+
])try {
|
|
340
|
+
return require.resolve(candidate);
|
|
341
|
+
} catch {}
|
|
342
|
+
};
|
|
343
|
+
const compilerOption = (configFile, name, seen = new Set())=>{
|
|
344
|
+
if (seen.has(configFile) || !node_fs.existsSync(configFile)) return null;
|
|
345
|
+
seen.add(configFile);
|
|
346
|
+
let config;
|
|
347
|
+
try {
|
|
348
|
+
config = JSON.parse(stripJsonComments(node_fs.readFileSync(configFile, 'utf8')));
|
|
349
|
+
} catch {
|
|
350
|
+
return null;
|
|
351
|
+
}
|
|
352
|
+
if (config.compilerOptions && name in config.compilerOptions) return config.compilerOptions[name];
|
|
353
|
+
const parents = [
|
|
354
|
+
config.extends ?? []
|
|
355
|
+
].flat().reverse();
|
|
356
|
+
for (const parent of parents){
|
|
357
|
+
const parentFile = resolveExtends(configFile, parent);
|
|
358
|
+
const value = parentFile ? compilerOption(parentFile, name, seen) : null;
|
|
359
|
+
if (void 0 !== value) return value;
|
|
360
|
+
}
|
|
361
|
+
};
|
|
362
|
+
class UnknownFormatNaming {
|
|
363
|
+
rawSource;
|
|
364
|
+
camelCase;
|
|
365
|
+
PascalCase;
|
|
366
|
+
constructor(rawSource){
|
|
367
|
+
this.rawSource = rawSource;
|
|
368
|
+
const source = rawSource.trim();
|
|
369
|
+
if (!source.includes('-')) {
|
|
370
|
+
this.camelCase = source.substring(0, 1).toLowerCase() + source.substring(1);
|
|
371
|
+
this.PascalCase = source.substring(0, 1).toUpperCase() + source.substring(1);
|
|
372
|
+
}
|
|
373
|
+
const words = source.split('-').filter((word)=>!!word);
|
|
374
|
+
this.camelCase = words.map((word, index)=>0 === index ? word.toLowerCase() : word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
|
|
375
|
+
this.PascalCase = words.map((word)=>word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
|
|
376
|
+
}
|
|
377
|
+
get fileName() {
|
|
378
|
+
return this.rawSource;
|
|
379
|
+
}
|
|
380
|
+
get variableName() {
|
|
381
|
+
return this.camelCase;
|
|
382
|
+
}
|
|
383
|
+
get ClassName() {
|
|
384
|
+
return this.PascalCase;
|
|
385
|
+
}
|
|
386
|
+
get withSpaces() {
|
|
387
|
+
return this.fileName.replaceAll('-', ' ');
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
const wiring_layers = [
|
|
391
|
+
'domain',
|
|
392
|
+
'application',
|
|
393
|
+
'infrastructure',
|
|
394
|
+
'presentation'
|
|
395
|
+
];
|
|
396
|
+
const visibleLayers = {
|
|
397
|
+
domain: [
|
|
398
|
+
'domain'
|
|
399
|
+
],
|
|
400
|
+
application: [
|
|
401
|
+
'domain',
|
|
402
|
+
'application'
|
|
403
|
+
],
|
|
404
|
+
infrastructure: [
|
|
405
|
+
'domain',
|
|
406
|
+
'application',
|
|
407
|
+
'infrastructure'
|
|
408
|
+
],
|
|
409
|
+
presentation: [
|
|
410
|
+
'application',
|
|
411
|
+
'presentation'
|
|
412
|
+
]
|
|
413
|
+
};
|
|
414
|
+
const branchedTypeFiles = {
|
|
415
|
+
repositories: (fileBase)=>[
|
|
416
|
+
'domain',
|
|
417
|
+
'aggregates',
|
|
418
|
+
fileBase.replace(/-repository$/, ''),
|
|
419
|
+
`${fileBase}.ts`
|
|
420
|
+
],
|
|
421
|
+
commands: (fileBase)=>[
|
|
422
|
+
'application',
|
|
423
|
+
'commands',
|
|
424
|
+
'execution',
|
|
425
|
+
`${fileBase}.ts`
|
|
426
|
+
],
|
|
427
|
+
queries: (fileBase)=>[
|
|
428
|
+
'application',
|
|
429
|
+
'queries',
|
|
430
|
+
'execution',
|
|
431
|
+
`${fileBase}.ts`
|
|
432
|
+
],
|
|
433
|
+
'application-ports': (fileBase)=>[
|
|
434
|
+
'application',
|
|
435
|
+
'ports',
|
|
436
|
+
`${fileBase}.ts`
|
|
437
|
+
]
|
|
438
|
+
};
|
|
439
|
+
const layerOf = (file, contextPath)=>{
|
|
440
|
+
const [firstSegment] = node_path.relative(contextPath, file).split(node_path.sep);
|
|
441
|
+
return wiring_layers.find((layer)=>layer === firstSegment);
|
|
442
|
+
};
|
|
443
|
+
const namedImports = (source, fromFile)=>{
|
|
444
|
+
const result = new Map();
|
|
445
|
+
for (const [, names, importPath] of source.matchAll(/import\s*(?:type\s*)?\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g))for (const name of names.split(',')){
|
|
446
|
+
const cleanName = name.replace(/^\s*type\s+/, '').trim();
|
|
447
|
+
if (cleanName) result.set(cleanName, `${node_path.resolve(node_path.dirname(fromFile), importPath)}.ts`);
|
|
448
|
+
}
|
|
449
|
+
return result;
|
|
450
|
+
};
|
|
451
|
+
const isEndpointWire = (wiringRelativePath)=>wiringRelativePath.startsWith([
|
|
452
|
+
'presentation',
|
|
453
|
+
'rest'
|
|
454
|
+
].join(node_path.sep));
|
|
455
|
+
const wireClassDefinitions = (source)=>[
|
|
456
|
+
...codeOnly(source).matchAll(/(?:export\s+)?const\s+(\w+)\s*=\s*(?:\w+\(\s*)*wireClass\(\s*(\w+)\s*,/g)
|
|
457
|
+
].map(([, wireName, className])=>({
|
|
458
|
+
wireName,
|
|
459
|
+
className
|
|
460
|
+
}));
|
|
461
|
+
const wiredClassNames = (source, wireName, initializerStart, branched)=>{
|
|
462
|
+
const definitions = wireClassDefinitions(source);
|
|
463
|
+
if (!branched) return definitions.filter((x)=>x.wireName === wireName).map((x)=>x.className);
|
|
464
|
+
const openIndex = source.indexOf('(', initializerStart);
|
|
465
|
+
const branches = codeOnly(source).slice(openIndex, closingIndex(source, openIndex));
|
|
466
|
+
const referenced = new Set(branches.match(/\w+/g));
|
|
467
|
+
return definitions.filter((x)=>referenced.has(x.wireName)).map((x)=>x.className);
|
|
468
|
+
};
|
|
469
|
+
const readWiredModule = (wireFile, contextPath)=>{
|
|
470
|
+
const wiringRelativePath = node_path.relative(node_path.join(contextPath, 'wiring'), wireFile);
|
|
471
|
+
if (isEndpointWire(wiringRelativePath)) return;
|
|
472
|
+
const source = new File(wireFile).data;
|
|
473
|
+
const wireName = `wire${new UnknownFormatNaming(node_path.basename(wireFile, '.ts').replace(/^wire-/, '')).ClassName}`;
|
|
474
|
+
const exportMatch = new RegExp(`export\\s+const\\s+${wireName}\\s*=\\s*`).exec(source);
|
|
475
|
+
if (!exportMatch) return;
|
|
476
|
+
const branched = source.slice(exportMatch.index + exportMatch[0].length).startsWith('envBranchedWire(');
|
|
477
|
+
const imports = namedImports(source, wireFile);
|
|
478
|
+
const implementations = wiredClassNames(source, wireName, exportMatch.index + exportMatch[0].length, branched).flatMap((className)=>{
|
|
479
|
+
const file = imports.get(className);
|
|
480
|
+
return file ? [
|
|
481
|
+
{
|
|
482
|
+
className,
|
|
483
|
+
file
|
|
484
|
+
}
|
|
485
|
+
] : [];
|
|
486
|
+
});
|
|
487
|
+
if (!implementations.length) return;
|
|
488
|
+
const typeName = wireName.slice(4);
|
|
489
|
+
const [wiringFolder] = wiringRelativePath.split(node_path.sep);
|
|
490
|
+
const typeFileSegments = branchedTypeFiles[wiringFolder]?.(node_path.basename(wireFile, '.ts').replace(/^wire-/, ''));
|
|
491
|
+
const typeFile = branched ? typeFileSegments && node_path.join(contextPath, ...typeFileSegments) : implementations[0].file;
|
|
492
|
+
const layer = typeFile && layerOf(typeFile, contextPath);
|
|
493
|
+
const implementationsLayer = layerOf(implementations[0].file, contextPath);
|
|
494
|
+
if (!typeFile || !layer || !implementationsLayer) return;
|
|
495
|
+
return {
|
|
496
|
+
wireName,
|
|
497
|
+
typeName,
|
|
498
|
+
wireFile,
|
|
499
|
+
typeFile,
|
|
500
|
+
layer,
|
|
501
|
+
implementations,
|
|
502
|
+
branched,
|
|
503
|
+
implementationsLayer,
|
|
504
|
+
kind: wiringFolder
|
|
505
|
+
};
|
|
506
|
+
};
|
|
507
|
+
const findWiredModules = (contextPath)=>{
|
|
508
|
+
const result = [];
|
|
509
|
+
const walk = (folderPath)=>{
|
|
510
|
+
if (!node_fs.existsSync(folderPath)) return;
|
|
511
|
+
for (const entry of node_fs.readdirSync(folderPath, {
|
|
512
|
+
withFileTypes: true
|
|
513
|
+
})){
|
|
514
|
+
const entryPath = node_path.join(folderPath, entry.name);
|
|
515
|
+
if (entry.isDirectory()) walk(entryPath);
|
|
516
|
+
else if (/^wire-.*(?<!\.spec)\.ts$/.test(entry.name)) {
|
|
517
|
+
const wiredModule = readWiredModule(entryPath, contextPath);
|
|
518
|
+
if (wiredModule) result.push(wiredModule);
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
};
|
|
522
|
+
walk(node_path.join(contextPath, 'wiring'));
|
|
523
|
+
return result.sort((a, b)=>a.typeName.localeCompare(b.typeName));
|
|
524
|
+
};
|
|
525
|
+
const moduleKindOf = (module)=>wiredModuleKind(module.kind, module.typeFile);
|
|
526
|
+
const layerRule = (consumer, candidate)=>visibleLayers[consumer.implementationsLayer].includes(candidate.layer) && ('infrastructure' !== consumer.implementationsLayer || 'application' !== candidate.layer || 'application-ports' === candidate.kind);
|
|
527
|
+
const implementationType = (consumer, implementation)=>consumer.branched ? node_path.basename(node_path.dirname(implementation.file)) : void 0;
|
|
528
|
+
const isSuggestedFor = (candidate, implementation)=>'infrastructure' === candidate.layer && `-${node_path.basename(candidate.typeFile, '.ts')}-`.includes(`-${implementation}-`);
|
|
529
|
+
const canDependOn = (consumer, candidate, rules = defaultDependencyRules)=>{
|
|
530
|
+
const consumerKind = moduleKindOf(consumer);
|
|
531
|
+
const candidateKind = moduleKindOf(candidate);
|
|
532
|
+
return consumerKind && candidateKind ? rules[consumerKind].has(candidateKind) : layerRule(consumer, candidate);
|
|
533
|
+
};
|
|
534
|
+
const availableDependencies = (consumer, implementation, candidates, rules = configuredDependencyRules())=>{
|
|
535
|
+
const wired = wiredDependencyNames(new File(consumer.wireFile).data, implementation.className);
|
|
536
|
+
return candidates.filter((candidate)=>candidate.wireFile !== consumer.wireFile && canDependOn(consumer, candidate, rules) && !wired.includes(candidate.wireName));
|
|
537
|
+
};
|
|
538
|
+
const relativeImport = (fromFile, toFile)=>{
|
|
539
|
+
const relativePath = node_path.relative(node_path.dirname(fromFile), toFile).replace(/\.ts$/, '').split(node_path.sep).join('/');
|
|
540
|
+
return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
|
|
541
|
+
};
|
|
542
|
+
const codeOnly = (source)=>{
|
|
543
|
+
let result = '';
|
|
544
|
+
let index = 0;
|
|
545
|
+
const blank = (text)=>text.replace(/[^\n]/g, ' ');
|
|
546
|
+
while(index < source.length){
|
|
547
|
+
const pair = source.slice(index, index + 2);
|
|
548
|
+
const char = source[index];
|
|
549
|
+
let end = index + 1;
|
|
550
|
+
if ('//' === pair) {
|
|
551
|
+
const lineEnd = source.indexOf('\n', index);
|
|
552
|
+
end = -1 === lineEnd ? source.length : lineEnd;
|
|
553
|
+
result += blank(source.slice(index, end));
|
|
554
|
+
} else if ('/*' === pair) {
|
|
555
|
+
const commentEnd = source.indexOf('*/', index + 2);
|
|
556
|
+
end = -1 === commentEnd ? source.length : commentEnd + 2;
|
|
557
|
+
result += blank(source.slice(index, end));
|
|
558
|
+
} else if ('=>' === pair) {
|
|
559
|
+
end = index + 2;
|
|
560
|
+
result += ' ';
|
|
561
|
+
} else if ("'" === char || '"' === char || '`' === char) {
|
|
562
|
+
while(end < source.length && source[end] !== char)end += '\\' === source[end] ? 2 : 1;
|
|
563
|
+
end = Math.min(end + 1, source.length);
|
|
564
|
+
result += char + blank(source.slice(index + 1, end - 1));
|
|
565
|
+
result += end - 1 > index ? source[end - 1] : '';
|
|
566
|
+
} else result += char;
|
|
567
|
+
index = end;
|
|
568
|
+
}
|
|
569
|
+
return result;
|
|
570
|
+
};
|
|
571
|
+
const addImport = (source, importLine)=>{
|
|
572
|
+
if (source.split('\n').some((line)=>line.trim() === importLine)) return source;
|
|
573
|
+
const lastImport = [
|
|
574
|
+
...codeOnly(source).matchAll(/^import\s(?:[^'"]*?from\s*)?['"][^'"]*['"]/gm)
|
|
575
|
+
].at(-1);
|
|
576
|
+
if (!lastImport) return `${importLine}\n\n${source}`;
|
|
577
|
+
const importEnd = lastImport.index + lastImport[0].length;
|
|
578
|
+
const lineEnd = source.indexOf('\n', importEnd);
|
|
579
|
+
const insertAt = -1 === lineEnd ? source.length : lineEnd;
|
|
580
|
+
return `${source.slice(0, insertAt)}\n${importLine}${source.slice(insertAt)}`;
|
|
581
|
+
};
|
|
582
|
+
const brackets = {
|
|
583
|
+
'(': ')',
|
|
584
|
+
'[': ']',
|
|
585
|
+
'{': '}',
|
|
586
|
+
'<': '>'
|
|
587
|
+
};
|
|
588
|
+
const closingIndex = (source, openIndex)=>{
|
|
589
|
+
const code = codeOnly(source);
|
|
590
|
+
let depth = 0;
|
|
591
|
+
for(let index = openIndex; index < code.length; index++){
|
|
592
|
+
const char = code[index];
|
|
593
|
+
if (char === code[openIndex]) depth++;
|
|
594
|
+
else if (char === brackets[code[openIndex]]) {
|
|
595
|
+
depth--;
|
|
596
|
+
if (0 === depth) return index;
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
return -1;
|
|
600
|
+
};
|
|
601
|
+
const splitTopLevel = (content)=>{
|
|
602
|
+
const code = codeOnly(content);
|
|
603
|
+
const items = [];
|
|
604
|
+
let depth = 0;
|
|
605
|
+
let itemStart = 0;
|
|
606
|
+
for(let index = 0; index <= code.length; index++){
|
|
607
|
+
const char = code[index];
|
|
608
|
+
if (void 0 !== char && char in brackets) depth++;
|
|
609
|
+
else if (Object.values(brackets).includes(char)) depth--;
|
|
610
|
+
if (index === code.length || ',' === char && 0 === depth) {
|
|
611
|
+
const item = content.slice(itemStart, index);
|
|
612
|
+
const itemCode = code.slice(itemStart, index);
|
|
613
|
+
const first = itemCode.search(/\S/);
|
|
614
|
+
const last = itemCode.search(/\S\s*$/);
|
|
615
|
+
if (-1 !== first) items.push(item.slice(first, last + 1));
|
|
616
|
+
itemStart = index + 1;
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
return items;
|
|
620
|
+
};
|
|
621
|
+
const appendItems = (content, items)=>{
|
|
622
|
+
const code = codeOnly(content);
|
|
623
|
+
const lastCode = code.search(/\S\s*$/);
|
|
624
|
+
if (-1 === lastCode) return items.join(', ');
|
|
625
|
+
const trailingComma = ',' === code[lastCode];
|
|
626
|
+
if (!content.includes('\n')) {
|
|
627
|
+
const added = trailingComma ? ` ${items.join(', ')},` : `, ${items.join(', ')}`;
|
|
628
|
+
return content.slice(0, lastCode + 1) + added + content.slice(lastCode + 1);
|
|
629
|
+
}
|
|
630
|
+
const indent = content.match(/\n([ \t]*)\S/)?.[1] ?? '';
|
|
631
|
+
const withComma = trailingComma ? content : `${content.slice(0, lastCode + 1)},${content.slice(lastCode + 1)}`;
|
|
632
|
+
const lineEndIndex = withComma.indexOf('\n', lastCode + 1);
|
|
633
|
+
const lineEnd = -1 === lineEndIndex ? withComma.length : lineEndIndex;
|
|
634
|
+
const added = trailingComma ? items.map((x)=>`\n${indent}${x},`).join('') : items.map((x)=>`\n${indent}${x}`).join(',');
|
|
635
|
+
return withComma.slice(0, lineEnd) + added + withComma.slice(lineEnd);
|
|
636
|
+
};
|
|
637
|
+
const addConstructorParameters = (source, className, parameters)=>{
|
|
638
|
+
const classMatch = new RegExp(`class\\s+${className}\\b[^{]*\\{`).exec(codeOnly(source));
|
|
639
|
+
if (!classMatch) throw new Error(`Class ${className} not found`);
|
|
640
|
+
const bodyStart = classMatch.index + classMatch[0].length;
|
|
641
|
+
const bodyEnd = closingIndex(source, bodyStart - 1);
|
|
642
|
+
const body = source.slice(bodyStart, bodyEnd);
|
|
643
|
+
const constructorIndex = codeOnly(body).search(/\bconstructor\s*\(/);
|
|
644
|
+
const renderParameters = (allParameters, indent)=>1 === allParameters.length ? allParameters[0] : `\n${allParameters.map((x)=>`${indent} ${x}`).join(',\n')}\n${indent}`;
|
|
645
|
+
if (-1 === constructorIndex) {
|
|
646
|
+
const constructorBody = /\bextends\b/.test(classMatch[0]) ? '{\n super()\n }' : '{}';
|
|
647
|
+
const constructorLine = ` constructor(${renderParameters(parameters, ' ')}) ${constructorBody}`;
|
|
648
|
+
const newBody = body.trim() ? `\n${constructorLine}\n${body.replace(/^\s*\n/, '\n')}` : `\n${constructorLine}\n`;
|
|
649
|
+
return source.slice(0, bodyStart) + newBody + source.slice(bodyEnd);
|
|
650
|
+
}
|
|
651
|
+
const openIndex = bodyStart + body.indexOf('(', constructorIndex);
|
|
652
|
+
const closeIndex = closingIndex(source, openIndex);
|
|
653
|
+
const content = source.slice(openIndex + 1, closeIndex);
|
|
654
|
+
if (content.includes('\n')) return source.slice(0, openIndex + 1) + appendItems(content, parameters) + source.slice(closeIndex);
|
|
655
|
+
const lineStart = source.lastIndexOf('\n', openIndex) + 1;
|
|
656
|
+
const indent = source.slice(lineStart).match(/^\s*/)?.[0] ?? '';
|
|
657
|
+
return source.slice(0, openIndex + 1) + renderParameters([
|
|
658
|
+
...splitTopLevel(content),
|
|
659
|
+
...parameters
|
|
660
|
+
], indent) + source.slice(closeIndex);
|
|
661
|
+
};
|
|
662
|
+
const addClassMember = (source, className, member)=>{
|
|
663
|
+
const classMatch = new RegExp(`class\\s+${className}\\b[^{]*\\{`).exec(codeOnly(source));
|
|
664
|
+
if (!classMatch) throw new Error(`Class ${className} not found`);
|
|
665
|
+
const bodyStart = classMatch.index + classMatch[0].length;
|
|
666
|
+
const bodyEnd = closingIndex(source, bodyStart - 1);
|
|
667
|
+
const body = source.slice(bodyStart, bodyEnd).trimEnd();
|
|
668
|
+
const separator = body.trim() ? '\n\n' : '\n';
|
|
669
|
+
return `${source.slice(0, bodyStart)}${body}${separator} ${member}\n${source.slice(bodyEnd)}`;
|
|
670
|
+
};
|
|
671
|
+
const wireListRange = (source, className)=>{
|
|
672
|
+
const match = new RegExp(`wireClass\\(\\s*${className}\\s*,\\s*\\[`).exec(codeOnly(source));
|
|
673
|
+
if (!match) throw new Error(`wireClass(${className}, [...]) not found`);
|
|
674
|
+
const openIndex = match.index + match[0].length - 1;
|
|
675
|
+
return {
|
|
676
|
+
openIndex,
|
|
677
|
+
closeIndex: closingIndex(source, openIndex)
|
|
678
|
+
};
|
|
679
|
+
};
|
|
680
|
+
const wiredDependencyNames = (source, className)=>{
|
|
681
|
+
const { openIndex, closeIndex } = wireListRange(source, className);
|
|
682
|
+
return splitTopLevel(source.slice(openIndex + 1, closeIndex));
|
|
683
|
+
};
|
|
684
|
+
const addWireDependencies = (source, className, wireNames)=>{
|
|
685
|
+
const { openIndex, closeIndex } = wireListRange(source, className);
|
|
686
|
+
return source.slice(0, openIndex + 1) + appendItems(source.slice(openIndex + 1, closeIndex), wireNames) + source.slice(closeIndex);
|
|
687
|
+
};
|
|
688
|
+
const parameterName = (typeName)=>typeName.substring(0, 1).toLowerCase() + typeName.substring(1);
|
|
689
|
+
const wireDependencies = (consumer, implementation, dependencies)=>{
|
|
690
|
+
const wireFile = new File(consumer.wireFile);
|
|
691
|
+
let wireSource = wireFile.data;
|
|
692
|
+
for (const dependency of dependencies)wireSource = addImport(wireSource, `import { ${dependency.wireName} } from '${relativeImport(consumer.wireFile, dependency.wireFile)}'`);
|
|
693
|
+
wireFile.update(addWireDependencies(wireSource, implementation.className, dependencies.map((x)=>x.wireName)));
|
|
694
|
+
const classFile = new File(implementation.file);
|
|
695
|
+
let classSource = classFile.data;
|
|
696
|
+
for (const dependency of dependencies)classSource = addImport(classSource, `import type { ${dependency.typeName} } from '${relativeImport(implementation.file, dependency.typeFile)}'`);
|
|
697
|
+
classFile.update(addConstructorParameters(classSource, implementation.className, dependencies.map((x)=>`private readonly ${parameterName(x.typeName)}: ${x.typeName}`)));
|
|
698
|
+
};
|
|
699
|
+
export { ConfigFile, File, Folder, ProjectRoot, UnknownFormatNaming, addClassMember, addConstructorParameters, addImport, addWireDependencies, availableDependencies, canDependOn, compilerOption, configuredDependencyRules, defaultDependencyRules, discardPendingChanges, fileModuleKind, filesToOverwrite, findWiredModules, implementationType, isSuggestedFor, moduleKindOf, readWiredModule, relativeImport, stripJsonComments, wireDependencies, wiredDependencyNames, writePendingChanges };
|