@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.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/lint.js ADDED
@@ -0,0 +1,296 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from "node:util";
3
+ import node_fs from "node:fs";
4
+ import node_path from "node:path";
5
+ import { defaultDependencyRules, fileModuleKind, canDependOn, moduleKindOf, findWiredModules, configuredDependencyRules, ConfigFile, ProjectRoot, compilerOption, wiredDependencyNames } from "./201.js";
6
+ const readAliases = (projectRoot)=>{
7
+ const tsconfig = node_path.join(projectRoot, 'tsconfig.json');
8
+ const paths = compilerOption(tsconfig, 'paths');
9
+ if (!paths || 'object' != typeof paths) return [];
10
+ const baseUrl = compilerOption(tsconfig, 'baseUrl');
11
+ const base = node_path.resolve(projectRoot, 'string' == typeof baseUrl ? baseUrl : '.');
12
+ return Object.entries(paths).filter(([, targets])=>targets.length).map(([key, [target]])=>{
13
+ const wildcard = key.endsWith('*');
14
+ return {
15
+ prefix: wildcard ? key.slice(0, -1) : key,
16
+ wildcard,
17
+ target: node_path.resolve(base, wildcard ? target.replace(/\*$/, '') : target)
18
+ };
19
+ }).sort((a, b)=>b.prefix.length - a.prefix.length);
20
+ };
21
+ const resolveSpecifier = (specifier, fromFile, aliases)=>{
22
+ if (specifier.startsWith('.')) return node_path.resolve(node_path.dirname(fromFile), specifier);
23
+ for (const { prefix, wildcard, target } of aliases)if (wildcard ? specifier.startsWith(prefix) : specifier === prefix) return node_path.join(target, wildcard ? specifier.slice(prefix.length) : '');
24
+ };
25
+ const inside = (folder, file)=>{
26
+ const relativePath = node_path.relative(folder, file);
27
+ return !relativePath || relativePath.startsWith('..') || node_path.isAbsolute(relativePath) ? void 0 : relativePath.split(node_path.sep);
28
+ };
29
+ const sourceFiles = (folder)=>{
30
+ if (!node_fs.existsSync(folder)) return [];
31
+ return node_fs.readdirSync(folder, {
32
+ withFileTypes: true
33
+ }).flatMap((entry)=>{
34
+ const entryPath = node_path.join(folder, entry.name);
35
+ if (entry.isDirectory()) return 'node_modules' === entry.name ? [] : sourceFiles(entryPath);
36
+ return /\.(c|m)?tsx?$/.test(entry.name) && !entry.name.endsWith('.d.ts') ? [
37
+ entryPath
38
+ ] : [];
39
+ });
40
+ };
41
+ 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;
42
+ const lineAt = (source, index)=>source.slice(0, index).split('\n').length;
43
+ const importsOf = (source, file, aliases)=>[
44
+ ...source.matchAll(importPattern)
45
+ ].map((match)=>({
46
+ typeOnly: 'import' === match[1] && Boolean(match[2]),
47
+ target: resolveSpecifier(match[4], file, aliases),
48
+ line: lineAt(source, match.index),
49
+ statement: match[0].replace(/\s+/g, ' ')
50
+ }));
51
+ const isSpec = (file)=>/\.(spec|test)\.(c|m)?tsx?$/.test(file);
52
+ const layerImportRules = {
53
+ domain: {
54
+ allows: ([layer])=>'domain' === layer,
55
+ rule: 'domain imports outside the domain layer:'
56
+ },
57
+ application: {
58
+ allows: ([layer])=>'domain' === layer || 'application' === layer,
59
+ rule: 'application imports outside domain and application:'
60
+ },
61
+ infrastructure: {
62
+ allows: ([layer, part, mode])=>'domain' === layer || 'infrastructure' === layer || 'application' === layer && ('ports' === part || ('commands' === part || 'queries' === part) && 'execution' === mode),
63
+ rule: 'infrastructure imports outside domain, infrastructure, application ports and execution contracts:'
64
+ },
65
+ presentation: {
66
+ allows: ([layer])=>'infrastructure' !== layer,
67
+ rule: 'presentation imports infrastructure (only wiring knows concrete classes):'
68
+ }
69
+ };
70
+ const baseName = (file)=>node_path.basename(file).replace(/\.[^.]+$/, '');
71
+ const isOwnContract = (file, target)=>baseName(file).endsWith(`-${baseName(target)}`);
72
+ const importViolations = (projectRoot, rootFolder, rules)=>{
73
+ const root = node_path.resolve(projectRoot, rootFolder);
74
+ const contextsFolder = node_path.join(root, 'bounded-contexts');
75
+ const sharedFolder = node_path.join(root, 'shared');
76
+ const reactFolder = node_path.join(root, 'presentation', 'react');
77
+ const uiKitFolder = node_path.join(reactFolder, 'ui-kit');
78
+ const widgetsFolder = node_path.join(reactFolder, 'widgets');
79
+ const hooksFolder = node_path.join(reactFolder, 'hooks');
80
+ const inMemoryDbFile = node_path.join(sharedFolder, 'infrastructure', 'services', 'in-memory-db-infrastructure-service.ts');
81
+ const aliases = readAliases(projectRoot);
82
+ const violations = [];
83
+ const locate = (file)=>{
84
+ const inContext = inside(contextsFolder, file);
85
+ if (inContext && inContext.length > 1) {
86
+ const [owner, ...segments] = inContext;
87
+ return {
88
+ owner,
89
+ segments
90
+ };
91
+ }
92
+ const inShared = inside(sharedFolder, file);
93
+ return inShared && {
94
+ owner: 'shared',
95
+ segments: inShared
96
+ };
97
+ };
98
+ const isDomainModel = ([layer, part], target)=>'domain' === layer && [
99
+ 'aggregates',
100
+ 'entities',
101
+ 'value-objects'
102
+ ].includes(part) && !/-repository(\.tsx?)?$/.test(node_path.basename(target));
103
+ const widgetFolders = new Map();
104
+ const isWidgetFolder = (folder)=>{
105
+ if (!widgetFolders.has(folder)) widgetFolders.set(folder, node_fs.existsSync(folder) && node_fs.statSync(folder).isDirectory() && node_fs.readdirSync(folder).some((name)=>name.endsWith('-widget.tsx')));
106
+ return widgetFolders.get(folder);
107
+ };
108
+ const widgetOf = (file)=>{
109
+ for(let folder = file; inside(widgetsFolder, folder); folder = node_path.dirname(folder))if (isWidgetFolder(folder)) return folder;
110
+ };
111
+ const files = [
112
+ contextsFolder,
113
+ sharedFolder,
114
+ reactFolder
115
+ ].flatMap(sourceFiles);
116
+ for (const file of files){
117
+ const source = node_fs.readFileSync(file, 'utf8');
118
+ const from = locate(file);
119
+ const ownContext = inside(contextsFolder, file)?.[0];
120
+ const report = (check, rule, imported)=>violations.push({
121
+ check,
122
+ rule,
123
+ file,
124
+ line: imported.line,
125
+ text: imported.statement
126
+ });
127
+ for (const imported of importsOf(source, file, aliases)){
128
+ const target = imported.target;
129
+ if (!target) continue;
130
+ const to = locate(target);
131
+ const targetContext = inside(contextsFolder, target)?.[0];
132
+ if (ownContext) {
133
+ if (targetContext && targetContext !== ownContext) report('context-isolation', `[${ownContext}] imports another context:`, imported);
134
+ } else if (inside(sharedFolder, file)) {
135
+ const allowed = !to || 'shared' === to.owner || 'domain' === to.segments[0] && 'errors' === to.segments[1] || file === inMemoryDbFile && isDomainModel(to.segments, target);
136
+ if (!allowed) report('shared-layer', '[shared] imports a bounded context outside its domain/errors (and domain models for the in-memory DB):', imported);
137
+ } else if (inside(uiKitFolder, file) || inside(hooksFolder, file)) {
138
+ const [area] = inside(reactFolder, target) ?? [];
139
+ const forbidden = inside(uiKitFolder, file) ? [
140
+ 'widgets',
141
+ 'pages'
142
+ ] : [
143
+ 'ui-kit',
144
+ 'widgets',
145
+ 'pages'
146
+ ];
147
+ 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);
148
+ } 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);
149
+ const ownWidget = widgetOf(file);
150
+ const targetWidget = widgetOf(target);
151
+ if (ownWidget && targetWidget && targetWidget !== ownWidget) report('react', '[presentation/react/widgets] a widget imports another widget:', imported);
152
+ if (!from || !to) continue;
153
+ if (isSpec(file)) continue;
154
+ const fromKind = fileModuleKind(from.segments);
155
+ const toKind = fileModuleKind(to.segments);
156
+ if (fromKind && toKind) {
157
+ if (!rules[fromKind].has(toKind) && !(fromKind === toKind && isOwnContract(file, target))) report('dependencies', `[${from.owner}] ${fromKind} may not use ${toKind} (dependency rules):`, imported);
158
+ if ('infrastructure' !== to.segments[0]) continue;
159
+ }
160
+ const layerRule = layerImportRules[from.segments[0]];
161
+ if (layerRule && !layerRule.allows(to.segments)) report('layers', `[${from.owner}] ${layerRule.rule}`, imported);
162
+ }
163
+ }
164
+ return violations;
165
+ };
166
+ const wiringViolations = (projectRoot, rootFolder, rules)=>{
167
+ const root = node_path.resolve(projectRoot, rootFolder);
168
+ const sharedFolder = node_path.join(root, 'shared');
169
+ const contextsFolder = node_path.join(root, 'bounded-contexts');
170
+ const sharedModules = findWiredModules(sharedFolder);
171
+ const owners = [
172
+ {
173
+ name: 'shared',
174
+ modules: sharedModules
175
+ },
176
+ ...node_fs.existsSync(contextsFolder) ? node_fs.readdirSync(contextsFolder, {
177
+ withFileTypes: true
178
+ }).filter((entry)=>entry.isDirectory()).map((entry)=>({
179
+ name: entry.name,
180
+ modules: findWiredModules(node_path.join(contextsFolder, entry.name))
181
+ })) : []
182
+ ];
183
+ const violations = [];
184
+ for (const { name, modules } of owners){
185
+ const visible = new Map([
186
+ ...sharedModules,
187
+ ...modules
188
+ ].map((x)=>[
189
+ x.wireName,
190
+ x
191
+ ]));
192
+ for (const consumer of modules){
193
+ const source = node_fs.readFileSync(consumer.wireFile, 'utf8');
194
+ for (const implementation of consumer.implementations){
195
+ let dependencies;
196
+ try {
197
+ dependencies = wiredDependencyNames(source, implementation.className);
198
+ } catch {
199
+ continue;
200
+ }
201
+ const listStart = source.search(new RegExp(`wireClass\\(\\s*${implementation.className}\\b`));
202
+ for (const dependency of dependencies){
203
+ const candidate = visible.get(dependency);
204
+ if (!candidate || canDependOn(consumer, candidate, rules)) continue;
205
+ const index = source.indexOf(dependency, listStart);
206
+ violations.push({
207
+ check: 'dependencies',
208
+ rule: `[${name}] wiring: a dependency the dependency rules don't allow:`,
209
+ file: consumer.wireFile,
210
+ line: lineAt(source, index),
211
+ text: `${implementation.className} (${moduleKindOf(consumer) ?? consumer.kind}) ← ${candidate.typeName} (${moduleKindOf(candidate) ?? candidate.kind})`
212
+ });
213
+ }
214
+ }
215
+ }
216
+ }
217
+ return violations;
218
+ };
219
+ const clockViolations = (projectRoot, rootFolder)=>{
220
+ const root = node_path.resolve(projectRoot, rootFolder);
221
+ const folders = [
222
+ node_path.join(root, 'shared'),
223
+ ...node_fs.existsSync(node_path.join(root, 'bounded-contexts')) ? node_fs.readdirSync(node_path.join(root, 'bounded-contexts')).map((name)=>node_path.join(root, 'bounded-contexts', name)) : []
224
+ ].flatMap((folder)=>[
225
+ node_path.join(folder, 'domain'),
226
+ node_path.join(folder, 'application')
227
+ ]);
228
+ return folders.flatMap(sourceFiles).filter((file)=>!isSpec(file)).flatMap((file)=>{
229
+ const source = node_fs.readFileSync(file, 'utf8');
230
+ return [
231
+ ...source.matchAll(/\bnew\s+Date\s*\(\s*\)|\bDate\.now\s*\(/g)
232
+ ].map((match)=>({
233
+ check: 'clock',
234
+ rule: 'domain or application reads the current time directly (use the clock port):',
235
+ file,
236
+ line: lineAt(source, match.index),
237
+ text: match[0]
238
+ }));
239
+ });
240
+ };
241
+ const lintProject = (projectRoot, rootFolder, { rules = defaultDependencyRules, checks = {} } = {})=>[
242
+ ...importViolations(projectRoot, rootFolder, rules),
243
+ ...wiringViolations(projectRoot, rootFolder, rules),
244
+ ...clockViolations(projectRoot, rootFolder)
245
+ ].filter((x)=>false !== checks[x.check]);
246
+ const formatViolations = (violations, projectRoot)=>{
247
+ const groups = new Map();
248
+ for (const { rule, file, line, text } of violations)groups.set(rule, [
249
+ ...groups.get(rule) ?? [],
250
+ ` ${node_path.relative(projectRoot, file)}:${line}: ${text}`
251
+ ]);
252
+ return [
253
+ ...groups
254
+ ].map(([rule, lines])=>[
255
+ rule,
256
+ ...lines
257
+ ].join('\n')).join('\n\n');
258
+ };
259
+ const help = `Usage: df-lint [rootFolder]
260
+
261
+ Reports what breaks the Domain-First rules in the project:
262
+ bounded context isolation, layers, dependency rules (imports and wiring),
263
+ React modules, and reading the time without the clock port.
264
+ rootFolder defaults to the one in domain-first.project-structure.config.json,
265
+ whose optional \`rules\` change the dependency rules and turn checks off.
266
+ Exits with 1 when something is found.
267
+
268
+ Options:
269
+ -h, --help show this help`;
270
+ const { values: values, positionals: positionals } = parseArgs({
271
+ allowPositionals: true,
272
+ options: {
273
+ help: {
274
+ type: 'boolean',
275
+ short: 'h',
276
+ default: false
277
+ }
278
+ }
279
+ });
280
+ if (values.help) {
281
+ console.log(help);
282
+ process.exit(0);
283
+ }
284
+ const lint_projectRoot = new ProjectRoot().path;
285
+ const config = ConfigFile.exists ? ConfigFile.Instance.data : void 0;
286
+ const lint_rootFolder = positionals[0] ?? config?.rootFolder ?? 'src';
287
+ const lint_violations = lintProject(lint_projectRoot, lint_rootFolder, {
288
+ rules: configuredDependencyRules(),
289
+ checks: config?.rules?.lint
290
+ });
291
+ if (lint_violations.length) {
292
+ console.log(formatViolations(lint_violations, lint_projectRoot));
293
+ console.log(`\n${lint_violations.length} problem(s) found.`);
294
+ process.exit(1);
295
+ }
296
+ console.log('OK: no Domain-First rule violations.');
@@ -0,0 +1,27 @@
1
+ import type { LintCheck } from './config-file';
2
+ import { type DependencyRules } from './dependency-rules';
3
+ export type Violation = {
4
+ /**
5
+ * The check that found it, which `rules.lint` can turn off.
6
+ */
7
+ check: LintCheck;
8
+ /**
9
+ * The broken rule, as printed above its violations.
10
+ */
11
+ rule: string;
12
+ file: string;
13
+ line: number;
14
+ text: string;
15
+ };
16
+ export type LintOptions = {
17
+ rules?: DependencyRules;
18
+ /**
19
+ * Checks turned off with `false`; the others run.
20
+ */
21
+ checks?: Partial<Record<LintCheck, boolean>>;
22
+ };
23
+ export declare const lintProject: (projectRoot: string, rootFolder: string, { rules, checks }?: LintOptions) => Violation[];
24
+ /**
25
+ * Violations grouped under their rules, with paths from the project root.
26
+ */
27
+ export declare const formatViolations: (violations: Violation[], projectRoot: string) => string;
@@ -0,0 +1 @@
1
+ export {};
package/dist/wiring.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type DependencyRules } from './dependency-rules';
1
2
  export declare const layers: readonly ["domain", "application", "infrastructure", "presentation"];
2
3
  export type Layer = (typeof layers)[number];
3
4
  /**
@@ -43,6 +44,10 @@ export type WiredModule = {
43
44
  };
44
45
  export declare const readWiredModule: (wireFile: string, contextPath: string) => WiredModule | undefined;
45
46
  export declare const findWiredModules: (contextPath: string) => WiredModule[];
47
+ /**
48
+ * The kind a module has in the dependency rules.
49
+ */
50
+ export declare const moduleKindOf: (module: WiredModule) => "repositories" | "domain-services" | "application-ports" | "application-services" | "use-cases" | "execution-commands" | "execution-queries" | "orchestration-commands" | "orchestration-queries" | "infrastructure-services" | "presentation-services" | undefined;
46
51
  /**
47
52
  * The implementation label of a branched wire's class, taken from its
48
53
  * folder: `infrastructure/repositories/prisma/…` → `prisma`.
@@ -53,13 +58,13 @@ export declare const implementationType: (consumer: WiredModule, implementation:
53
58
  * as whole words: `in-memory-db-infrastructure-service` for `in-memory`.
54
59
  */
55
60
  export declare const isSuggestedFor: (candidate: WiredModule, implementation: string) => boolean;
56
- export declare const canDependOn: (consumer: WiredModule, candidate: WiredModule) => boolean;
61
+ export declare const canDependOn: (consumer: WiredModule, candidate: WiredModule, rules?: DependencyRules) => boolean;
57
62
  /**
58
- * What an implementation of the consumer can depend on: modules of the
59
- * visible layers, except the consumer and what this implementation
60
- * already depends on.
63
+ * What an implementation of the consumer can depend on by the project's
64
+ * rules, except the consumer and what this implementation already
65
+ * depends on.
61
66
  */
62
- export declare const availableDependencies: (consumer: WiredModule, implementation: WiredClass, candidates: WiredModule[]) => WiredModule[];
67
+ export declare const availableDependencies: (consumer: WiredModule, implementation: WiredClass, candidates: WiredModule[], rules?: DependencyRules) => WiredModule[];
63
68
  /**
64
69
  * Import path without extension, always starting with `./` or `../`.
65
70
  */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@domain-first/project-structure",
3
3
  "description": "Build and manage your Domain-First project structure with CLI",
4
- "version": "4.0.0",
4
+ "version": "4.2.0",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -17,7 +17,8 @@
17
17
  },
18
18
  "bin": {
19
19
  "df-ps": "./dist/index.js",
20
- "df-skills": "./bin/df-skills.mjs"
20
+ "df-skills": "./bin/df-skills.mjs",
21
+ "df-lint": "./dist/lint.js"
21
22
  },
22
23
  "main": "./dist/index.cjs",
23
24
  "homepage": "https://domain-first-landing.vercel.app/scaffolder/",
@@ -15,6 +15,7 @@ Generated files contain placeholders: empty classes, `{}` schemas, `[]` dependen
15
15
  - Constructors take abstractions (`OrderRepository`, abstract `PlaceOrderCommand`, port `PaymentGateway`), never `PrismaOrderRepository`.
16
16
  - Implementation order: domain → application → schema tool runs (migrations, only if infrastructure needs data the database lacks) → infrastructure (repositories, execution commands/queries, adapters) → endpoints → other tool runs (OpenAPI, API client) → React. Widgets need the regenerated client. How to run tools and handle their output: the project's scripts skill (`project-scripts`), if there is one.
17
17
  - Run the project's tsc/lint/tests after each component.
18
+ - What each kind of module may use follows the defaults in these skills unless `rules.dependencies` in the config changes them; then follow the config, in imports as well as in wiring.
18
19
 
19
20
  ## Bounded context isolation
20
21
 
@@ -31,10 +32,18 @@ A file in context A imports **nothing** from context B: no types (`import type`
31
32
  Check before reporting done; fix every finding:
32
33
 
33
34
  ```bash
34
- node <this-skill-dir>/scripts/check-context-isolation.mjs [rootFolder]
35
+ npx df-lint [rootFolder]
35
36
  ```
36
37
 
37
- Run it from the project root; `rootFolder` defaults to the config's. It resolves relative paths and tsconfig `paths` aliases, and checks `import`/`export … from`, side-effect imports, `import()`, and `require()`. It also reports a widget importing another widget (a widget = the nearest folder under `presentation/react/widgets/` with a `*-widget.tsx`, nested widgets included).
38
+ Run it from the project root; `rootFolder` defaults to the config's. It resolves relative paths and tsconfig `paths` aliases, checks `import`/`export … from`, side-effect imports, `import()` and `require()`, and reports:
39
+
40
+ - imports across contexts, and from `shared/` or React outside the exceptions above;
41
+ - imports against the layers ("Ground rules"; specs excluded);
42
+ - module files importing kinds the project's dependency rules don't allow (a use case importing a use case, a query importing a command, …), and wired dependencies they don't allow ("Wiring" below, `df-ps-scaffold` rule 3); an implementation importing its own contract is fine;
43
+ - a widget importing another widget (a widget = the nearest folder under `presentation/react/widgets/` with a `*-widget.tsx`, nested widgets included), UI-kit importing widgets, pages or contexts, shared hooks importing UI-kit, widgets, pages or contexts;
44
+ - `new Date()` / `Date.now()` in domain or application (use the `clock` port).
45
+
46
+ It exits with 1 when anything is found. Checks turned off in the config (`rules.lint`) aren't reported; don't turn checks off yourself.
38
47
 
39
48
  ## Domain
40
49
 
@@ -58,7 +67,7 @@ export class Order extends domainType(
58
67
  ## Application
59
68
 
60
69
  - Use cases, commands, queries ({handlers}): the member is `handle = defineHandler({ inputSchema, outputSchema, handler })`. Replace the static `{}` schemas with real ones and write the logic in the `handler` callback; dependencies come through the constructor. Execution: the abstract contract holds the static schemas and `abstract handle`; each infrastructure implementation defines `handle` with the contract's schemas and writes only its `handler` callback. Orchestrator: a concrete class composing injected contracts. Call with `x.handle(input)` (returns a result) or `x.handle.unsafe(input)` (throws).
61
- - What a query or command may change: "Commonly confused" in `df-ps-scaffold/references/choosing-components.md`. Data a command returns goes in its output schema.
70
+ - A query only reads: it never changes data (not even idempotently) and never uses a command; an orchestrator query may use a repository, but calls only its reading methods (never `save`/`delete`); see "Commonly confused" in `df-ps-scaffold/references/choosing-components.md`. Data a command returns goes in its output schema.
62
71
  - Ports: abstract members in the port, one implementation per adapter (`api` real, `mock`/`fake` deterministic). Use the shared `clock` port instead of `new Date()`.
63
72
  - Services: what each kind may contain and call is in `choosing-components.md` (steps 13–16, "Port or service?"). Domain services take and return domain types. Application services have no `handle`.
64
73
 
@@ -9,14 +9,14 @@ description: Generate Domain-First components with the `df-ps` CLI (@domain-firs
9
9
 
10
10
  Follow this order for every request:
11
11
 
12
- 1. Read `domain-first.project-structure.config.json` (beside the nearest `package.json`). If missing, stop and tell the user to initialize the project with `npx df-ps` first.
12
+ 1. Read `domain-first.project-structure.config.json` (beside the nearest `package.json`). If missing, stop and tell the user to initialize the project with `npx df-ps` first. Its optional `rules.dependencies` changes what each kind of module may depend on; where it differs from the defaults in these skills, the config wins.
13
13
  2. Feature request without named contexts/components → `df-ps-plan-feature` (it covers steps 3–5).
14
14
  3. Choose a component for each piece of logic with `references/choosing-components.md`.
15
15
  4. Prepare the run details ("Preparing runs" below).
16
16
  5. If the task creates files, show the work plan and **stop until it's approved** (rule 1).
17
17
  6. Run the generators in plan order with the driver; check each output.
18
18
  7. Implement with `df-ps-implement`, in its order: domain → application → schema tool runs (migrations) → infrastructure → endpoints → other tool runs (OpenAPI, API client) → React.
19
- 8. Run `df-ps-implement/scripts/check-context-isolation.mjs` and the project's tsc/lint/tests.
19
+ 8. Run `npx df-lint` and the project's tsc/lint/tests.
20
20
  9. Report against the plan.
21
21
 
22
22
  ## Mandatory rules
@@ -82,7 +82,7 @@ Moving or renaming a page or widget is a df-ps run too (`Move or rename page` /
82
82
  With `@domain-first/wire`, every new dependency of a wired class (a constructor parameter plus its wire) is added by `df-ps`: the generator's `Dependencies:` step for a new module, `Wire dependency` for an existing one, and the `Handler:` pick for an endpoint (its generator is added automatically). Don't add constructor parameters or wire entries by hand, and don't reorder or remove the ones `df-ps` added.
83
83
 
84
84
  - List each module's dependencies in the plan as run options (`deps: OrderRepository`), with a `Wire dependency` run for existing modules.
85
- - A dependency the CLI doesn't offer is forbidden by the wiring rules (layer, kind, or another context): change the design (a port, an execution query or command, an infrastructure service) instead of adding it by hand.
85
+ - A dependency the CLI doesn't offer is forbidden by the project's dependency rules (the defaults, changed by `rules.dependencies` in the config) or by context isolation: change the design (a port, an execution query or command, an infrastructure service) instead of adding it by hand.
86
86
  - A value that isn't a wired module (a database or SDK client, a config value) lives in an infrastructure service named after the implementation label (`prisma`, `in-memory-db`, `stripe`): the service creates or reads it itself (`readonly client = new PrismaClient()`), with no constructor parameter for it. Implementations get the service through `df-ps`, where it shows up under `Suggested`. Wrap the service's wire in `memoWire(...)` when one instance must be shared (a connection pool, an in-memory store). No `wireValue(...)`. A domain or application module never gets such a value directly: it depends on a port whose adapter uses the service.
87
87
  - An endpoint generated with `handler: never` gets its handler by re-running the endpoint generator once the handler exists, as an approved overwrite.
88
88
 
@@ -1,6 +1,6 @@
1
1
  # Choosing the component for a piece of logic
2
2
 
3
- The only place where these rules live.
3
+ The only place where these rules live. What each kind of module may depend on is the default; `rules.dependencies` in the project's config can change it (e.g. let use cases call each other), and then the config wins.
4
4
 
5
5
  Split the request into pieces of logic (one responsibility each). For each piece, go through the steps **in order**: the first "yes" decides. A name the user used ("service", "gateway") is not a decision.
6
6
 
@@ -19,7 +19,7 @@ Split the request into pieces of logic (one responsibility each). For each piece
19
19
  | 9 | Data or behavior of **another context**? | **Execution query** (read) / **execution command** (write) in this context (see below) |
20
20
  | 10 | Leaves this context's code and storage: external system or time? | **Port** (+ adapters) |
21
21
  | 11 | One read/write on this context's own storage that isn't "load/save one aggregate" (read model, report, bulk update)? | **Execution command** (write) / **query** (read) |
22
- | 12 | A reusable read/write composed of other commands/queries/ports? | **Orchestrator command / query** |
22
+ | 12 | A reusable read/write composed of other commands/queries? | **Orchestrator command** (execution commands and queries) / **query** (execution queries and repositories only, calling only their reading methods) |
23
23
  | 13 | A rule at the junction of several entities / value objects not all belonging to one aggregate (a discount from purchase history and the current discount), no I/O? | **Domain service**, always |
24
24
  | 14 | Application logic reused by 2+ use cases, with any external interaction delegated to injected ports? | **Application service** |
25
25
  | 15 | A technical helper used only by infrastructure code? | **Infrastructure service** |
@@ -47,7 +47,7 @@ Example: `order-confirmation` prepares a message and calls the injected `mailer`
47
47
  | --- | --- |
48
48
  | Port / repository | Own aggregate's persistence → repository. External system → port. |
49
49
  | Port / execution command, query | Own storage or another context → command/query. External system → port. |
50
- | Query / command | A query reads; it may have side effects, but only idempotent ones: repeating it changes nothing further (filling a cache, creating default settings if missing). Any other state change → command. A command may return data (the created order, the new balance). |
50
+ | Query / command | A query only reads: it never changes any state, not even idempotently (no cache filling, no default settings created if missing), and never calls a command. Any state change → command. A command may return data (the created order, the new balance); an orchestrator command may also use execution queries. An orchestrator query may load aggregates through a repository, but never calls its writing methods (`save`, `delete`): the wiring can't forbid it, so it's on the developer. |
51
51
  | Domain service / entity, value object method | One entity / value object → its method. The junction of several → always a domain service, unless they all belong to one aggregate → a method on that aggregate. |
52
52
  | Domain / application service | Stated without requests, permissions, responses, scenarios → domain. Otherwise application. |
53
53
  | Use case / application service | Use case = one action with `handle`. Application service = helper used by use cases. |
@@ -6,7 +6,7 @@ Every step list starts with `"pick:Bounded Context: <ctx>"` or `"pick:Shared Lay
6
6
 
7
7
  Any generator: if the run would replace existing files, the last prompt is the confirm `Overwrite them?` (the files are listed above it). Without it, nothing extra is asked. Added lines (barrels, errors, wiring indexes) never trigger it.
8
8
 
9
- {wire} Generators that create a wire (all below except endpoints, which ask their own two selects) then ask the checkbox `Dependencies:`, before `Overwrite them?`. It lists wired modules of `<C>` and of the Shared Layer (`(shared)` suffix), grouped under headers in this order: Repositories, Domain services, Ports, Application services, Queries, Commands, Use cases, Infrastructure services, Presentation services. Inside a group: by type name, `<C>` first. Headers are not counted: `toggle:<n,..>` numbers only modules, top to bottom. Answer `toggle:<n,..>` or `none`. It is skipped when nothing fits, so check `<C>/wiring/` and `<rootFolder>/shared/wiring/` before counting steps. What fits depends on the layer of the class the wire builds: domain → domain; application → domain, application; infrastructure (repository, execution command/query, and port implementations, infrastructure services) → domain, application ports (of `<C>` and the Shared Layer; no other application modules), infrastructure; presentation → application, presentation. On top of that, application services see only ports from application, use cases never see use cases, repository implementations never see repositories, execution command/query implementations never see commands or queries, and orchestration commands/queries see only execution commands and queries from application. Endpoints are never listed. Each chosen module goes into the wire (`wireClass(X, [wireUserRepository])`) and the constructor (`private readonly userRepository: UserRepository`, with `import type`), in the same order. An env-branched wire (repository, execution command/query, port) wires each implementation in isolation: instead of `Dependencies:` it asks `Dependencies for <Implementation>:` once per implementation, in the order of the wire (main, then test). Each list leaves out only what that implementation already has, and a list with nothing to choose is skipped. It may start with a `Suggested` group: infrastructure modules whose file name has the implementation label (its folder, e.g. `prisma`, `in-memory`) as whole words, such as `in-memory-db-infrastructure-service` for `in-memory`. They are listed there only, so numbering starts with them, and they are **checked**: `none` keeps them, `toggle:<n>` on one of them unchecks it.
9
+ {wire} Generators that create a wire (all below except endpoints, which ask their own two selects) then ask the checkbox `Dependencies:`, before `Overwrite them?`. It lists wired modules of `<C>` and of the Shared Layer (`(shared)` suffix), grouped under headers in this order: Repositories, Domain services, Ports, Application services, Queries, Commands, Use cases, Infrastructure services, Presentation services. Inside a group: by type name, `<C>` first. Headers are not counted: `toggle:<n,..>` numbers only modules, top to bottom. Answer `toggle:<n,..>` or `none`. It is skipped when nothing fits, so check `<C>/wiring/` and `<rootFolder>/shared/wiring/` before counting steps. What fits depends on the layer of the class the wire builds: domain → domain; application → domain, application; infrastructure (repository, execution command/query, and port implementations, infrastructure services) → domain, application ports (of `<C>` and the Shared Layer; no other application modules), infrastructure; presentation → application, presentation. On top of that, application services see only ports from application, use cases never see use cases, repository implementations never see repositories, execution command/query implementations never see commands or queries, orchestration commands see only execution commands and queries from application, and orchestration queries only execution queries (repositories from domain stay available; they call only reading methods). These are the defaults: `rules.dependencies` in the config changes them per kind (`use-cases`, `orchestration-queries`, …), so count items from what the project's rules allow. Endpoints are never listed. Each chosen module goes into the wire (`wireClass(X, [wireUserRepository])`) and the constructor (`private readonly userRepository: UserRepository`, with `import type`), in the same order. An env-branched wire (repository, execution command/query, port) wires each implementation in isolation: instead of `Dependencies:` it asks `Dependencies for <Implementation>:` once per implementation, in the order of the wire (main, then test). Each list leaves out only what that implementation already has, and a list with nothing to choose is skipped. It may start with a `Suggested` group: infrastructure modules whose file name has the implementation label (its folder, e.g. `prisma`, `in-memory`) as whole words, such as `in-memory-db-infrastructure-service` for `in-memory`. They are listed there only, so numbering starts with them, and they are **checked**: `none` keeps them, `toggle:<n>` on one of them unchecks it.
10
10
 
11
11
  ## Bounded context
12
12