@domain-first/project-structure 8.8.0 → 8.9.1

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