@domain-first/project-structure 8.9.0 → 8.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,7 @@
1
1
  import node_fs from "node:fs";
2
2
  import node_path from "node:path";
3
- import { defaultDependencyRules, configuredDependencyRules, wiredModuleKind, File } from "./780.js";
3
+ import zod from "zod";
4
+ import { createRequire } from "node:module";
4
5
  const crossContextImplementation = 'cross-context';
5
6
  const hasNeighboringBoundedContext = (ownerPath)=>{
6
7
  const contextsPath = node_path.dirname(ownerPath);
@@ -44,6 +45,449 @@ const crossContextImportAllowed = (from, to)=>{
44
45
  'use-cases'
45
46
  ].includes(targetKind) && (isCrossContextImplementation(from) && 'application' === targetLayer || 'wiring' === layer && 'application-ports' === kind && 'wiring' === targetLayer);
46
47
  };
48
+ const implementationKinds = [
49
+ 'repositories',
50
+ 'commands',
51
+ 'queries',
52
+ 'ports'
53
+ ];
54
+ const implementationLabelSchema = zod.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/);
55
+ const implementationGroupSchema = zod.object({
56
+ primary: zod.array(implementationLabelSchema).default([]),
57
+ test: zod.array(implementationLabelSchema).default([])
58
+ }).strict();
59
+ const implementationOptionsSchema = zod.object({
60
+ ...Object.fromEntries(implementationKinds.map((kind)=>[
61
+ kind,
62
+ implementationGroupSchema.optional()
63
+ ])),
64
+ integrationTests: zod.array(implementationLabelSchema).optional()
65
+ }).strict();
66
+ const moduleKinds = [
67
+ 'repositories',
68
+ 'domain-services',
69
+ 'application-ports',
70
+ 'application-services',
71
+ 'use-cases',
72
+ 'commands',
73
+ 'queries',
74
+ 'infrastructure-services',
75
+ 'presentation-services'
76
+ ];
77
+ const domain = [
78
+ 'repositories',
79
+ 'domain-services'
80
+ ];
81
+ const commandsAndQueries = [
82
+ 'commands',
83
+ 'queries'
84
+ ];
85
+ const infrastructure = [
86
+ ...domain,
87
+ 'application-ports',
88
+ 'infrastructure-services'
89
+ ];
90
+ const defaultDependencies = {
91
+ 'domain-services': [
92
+ 'domain-services'
93
+ ],
94
+ repositories: [
95
+ 'domain-services',
96
+ 'application-ports',
97
+ 'infrastructure-services'
98
+ ],
99
+ 'application-ports': infrastructure,
100
+ 'application-services': [
101
+ ...domain,
102
+ 'application-ports',
103
+ ...commandsAndQueries
104
+ ],
105
+ 'use-cases': [
106
+ ...domain,
107
+ 'application-ports',
108
+ 'application-services',
109
+ ...commandsAndQueries
110
+ ],
111
+ commands: [
112
+ 'infrastructure-services'
113
+ ],
114
+ queries: [
115
+ 'infrastructure-services'
116
+ ],
117
+ 'infrastructure-services': infrastructure,
118
+ 'presentation-services': [
119
+ 'application-ports',
120
+ 'application-services',
121
+ 'use-cases',
122
+ ...commandsAndQueries,
123
+ 'presentation-services'
124
+ ]
125
+ };
126
+ const kindSchema = zod["enum"](moduleKinds);
127
+ const dependencyRulesSchema = zod.partialRecord(kindSchema, zod.union([
128
+ zod.array(kindSchema),
129
+ zod.object({
130
+ add: zod.array(kindSchema).optional(),
131
+ remove: zod.array(kindSchema).optional()
132
+ })
133
+ ]));
134
+ const resolveDependencyRules = (config = {})=>{
135
+ const entries = moduleKinds.map((kind)=>{
136
+ const override = config[kind];
137
+ if (Array.isArray(override)) return [
138
+ kind,
139
+ new Set(override)
140
+ ];
141
+ const kinds = new Set([
142
+ ...defaultDependencies[kind],
143
+ ...override?.add ?? []
144
+ ]);
145
+ for (const removed of override?.remove ?? [])kinds.delete(removed);
146
+ return [
147
+ kind,
148
+ kinds
149
+ ];
150
+ });
151
+ return Object.fromEntries(entries);
152
+ };
153
+ const defaultDependencyRules = resolveDependencyRules();
154
+ const isModuleKind = (value)=>moduleKinds.includes(value);
155
+ const wiredModuleKind = (wiringKind)=>isModuleKind(wiringKind) ? wiringKind : void 0;
156
+ const fileModuleKind = (segments)=>{
157
+ const [layer, folder] = segments;
158
+ const file = segments.at(-1) ?? '';
159
+ if (/^index(\.tsx?)?$/.test(file)) return;
160
+ if ('domain' === layer) {
161
+ if ('services' === folder) return 'domain-services';
162
+ return 'aggregates' === folder && /-repository(\.tsx?)?$/.test(file) ? 'repositories' : void 0;
163
+ }
164
+ if ('application' === layer) return ({
165
+ commands: 'commands',
166
+ queries: 'queries',
167
+ ports: 'application-ports',
168
+ services: 'application-services',
169
+ 'use-cases': 'use-cases'
170
+ })[folder];
171
+ if ('infrastructure' === layer) return ({
172
+ repositories: 'repositories',
173
+ commands: 'commands',
174
+ queries: 'queries',
175
+ 'application-adapters': 'application-ports',
176
+ services: 'infrastructure-services'
177
+ })[folder];
178
+ return 'presentation' === layer && 'services' === folder ? 'presentation-services' : void 0;
179
+ };
180
+ const pendingFiles = new Map();
181
+ const pendingFolders = new Set();
182
+ const pendingMoves = new Map();
183
+ const pendingDeletions = new Map();
184
+ const filesToOverwrite = ({ changedOnly = false } = {})=>[
185
+ ...pendingFiles
186
+ ].filter(([filePath, { replacesFile, content }])=>replacesFile && node_fs.existsSync(filePath) && (!changedOnly || node_fs.readFileSync(filePath, 'utf8') !== content)).map(([filePath])=>filePath);
187
+ const pendingChanges = ()=>({
188
+ created: [
189
+ ...new Set([
190
+ ...[
191
+ ...pendingFiles.keys()
192
+ ].filter((file)=>!node_fs.existsSync(file)),
193
+ ...pendingMoves.keys()
194
+ ])
195
+ ].sort(),
196
+ updated: [
197
+ ...pendingFiles
198
+ ].filter(([file, change])=>node_fs.existsSync(file) && node_fs.readFileSync(file, 'utf8') !== change.content).map(([file])=>file).sort(),
199
+ deleted: [
200
+ ...new Set([
201
+ ...pendingDeletions.keys(),
202
+ ...[
203
+ ...pendingMoves.values()
204
+ ].map((move)=>move.sourcePath)
205
+ ])
206
+ ].sort(),
207
+ directories: [
208
+ ...pendingFolders
209
+ ].filter((folder)=>!node_fs.existsSync(folder)).sort()
210
+ });
211
+ const withoutOverwrites = (generate)=>{
212
+ const before = new Map(pendingFiles);
213
+ const result = generate();
214
+ for (const [filePath, change] of pendingFiles){
215
+ if (before.get(filePath) === change || !change.replacesFile || !node_fs.existsSync(filePath)) continue;
216
+ const previous = before.get(filePath);
217
+ if (previous) pendingFiles.set(filePath, previous);
218
+ else pendingFiles.delete(filePath);
219
+ }
220
+ return result;
221
+ };
222
+ const discardPendingChanges = ()=>{
223
+ pendingFolders.clear();
224
+ pendingFiles.clear();
225
+ pendingMoves.clear();
226
+ pendingDeletions.clear();
227
+ };
228
+ const removeEmptyFolders = (folderPath, stopAt)=>{
229
+ let current = folderPath;
230
+ while(current.startsWith(`${stopAt}${node_path.sep}`) && node_fs.existsSync(current) && !node_fs.readdirSync(current).length){
231
+ node_fs.rmdirSync(current);
232
+ current = node_path.dirname(current);
233
+ }
234
+ };
235
+ const writePendingChanges = ()=>{
236
+ for (const folderPath of pendingFolders)node_fs.mkdirSync(folderPath, {
237
+ recursive: true
238
+ });
239
+ for (const [filePath, { content }] of pendingFiles){
240
+ node_fs.mkdirSync(node_path.dirname(filePath), {
241
+ recursive: true
242
+ });
243
+ node_fs.writeFileSync(filePath, content, 'utf8');
244
+ }
245
+ for (const [targetPath, { sourcePath }] of pendingMoves){
246
+ node_fs.mkdirSync(node_path.dirname(targetPath), {
247
+ recursive: true
248
+ });
249
+ node_fs.renameSync(sourcePath, targetPath);
250
+ }
251
+ for (const filePath of pendingDeletions.keys())node_fs.rmSync(filePath, {
252
+ force: true
253
+ });
254
+ for (const [filePath, stopAt] of pendingDeletions)removeEmptyFolders(node_path.dirname(filePath), stopAt);
255
+ for (const { sourcePath, stopAt } of pendingMoves.values())removeEmptyFolders(node_path.dirname(sourcePath), stopAt);
256
+ discardPendingChanges();
257
+ };
258
+ class FileSystemItem {
259
+ path;
260
+ constructor(path){
261
+ this.path = path;
262
+ }
263
+ subitem = (relativePath)=>new this.constructor(node_path.resolve(this.path, ...relativePath));
264
+ get exists() {
265
+ return node_fs.existsSync(this.path);
266
+ }
267
+ }
268
+ class Folder extends FileSystemItem {
269
+ createIfNotExisted = ()=>{
270
+ pendingFolders.add(this.path);
271
+ };
272
+ get content() {
273
+ if (!this.exists) return {
274
+ subfolderNames: [],
275
+ fileNames: []
276
+ };
277
+ const content = node_fs.readdirSync(this.path, {
278
+ withFileTypes: true
279
+ });
280
+ return {
281
+ subfolderNames: content.filter((x)=>x.isDirectory()).map((x)=>x.name),
282
+ fileNames: content.filter((x)=>!x.isDirectory()).map((x)=>node_path.parse(x.name).name)
283
+ };
284
+ }
285
+ get name() {
286
+ return node_path.basename(this.path);
287
+ }
288
+ createFile = (name, content)=>{
289
+ this.createIfNotExisted();
290
+ const file = new File(this.path).subitem([
291
+ name
292
+ ]);
293
+ file.data = content;
294
+ return file;
295
+ };
296
+ file = (name)=>{
297
+ this.createIfNotExisted();
298
+ const file = new File(this.path).subitem([
299
+ name
300
+ ]);
301
+ return file;
302
+ };
303
+ }
304
+ class File extends FileSystemItem {
305
+ get exists() {
306
+ return pendingFiles.has(this.path) || pendingMoves.has(this.path) || node_fs.existsSync(this.path) && !pendingDeletions.has(this.path);
307
+ }
308
+ delete = (stopAt)=>{
309
+ pendingDeletions.set(this.path, stopAt);
310
+ };
311
+ moveTo = (targetPath, stopAt)=>{
312
+ pendingMoves.set(targetPath, {
313
+ sourcePath: this.path,
314
+ stopAt
315
+ });
316
+ };
317
+ get data() {
318
+ const pendingFile = pendingFiles.get(this.path);
319
+ if (pendingFile) return pendingFile.content;
320
+ if (!this.exists) throw new Error('File does not exist');
321
+ return node_fs.readFileSync(this.path, 'utf-8');
322
+ }
323
+ set data(content) {
324
+ pendingFiles.set(this.path, {
325
+ content,
326
+ replacesFile: true
327
+ });
328
+ }
329
+ update = (content)=>{
330
+ pendingFiles.set(this.path, {
331
+ content,
332
+ replacesFile: pendingFiles.get(this.path)?.replacesFile ?? false
333
+ });
334
+ };
335
+ addLine = (newLine, separator = '\n')=>{
336
+ const content = this.exists ? this.data : '';
337
+ pendingFiles.set(this.path, {
338
+ content: [
339
+ content.trim(),
340
+ newLine.trim()
341
+ ].filter((x)=>!!x).join(separator),
342
+ replacesFile: pendingFiles.get(this.path)?.replacesFile ?? false
343
+ });
344
+ };
345
+ addLineIfMissing = (newLine, separator = '\n')=>{
346
+ const normalized = (line)=>line.trim().replace(/;$/, '');
347
+ const alreadyAdded = this.exists && this.data.split('\n').some((line)=>normalized(line) === normalized(newLine));
348
+ if (!alreadyAdded) this.addLine(newLine, separator);
349
+ };
350
+ }
351
+ class ProjectRoot {
352
+ path;
353
+ constructor(){
354
+ let dir = process.cwd();
355
+ while(dir !== node_path.parse(dir).root){
356
+ if (node_fs.existsSync(node_path.join(dir, 'package.json'))) {
357
+ this.path = dir;
358
+ return;
359
+ }
360
+ dir = node_path.dirname(dir);
361
+ }
362
+ throw new Error('No package.json was found');
363
+ }
364
+ }
365
+ const lintChecks = [
366
+ 'context-isolation',
367
+ 'shared-kernel',
368
+ 'layers',
369
+ 'dependencies',
370
+ 'react',
371
+ 'clock',
372
+ 'config'
373
+ ];
374
+ const configFileName = 'domain-first.project-structure.config.json';
375
+ const projectConfigSchema = zod.object({
376
+ rootFolder: zod.string().min(1)
377
+ }).passthrough();
378
+ const domainFirstPackages = [
379
+ '@domain-first/types',
380
+ '@domain-first/errors',
381
+ '@domain-first/handlers',
382
+ '@domain-first/wire',
383
+ '@domain-first/handlers-rest'
384
+ ];
385
+ const rulesSchema = zod.object({
386
+ dependencies: dependencyRulesSchema.optional(),
387
+ lint: zod.partialRecord(zod["enum"](lintChecks), zod.boolean()).optional()
388
+ });
389
+ const branchNameSchema = zod.string().regex(/^[a-z][a-z0-9]*$/, 'Use lowercase letters and digits, e.g. staging.');
390
+ const envBranchesSchema = zod.object({
391
+ names: zod.array(branchNameSchema).min(1),
392
+ test: branchNameSchema.optional()
393
+ }).refine(({ names })=>new Set(names).size === names.length, {
394
+ message: 'Branch names must be unique.'
395
+ }).refine(({ names, test })=>void 0 === test || names.includes(test), {
396
+ message: 'The test branch must be one of the branches.'
397
+ }).refine(({ names, test })=>void 0 === test || names.length > 1, {
398
+ message: 'The primary implementation needs a branch besides the test one.'
399
+ });
400
+ const backendConfigSchema = zod.object({
401
+ domainFirstPackages: zod.array(zod["enum"](domainFirstPackages)),
402
+ envBranches: envBranchesSchema.optional(),
403
+ withInMemoryDb: zod.boolean().optional(),
404
+ testingLibrary: zod.string().optional(),
405
+ implementations: implementationOptionsSchema.optional(),
406
+ rules: rulesSchema.optional()
407
+ }).passthrough();
408
+ const reactConfigSchema = zod.object({
409
+ framework: zod["enum"]([
410
+ 'react',
411
+ 'next'
412
+ ]).optional(),
413
+ storybookFramework: zod.string().optional()
414
+ }).passthrough();
415
+ const frontendConfigSchema = zod.object({
416
+ react: reactConfigSchema.optional()
417
+ }).passthrough();
418
+ const configSchema = zod.object({
419
+ project: projectConfigSchema,
420
+ backend: backendConfigSchema.optional(),
421
+ frontend: frontendConfigSchema.optional()
422
+ }).passthrough();
423
+ const scaffoldBackendRules = (rules = {})=>({
424
+ dependencies: {
425
+ ...Object.fromEntries(Object.entries(defaultDependencies).map(([kind, dependencies])=>[
426
+ kind,
427
+ [
428
+ ...dependencies
429
+ ]
430
+ ])),
431
+ ...rules.dependencies
432
+ },
433
+ lint: {
434
+ ...Object.fromEntries(lintChecks.map((check)=>[
435
+ check,
436
+ true
437
+ ])),
438
+ ...rules.lint
439
+ }
440
+ });
441
+ const isOutdatedConfig = (value)=>'object' == typeof value && null !== value && !Array.isArray(value) && !('project' in value);
442
+ const outdatedConfigMessage = `${configFileName} uses the format of an earlier major version: run npx df-upgrade.`;
443
+ class ConfigOutdatedError extends Error {
444
+ constructor(){
445
+ super(outdatedConfigMessage);
446
+ }
447
+ }
448
+ class ConfigFile {
449
+ data;
450
+ constructor(){
451
+ const raw = JSON.parse(new File(ConfigFile.path).data);
452
+ if (isOutdatedConfig(raw)) throw new ConfigOutdatedError();
453
+ this.data = configSchema.parse(raw);
454
+ }
455
+ static get Instance() {
456
+ return new ConfigFile();
457
+ }
458
+ static get backend() {
459
+ const backend = ConfigFile.Instance.data.backend;
460
+ if (!backend) throw new Error('Backend is not configured: run df-init --section backend.');
461
+ return backend;
462
+ }
463
+ static get path() {
464
+ return node_path.resolve(new ProjectRoot().path, configFileName);
465
+ }
466
+ static get exists() {
467
+ return new File(ConfigFile.path).exists;
468
+ }
469
+ static get outdated() {
470
+ if (!ConfigFile.exists) return false;
471
+ try {
472
+ return isOutdatedConfig(JSON.parse(new File(ConfigFile.path).data));
473
+ } catch {
474
+ return false;
475
+ }
476
+ }
477
+ static write = (config)=>{
478
+ ConfigFile.stage(configSchema.parse(config));
479
+ };
480
+ static update = (sections)=>{
481
+ ConfigFile.stage(configSchema.parse({
482
+ ...ConfigFile.Instance.data,
483
+ ...sections
484
+ }));
485
+ };
486
+ static stage(config) {
487
+ new File(ConfigFile.path).update(`${JSON.stringify(config, null, 4)}\n`);
488
+ }
489
+ }
490
+ const configuredDependencyRules = ()=>resolveDependencyRules(ConfigFile.exists ? ConfigFile.Instance.data.backend?.rules?.dependencies : void 0);
47
491
  class UnknownFormatNaming {
48
492
  rawSource;
49
493
  camelCase;
@@ -479,4 +923,37 @@ const addBranchedImplementation = (source, wireName, implementation)=>{
479
923
  const withWireClass = `${withImport.slice(0, declarationIndex)}const ${implementation.wireName} = wireClass(${implementation.className}, [])\n\n${withImport.slice(declarationIndex)}`;
480
924
  return setWireBranches(withWireClass, wireName, implementation.environments, implementation.wireName);
481
925
  };
482
- export { UnknownFormatNaming, addBranchedImplementation, addClassMember, addConstructorParameters, addImport, addWireDependencies, availableDependencies, boundedContextLocation, canDependOn, crossContextImplementation, crossContextImportAllowed, findWiredModules, hasNeighboringBoundedContext, implementationType, isCrossContextImplementation, isSuggestedFor, moduleKindOf, namedImportFiles, readWiredModule, relativeImport, wireBranches, wireDependencies, wiredDependencyNames, wiring_layers };
926
+ const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
927
+ const resolveExtends = (fromFile, target)=>{
928
+ if (target.startsWith('.') || node_path.isAbsolute(target)) {
929
+ const resolved = node_path.resolve(node_path.dirname(fromFile), target);
930
+ return resolved.endsWith('.json') ? resolved : `${resolved}.json`;
931
+ }
932
+ const require = createRequire(fromFile);
933
+ for (const candidate of [
934
+ target,
935
+ `${target}/tsconfig.json`
936
+ ])try {
937
+ return require.resolve(candidate);
938
+ } catch {}
939
+ };
940
+ const compilerOption = (configFile, name, seen = new Set())=>{
941
+ if (seen.has(configFile) || !node_fs.existsSync(configFile)) return null;
942
+ seen.add(configFile);
943
+ let config;
944
+ try {
945
+ config = JSON.parse(stripJsonComments(node_fs.readFileSync(configFile, 'utf8')));
946
+ } catch {
947
+ return null;
948
+ }
949
+ if (config.compilerOptions && name in config.compilerOptions) return config.compilerOptions[name];
950
+ const parents = [
951
+ config.extends ?? []
952
+ ].flat().reverse();
953
+ for (const parent of parents){
954
+ const parentFile = resolveExtends(configFile, parent);
955
+ const value = parentFile ? compilerOption(parentFile, name, seen) : null;
956
+ if (void 0 !== value) return value;
957
+ }
958
+ };
959
+ export { ConfigFile, File, Folder, ProjectRoot, UnknownFormatNaming, addBranchedImplementation, addClassMember, addConstructorParameters, addImport, addWireDependencies, availableDependencies, boundedContextLocation, branchNameSchema, canDependOn, compilerOption, configFileName, configSchema, configuredDependencyRules, crossContextImplementation, crossContextImportAllowed, defaultDependencyRules, discardPendingChanges, domainFirstPackages, fileModuleKind, filesToOverwrite, findWiredModules, hasNeighboringBoundedContext, implementationKinds, implementationLabelSchema, implementationType, isCrossContextImplementation, isOutdatedConfig, isSuggestedFor, moduleKindOf, namedImportFiles, outdatedConfigMessage, pendingChanges, readWiredModule, relativeImport, rulesSchema, scaffoldBackendRules, stripJsonComments, wireBranches, wireDependencies, wiredDependencyNames, wiring_layers, withoutOverwrites, writePendingChanges };