@domain-first/project-structure 8.10.1 → 8.12.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.
Files changed (58) hide show
  1. package/README.md +17 -7
  2. package/dist/287.js +406 -788
  3. package/dist/364.js +79 -0
  4. package/dist/38.js +31 -14
  5. package/dist/561.js +179 -96
  6. package/dist/783.js +1147 -0
  7. package/dist/{201.js → 878.js} +465 -2
  8. package/dist/agent-cli.d.ts +17 -6
  9. package/dist/agent-requests.d.ts +82 -8
  10. package/dist/config-file.d.ts +25 -1
  11. package/dist/frontend-cli.d.ts +3 -0
  12. package/dist/frontend-modules.d.ts +14 -0
  13. package/dist/graph.cjs +125 -5
  14. package/dist/graph.js +1 -1
  15. package/dist/index.cjs +3545 -2930
  16. package/dist/index.js +1 -1
  17. package/dist/init.cjs +368 -83
  18. package/dist/init.js +1 -1
  19. package/dist/integration.cjs +3545 -2930
  20. package/dist/integration.js +1 -1
  21. package/dist/integrations/openapi.d.ts +19 -2
  22. package/dist/integrations/orval.d.ts +31 -4
  23. package/dist/integrations/rest-endpoint-generator.d.ts +11 -7
  24. package/dist/integrations/storybook.d.ts +19 -1
  25. package/dist/lint.cjs +159 -22
  26. package/dist/lint.js +2 -2
  27. package/dist/page-router.d.ts +18 -0
  28. package/dist/react-module-move.d.ts +47 -14
  29. package/dist/react.cjs +1645 -999
  30. package/dist/react.js +2 -102
  31. package/dist/rest-adapters.d.ts +13 -0
  32. package/dist/svelte-agent-cli.spec.d.ts +1 -0
  33. package/dist/svelte.cjs +7373 -0
  34. package/dist/svelte.d.ts +2 -0
  35. package/dist/svelte.js +3 -0
  36. package/dist/sveltekit-app.d.ts +7 -0
  37. package/dist/upgrade-steps.d.ts +6 -1
  38. package/dist/upgrade-svelte.d.ts +15 -0
  39. package/dist/upgrade-svelte.spec.d.ts +1 -0
  40. package/dist/upgrade.cjs +307 -42
  41. package/dist/upgrade.js +132 -13
  42. package/dist/use-cases/add-integration.d.ts +1 -1
  43. package/dist/use-cases/delete-react-module.d.ts +4 -4
  44. package/dist/use-cases/index.d.ts +1 -0
  45. package/dist/use-cases/move-react-module.d.ts +2 -2
  46. package/dist/use-cases/rest-endpoint-generator.d.ts +6 -4
  47. package/dist/use-cases/scaffold-svelte-modules.d.ts +27 -0
  48. package/package.json +2 -1
  49. package/skills/df-ps-implement/SKILL.md +3 -3
  50. package/skills/df-ps-plan-feature/SKILL.md +1 -1
  51. package/skills/df-ps-scaffold/SKILL.md +9 -8
  52. package/skills/df-ps-scaffold/references/agent-mode.md +1 -1
  53. package/skills/df-ps-scaffold/references/agent-operations.md +8 -4
  54. package/skills/df-ps-scaffold/references/generators.md +1 -1
  55. package/skills/df-ps-scaffold/references/work-plan.md +1 -1
  56. package/skills/df-ps-svelte/SKILL.md +54 -0
  57. package/skills/df-ps-svelte/references/generators.md +56 -0
  58. package/dist/115.js +0 -615
package/dist/115.js DELETED
@@ -1,615 +0,0 @@
1
- import node_path from "node:path";
2
- import node_fs from "node:fs";
3
- import { addImport, addWireDependencies, addConstructorParameters, UnknownFormatNaming, ConfigFile, Folder, relativeImport, File, ProjectRoot, addClassMember, stripJsonComments } from "./201.js";
4
- const inMemoryImplementationType = 'in-memory';
5
- const className = 'InMemoryDbInfrastructureService';
6
- const wireName = 'wireInMemoryDbInfrastructureService';
7
- const parameterName = 'inMemoryDbInfrastructureService';
8
- const legacyWithIdLookup = ` withId: (id: TId): T | null =>
9
- items().find(
10
- (x: T) => hasId(x) && idsAreEqual(x.id as TId, id)
11
- ) ?? null,
12
- `;
13
- const legacyHasId = `const hasId = (x: unknown): x is { id: unknown } =>
14
- typeof x === 'object' && x !== null && 'id' in x;
15
-
16
- `;
17
- const withIdLookup = ` withId: (id: TId): T | null =>
18
- globalThis.___SHARED_IN_MEMORY_DB___![key].find((entry) =>
19
- idsAreEqual(entry.id as TId, id)
20
- )?.item ?? null,
21
- `;
22
- const inMemoryDbService = `type Entry = {
23
- id: unknown;
24
- item: any;
25
- };
26
-
27
- declare global {
28
- var ___SHARED_IN_MEMORY_DB___: Record<string, Array<Entry>> | undefined;
29
- }
30
-
31
- type Section<T, TId> = {
32
- all: (predicate?: (x: T) => boolean) => T[];
33
- first: (predicate: (x: T) => boolean) => T | null;
34
- withId: (id: TId) => T | null;
35
- lastAddedItem: () => T | null;
36
- save: (payload: T extends { id: TId } ? T : [TId, T]) => void;
37
- deleteById: (id: TId) => void;
38
- delete: (predicate: (x: T) => boolean) => void;
39
- };
40
-
41
- type IdsAreEqual<TId> = (a: TId, b: TId) => boolean;
42
-
43
- const comparisonMethodNames = ['equals', 'same', 'isSame', 'isEqual'] as const;
44
-
45
- const defaultIdsAreEqual = (a: unknown, b: unknown): boolean => {
46
- if (typeof a !== 'object' || a === null) {
47
- return Object.is(a, b);
48
- }
49
-
50
- for (const methodName of comparisonMethodNames) {
51
- const method: unknown = (a as Record<string, unknown>)[methodName];
52
- if (typeof method === 'function') {
53
- return Boolean(method.call(a, b));
54
- }
55
- }
56
-
57
- return Object.is(a, b);
58
- };
59
-
60
- export class InMemoryDbInfrastructureService {
61
- protected section<T extends { id: unknown }>(
62
- key: string,
63
- idsAreEqual?: IdsAreEqual<T['id']>
64
- ): Section<T, T['id']>;
65
- protected section<T, TId>(
66
- key: string,
67
- idsAreEqual?: IdsAreEqual<TId>
68
- ): Section<T, TId>;
69
- protected section<T, TId>(
70
- key: string,
71
- idsAreEqual: IdsAreEqual<TId> = defaultIdsAreEqual
72
- ): Section<T, TId> {
73
- if (!globalThis.___SHARED_IN_MEMORY_DB___) {
74
- globalThis.___SHARED_IN_MEMORY_DB___ = {};
75
- }
76
-
77
- if (!globalThis.___SHARED_IN_MEMORY_DB___[key]) {
78
- globalThis.___SHARED_IN_MEMORY_DB___[key] = [];
79
- }
80
-
81
- const items = (): T[] =>
82
- globalThis.___SHARED_IN_MEMORY_DB___![key].map(
83
- (entry) => entry.item
84
- );
85
-
86
- return {
87
- all: (predicate: (x: T) => boolean = () => true): T[] =>
88
- items().filter(predicate),
89
- first: (predicate: (x: T) => boolean): T | null =>
90
- items().find(predicate) ?? null,
91
- ${withIdLookup} lastAddedItem: (): T | null =>
92
- globalThis.___SHARED_IN_MEMORY_DB___![key].at(-1)?.item ?? null,
93
- save: (payload: T extends { id: TId } ? T : [TId, T]) => {
94
- const id = Array.isArray(payload) ? payload[0] : payload.id;
95
- const item = Array.isArray(payload) ? payload[1] : payload;
96
- const entries = globalThis.___SHARED_IN_MEMORY_DB___![key];
97
- const existing = entries.find((entry) =>
98
- idsAreEqual(entry.id as TId, id)
99
- );
100
- if (existing) {
101
- existing.item = item;
102
- return;
103
- }
104
- entries.push({ id, item });
105
- },
106
- deleteById: (id: TId) => {
107
- globalThis.___SHARED_IN_MEMORY_DB___![key] =
108
- globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
109
- (entry) => !idsAreEqual(entry.id as TId, id)
110
- );
111
- },
112
- delete: (predicate: (x: T) => boolean) => {
113
- globalThis.___SHARED_IN_MEMORY_DB___![key] =
114
- globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
115
- (entry) => !predicate(entry.item)
116
- );
117
- }
118
- };
119
- }
120
- }
121
- `;
122
- const inMemoryDbWiring = `import { wireClass } from '@domain-first/wire';
123
- import { InMemoryDbInfrastructureService } from '../../infrastructure/services/in-memory-db-infrastructure-service';
124
-
125
- export const wireInMemoryDbInfrastructureService = wireClass(
126
- InMemoryDbInfrastructureService,
127
- []
128
- );
129
- `;
130
- const withWiring = ()=>ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
131
- const sharedFolder = ()=>new Folder(new ProjectRoot().path).subitem([
132
- ConfigFile.Instance.data.project.rootFolder,
133
- 'shared-kernel'
134
- ]);
135
- const serviceFile = ()=>new File(sharedFolder().path).subitem([
136
- 'infrastructure',
137
- 'services',
138
- 'in-memory-db-infrastructure-service.ts'
139
- ]);
140
- const wireFile = ()=>new File(sharedFolder().path).subitem([
141
- 'wiring',
142
- 'infrastructure-services',
143
- 'wire-in-memory-db-infrastructure-service.ts'
144
- ]);
145
- const scaffoldInMemoryDb = (shared)=>{
146
- const servicesFolder = shared.subitem([
147
- 'infrastructure',
148
- 'services'
149
- ]);
150
- servicesFolder.createFile('in-memory-db-infrastructure-service.ts', inMemoryDbService);
151
- if (withWiring()) shared.subitem([
152
- 'wiring',
153
- 'infrastructure-services'
154
- ]).createFile('wire-in-memory-db-infrastructure-service.ts', inMemoryDbWiring);
155
- };
156
- const inMemoryDbScaffolded = ()=>serviceFile().exists && (!withWiring() || wireFile().exists);
157
- const usesInMemoryDb = (implementationType)=>Boolean(ConfigFile.Instance.data.backend?.withInMemoryDb) && new UnknownFormatNaming(implementationType).fileName === inMemoryImplementationType && inMemoryDbScaffolded();
158
- const uncountableEndings = [
159
- 'data',
160
- 'info',
161
- 'usage',
162
- 'feedback',
163
- 'media',
164
- 'ware',
165
- 'equipment',
166
- 'information',
167
- 'knowledge',
168
- 'traffic',
169
- 'telemetry',
170
- 'analytics',
171
- 'series'
172
- ];
173
- const uncountable = new RegExp(`(${uncountableEndings.join('|')})$`, 'i');
174
- const plural = (word)=>{
175
- if (uncountable.test(word)) return word;
176
- if (/[^aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`;
177
- if (/(^|[^aeiou]|qu)[aeiou]z$/i.test(word)) return `${word}zes`;
178
- if (/(s|x|z|ch|sh)$/i.test(word)) return `${word}es`;
179
- return `${word}s`;
180
- };
181
- const addInMemoryDbSection = (typeNaming, typeImportTarget)=>{
182
- const file = serviceFile();
183
- const sectionNaming = new UnknownFormatNaming(plural(typeNaming.fileName));
184
- const field = sectionNaming.variableName;
185
- if (new RegExp(`\\b${field}\\s*=\\s*this\\.section\\b`).test(file.data)) return field;
186
- const withImport = addImport(file.data, `import type { ${typeNaming.ClassName} } from '${relativeImport(file.path, typeImportTarget)}';`);
187
- file.update(addClassMember(withImport, className, `${field} = this.section<${typeNaming.ClassName}>('${sectionNaming.fileName.toUpperCase()}');`));
188
- return field;
189
- };
190
- const inMemoryDbTypeImport = (fromFile)=>`import type { ${className} } from '${relativeImport(fromFile, serviceFile().path)}'`;
191
- const inMemoryDbSectionMembers = (field, derived)=>`
192
- private readonly data: ${className}['${field}']
193
-
194
- constructor(${parameterName}: ${className}) {
195
- ${derived ? 'super()\n ' : ''}this.data = ${parameterName}.${field}
196
- }
197
- `.trim();
198
- const keepInMemoryDbSection = (classFile, field)=>{
199
- classFile.update(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)).replace('constructor() {}', inMemoryDbSectionMembers(field, false)));
200
- };
201
- const isInMemoryDb = (module)=>module.wireName === wireName;
202
- const injectInMemoryDb = (classFile, implementationName)=>{
203
- classFile.update(addConstructorParameters(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)), implementationName, [
204
- `private readonly ${parameterName}: ${className}`
205
- ]));
206
- };
207
- const wireInMemoryDb = (consumerWireFile, implementationName)=>{
208
- consumerWireFile.update(addWireDependencies(addImport(consumerWireFile.data, `import { ${wireName} } from '${relativeImport(consumerWireFile.path, wireFile().path)}'`), implementationName, [
209
- wireName
210
- ]));
211
- };
212
- const hasDependency = (name)=>{
213
- const manifestFile = new File(node_path.join(new ProjectRoot().path, 'package.json'));
214
- if (!manifestFile.exists) return false;
215
- const manifest = JSON.parse(manifestFile.data);
216
- return [
217
- manifest.dependencies,
218
- manifest.devDependencies,
219
- manifest.optionalDependencies
220
- ].some((dependencies)=>dependencies && Object.hasOwn(dependencies, name));
221
- };
222
- const missingPackages = (packages)=>{
223
- const missing = [
224
- ...new Set(packages)
225
- ].filter((name)=>!hasDependency(name));
226
- return missing.length ? [
227
- `npm i ${missing.join(' ')}`
228
- ] : [];
229
- };
230
- const missingDomainFirstPackages = ()=>missingPackages(ConfigFile.backend.domainFirstPackages);
231
- const openapiExtractorPath = "scripts/extract-open-api-data-from-endpoint.ts";
232
- const rootFolderSegments = (rootFolder, indent = 20)=>rootFolder.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment && '.' !== segment).map((segment)=>`'${segment}',\n${' '.repeat(indent)}`).join('');
233
- const legacyEndpointFileLookup = (rootFolder)=>` // The controller, if any, is the first folder of the path:
234
- // context-root endpoints live right in presentation/rest.
235
- const [currentBoundedContext, ...relativePath] = routeMetadata.path;
236
-
237
- if (!currentBoundedContext) {
238
- return undefined;
239
- }
240
-
241
- const endpointFile = project.getSourceFile(
242
- path.join(
243
- ${rootFolderSegments(rootFolder)}'bounded-contexts',
244
- currentBoundedContext,
245
- 'presentation',
246
- 'rest',
247
- ...relativePath.map(pathParameterAsName),
248
- \`\${routeMetadata.method.toUpperCase()}.ts\`
249
- )
250
- );
251
- `;
252
- const rootEndpointFileLookup = (rootFolder)=>` const [currentBoundedContext, ...relativePath] = routeMetadata.path;
253
-
254
- if (!currentBoundedContext) {
255
- return undefined;
256
- }
257
-
258
- // A controller is the first folder of the path; other routes
259
- // belong to the context root in presentation/rest/(root).
260
- const restFolder = path.join(
261
- ${rootFolderSegments(rootFolder, 16)}'bounded-contexts',
262
- currentBoundedContext,
263
- 'presentation',
264
- 'rest'
265
- );
266
- const endpointPath = [
267
- ...relativePath.map(pathParameterAsName),
268
- \`\${routeMetadata.method.toUpperCase()}.ts\`
269
- ];
270
- const endpointFile =
271
- project.getSourceFile(path.join(restFolder, ...endpointPath)) ??
272
- project.getSourceFile(
273
- path.join(restFolder, '(root)', ...endpointPath)
274
- );
275
- `;
276
- const endpointFileLookup = (rootFolder)=>` // A context is the start of the route, nested ones included
277
- // (/sales/orders/...). A controller is the next folder; other
278
- // routes belong to the context root in presentation/rest/(root).
279
- const contextsFolder = path.join(
280
- ${rootFolderSegments(rootFolder, 16)}'bounded-contexts'
281
- );
282
- const endpointFile = Array.from(
283
- { length: routeMetadata.path.length },
284
- (_, index) => index + 1
285
- )
286
- .flatMap((contextLength) => {
287
- const restFolder = path.join(
288
- contextsFolder,
289
- ...routeMetadata.path.slice(0, contextLength),
290
- 'presentation',
291
- 'rest'
292
- );
293
- const endpointPath = [
294
- ...routeMetadata.path
295
- .slice(contextLength)
296
- .map(pathParameterAsName),
297
- \`\${routeMetadata.method.toUpperCase()}.ts\`
298
- ];
299
- return [
300
- path.join(restFolder, ...endpointPath),
301
- path.join(restFolder, '(root)', ...endpointPath)
302
- ];
303
- })
304
- .map((file) => project.getSourceFile(file))
305
- .find((file) => !!file);
306
- `;
307
- const openapiExtractor = (rootFolder)=>`import path from 'node:path';
308
- import {
309
- type DocNode,
310
- DocPlainText,
311
- TSDocConfiguration,
312
- TSDocParser,
313
- TSDocTagDefinition,
314
- TSDocTagSyntaxKind
315
- } from '@microsoft/tsdoc';
316
- import { Node, Project, type SourceFile, SyntaxKind } from 'ts-morph';
317
-
318
- type BlockTag = \`@\${string}\`;
319
-
320
- type OpenApiDataTags = {
321
- /** Omit to take the summary from the comment text before the first tag. */
322
- summary?: BlockTag;
323
- description?: BlockTag;
324
- };
325
-
326
- type OpenApiData = Partial<{
327
- summary: string;
328
- description: string;
329
- operationId: string;
330
- }>;
331
-
332
- const project = new Project({
333
- tsConfigFilePath: 'tsconfig.json'
334
- });
335
-
336
- const getText = (node: DocNode): string =>
337
- node
338
- .getChildNodes()
339
- .map((child) => {
340
- if (child instanceof DocPlainText) {
341
- return child.text;
342
- }
343
-
344
- return getText(child);
345
- })
346
- .join('');
347
-
348
- const getRawCommentText = (comment: string): string =>
349
- comment
350
- .replace(/^\\/\\*\\*/, '')
351
- .replace(/\\*\\/$/, '')
352
- .split(/\\r?\\n/)
353
- .map((line) => line.replace(/^\\s*\\*\\s?/, ''))
354
- .join('\\n');
355
-
356
- // TSDoc treats an unknown tag as summary content, so every block tag of the
357
- // comment has to be registered for the summary section to end before it.
358
- const parseSummary = (comment: string): string | undefined => {
359
- const configuration = new TSDocConfiguration();
360
- const tagNames = getRawCommentText(comment).matchAll(/(?:^|\\n)\\s*(@\\w+)/g);
361
-
362
- for (const [, tagName] of tagNames) {
363
- if (!configuration.tryGetTagDefinition(tagName)) {
364
- configuration.addTagDefinition(
365
- new TSDocTagDefinition({
366
- tagName,
367
- syntaxKind: TSDocTagSyntaxKind.BlockTag
368
- })
369
- );
370
- }
371
- }
372
-
373
- const { docComment } = new TSDocParser(configuration).parseString(comment);
374
-
375
- return getText(docComment.summarySection).trim() || undefined;
376
- };
377
-
378
- // Parsed by hand rather than through TSDoc, which drops the line breaks.
379
- const getTagText = (comment: string, tag: BlockTag): string | undefined => {
380
- const tagMatch = getRawCommentText(comment).match(
381
- new RegExp(
382
- \`(?:^|\\\\n)\\\\s*\${tag}(?:[ \\\\t]*\\\\n|[ \\\\t]+)([\\\\s\\\\S]*?)(?=\\\\n\\\\s*@\\\\w+|\\\\s*$)\`
383
- )
384
- );
385
-
386
- return tagMatch?.[1].trim() || undefined;
387
- };
388
-
389
- // Endpoints pass their logic as the generator's first argument
390
- // (\`this.endpointGenerator(this.handler.handle, ...)\`), while other injected
391
- // queries only serve as helpers, e.g. guest checks.
392
- const findHandlerClass = (endpointFile: SourceFile) =>
393
- endpointFile
394
- .getDescendantsOfKind(SyntaxKind.CallExpression)
395
- .map((call) => call.getArguments()[0])
396
- .filter(Node.isPropertyAccessExpression)
397
- .find((argument) => argument.getName() === 'handle')
398
- ?.getExpression()
399
- .getType()
400
- .getSymbol()
401
- ?.getDeclarations()
402
- .find(Node.isClassDeclaration);
403
-
404
- // Path parameters (\`:id\`) can't be part of file and folder names
405
- // everywhere (Windows), so endpoints name them \`_id_\` there.
406
- const pathParameterAsName = (segment: string) =>
407
- segment.startsWith(':') ? \`_\${segment.slice(1)}_\` : segment;
408
-
409
- export const createOpenApiDataFromEndpointLogicExtractor = ({
410
- summary: summaryTag,
411
- description: descriptionTag = '@description'
412
- }: OpenApiDataTags = {}) => {
413
- return (routeMetadata: {
414
- method: string;
415
- path: readonly string[];
416
- }): OpenApiData | undefined => {
417
- try {
418
- ${endpointFileLookup(rootFolder)}
419
- if (!endpointFile) {
420
- return undefined;
421
- }
422
-
423
- const declaration = findHandlerClass(endpointFile);
424
- const operationId = declaration?.getName();
425
- const comment = declaration?.getJsDocs().at(-1)?.getText();
426
-
427
- if (!comment) {
428
- return { operationId };
429
- }
430
-
431
- return {
432
- summary: summaryTag
433
- ? getTagText(comment, summaryTag)
434
- : parseSummary(comment),
435
- description: getTagText(comment, descriptionTag),
436
- operationId
437
- };
438
- } catch (e: unknown) {
439
- console.error(e);
440
- return undefined;
441
- }
442
- };
443
- };
444
- `;
445
- const ignoredFolders = new Set([
446
- 'node_modules',
447
- '.git',
448
- '.next',
449
- 'dist',
450
- 'build',
451
- 'out',
452
- 'coverage',
453
- 'storybook-static'
454
- ]);
455
- const codeExtension = /\.(?:tsx?|mts|cts|jsx?|mjs|cjs|mdx)$/;
456
- const escapeRegExp = (value)=>value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
457
- const walk = (folder)=>{
458
- if (!node_fs.existsSync(folder)) return [];
459
- return node_fs.readdirSync(folder, {
460
- withFileTypes: true
461
- }).flatMap((entry)=>{
462
- const entryPath = node_path.join(folder, entry.name);
463
- if (entry.isDirectory()) return ignoredFolders.has(entry.name) ? [] : walk(entryPath);
464
- return entry.isFile() ? [
465
- entryPath
466
- ] : [];
467
- });
468
- };
469
- const toPosix = (value)=>value.split(node_path.sep).join('/');
470
- const readAliases = (projectRoot)=>{
471
- const tsconfig = node_path.join(projectRoot, 'tsconfig.json');
472
- if (!node_fs.existsSync(tsconfig)) return [];
473
- try {
474
- const { compilerOptions = {} } = JSON.parse(stripJsonComments(node_fs.readFileSync(tsconfig, 'utf8')));
475
- const base = node_path.resolve(projectRoot, compilerOptions.baseUrl ?? '.');
476
- return Object.entries(compilerOptions.paths ?? {}).filter(([pattern, targets])=>pattern.endsWith('*') && targets[0]?.endsWith('*')).map(([pattern, [target]])=>({
477
- prefix: pattern.slice(0, -1),
478
- target: node_path.resolve(base, target.slice(0, -1))
479
- }));
480
- } catch {
481
- return [];
482
- }
483
- };
484
- const specifierPattern = /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*|\bmock\s*\(\s*)(['"])([^'"\n]+)\2/g;
485
- const reExportPattern = /\bexport\s+(?:type\s+)?(?:\*(?:\s+as\s+[\w$]+)?|\{[^}]*\})\s*from\s*(['"])([^'"\n]+)\1/g;
486
- const importPaths = (file)=>{
487
- const withoutExtension = file.replace(codeExtension, '');
488
- return 'index' === node_path.basename(withoutExtension) ? [
489
- withoutExtension,
490
- node_path.dirname(withoutExtension)
491
- ] : [
492
- withoutExtension
493
- ];
494
- };
495
- const projectImports = (projectRoot)=>{
496
- const aliases = readAliases(projectRoot);
497
- const resolve = (specifier, fromFile)=>{
498
- if (specifier.startsWith('.')) return {
499
- resolved: node_path.resolve(node_path.dirname(fromFile), specifier),
500
- alias: void 0
501
- };
502
- const alias = aliases.find(({ prefix })=>specifier.startsWith(prefix));
503
- return alias ? {
504
- resolved: node_path.resolve(alias.target, specifier.slice(alias.prefix.length)),
505
- alias
506
- } : void 0;
507
- };
508
- const specifierFor = (fromFile, toPath, alias)=>{
509
- const aliased = alias && toPosix(node_path.relative(alias.target, toPath));
510
- if (aliased && !aliased.startsWith('..')) return `${alias.prefix}${aliased}`;
511
- const relative = toPosix(node_path.relative(node_path.dirname(fromFile), toPath));
512
- return relative.startsWith('.') ? relative : `./${relative}`;
513
- };
514
- const codeFiles = new Map(walk(projectRoot).filter((file)=>codeExtension.test(file)).map((file)=>[
515
- file,
516
- node_fs.readFileSync(file, 'utf8')
517
- ]));
518
- const importsOf = (file)=>[
519
- ...(codeFiles.get(file) ?? '').matchAll(specifierPattern)
520
- ].map(([, , , specifier])=>resolve(specifier, file)?.resolved).filter((resolved)=>!!resolved);
521
- return {
522
- resolve,
523
- specifierFor,
524
- codeFiles,
525
- importsOf
526
- };
527
- };
528
- const stageModuleMove = ({ projectRoot, stopAt, moves, movedPath, rename, everyFile = (content)=>content, stopAtFor })=>{
529
- const stopFor = (file)=>stopAtFor?.(file) ?? stopAt;
530
- const { resolve, specifierFor, codeFiles } = projectImports(projectRoot);
531
- const barrels = new Set();
532
- const isBarrel = (resolved)=>barrels.has(resolved.replace(codeExtension, ''));
533
- for(let found = true; found;){
534
- found = false;
535
- for (const [file, content] of codeFiles){
536
- if (moves.has(file) || isBarrel(file)) continue;
537
- const reExportsModule = [
538
- ...content.matchAll(reExportPattern)
539
- ].some(([, , specifier])=>{
540
- const resolution = resolve(specifier, file);
541
- return !!resolution && (!!movedPath(resolution.resolved) || isBarrel(resolution.resolved));
542
- });
543
- if (reExportsModule) {
544
- for (const importPath of importPaths(file))barrels.add(importPath);
545
- found = true;
546
- }
547
- }
548
- }
549
- const rewrite = (content, oldFile, newFile)=>{
550
- let referencesModule = false;
551
- const rewritten = content.replace(specifierPattern, (match, keyword, quote, specifier)=>{
552
- const resolution = resolve(specifier, oldFile);
553
- if (!resolution) return match;
554
- const moved = movedPath(resolution.resolved);
555
- if (moved || isBarrel(resolution.resolved)) referencesModule = true;
556
- if (!moved && oldFile === newFile) return match;
557
- const next = specifierFor(newFile, moved ?? resolution.resolved, resolution.alias);
558
- return `${keyword}${quote}${next}${quote}`;
559
- });
560
- const changed = everyFile(rewritten);
561
- if (!referencesModule && !moves.has(oldFile)) return changed;
562
- return rename(changed, {
563
- moved: moves.has(oldFile)
564
- });
565
- };
566
- for (const [file, newFile] of moves)if (!codeFiles.has(file) && newFile !== file) new File(file).moveTo(newFile, stopFor(file));
567
- const updated = [];
568
- for (const [file, content] of codeFiles){
569
- const newFile = moves.get(file);
570
- const next = rewrite(content, file, newFile ?? file);
571
- if (newFile && newFile !== file) {
572
- new File(newFile).data = next;
573
- new File(file).delete(stopFor(file));
574
- } else if (next !== content) {
575
- new File(file).update(next);
576
- if (!newFile) updated.push(file);
577
- }
578
- }
579
- return {
580
- moves: [
581
- ...moves
582
- ].filter(([from, to])=>from !== to),
583
- updated
584
- };
585
- };
586
- const rootControllerFolder = '(root)';
587
- const pathParameterAsName = (segment)=>segment.startsWith(':') ? `_${segment.slice(1)}_` : segment;
588
- const isPathParameterName = (name)=>name.startsWith(':') || /^_.+_$/.test(name);
589
- const endpointFileNames = new Set([
590
- 'get',
591
- 'post',
592
- 'put',
593
- 'patch',
594
- 'delete'
595
- ].map((method)=>`${method.toUpperCase()}.ts`));
596
- const entries = (folder)=>node_fs.existsSync(folder) ? node_fs.readdirSync(folder, {
597
- withFileTypes: true
598
- }) : [];
599
- const subfolders = (folder)=>entries(folder).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name);
600
- const restFolders = (boundedContextFolder)=>({
601
- presentation: node_path.join(boundedContextFolder, 'presentation', 'rest'),
602
- wiring: node_path.join(boundedContextFolder, 'wiring', 'presentation', 'rest')
603
- });
604
- const restControllers = (boundedContextFolder)=>subfolders(restFolders(boundedContextFolder).presentation).filter((name)=>name !== rootControllerFolder && !isPathParameterName(name));
605
- const rootStaticSegments = (boundedContextFolder)=>subfolders(node_path.join(restFolders(boundedContextFolder).presentation, rootControllerFolder)).filter((name)=>!isPathParameterName(name));
606
- const legacyRootEndpoints = (boundedContextFolder)=>{
607
- const { presentation, wiring } = restFolders(boundedContextFolder);
608
- return {
609
- endpointFiles: entries(presentation).filter((entry)=>entry.isFile() && endpointFileNames.has(entry.name)).map((entry)=>node_path.join(presentation, entry.name)),
610
- parameterFolders: subfolders(presentation).filter(isPathParameterName).map((name)=>node_path.join(presentation, name)),
611
- wireFiles: entries(wiring).filter((entry)=>entry.isFile() && 'index.ts' !== entry.name && /\.ts$/.test(entry.name)).map((entry)=>node_path.join(wiring, entry.name))
612
- };
613
- };
614
- const hasLegacyRootEndpoints = (boundedContextFolder)=>Object.values(legacyRootEndpoints(boundedContextFolder)).some((paths)=>paths.length > 0);
615
- export { addInMemoryDbSection, codeExtension, endpointFileLookup, escapeRegExp, hasDependency, hasLegacyRootEndpoints, inMemoryDbScaffolded, inMemoryDbSectionMembers, inMemoryDbTypeImport, inMemoryImplementationType, injectInMemoryDb, isInMemoryDb, isPathParameterName, keepInMemoryDbSection, legacyEndpointFileLookup, legacyHasId, legacyRootEndpoints, legacyWithIdLookup, missingDomainFirstPackages, missingPackages, openapiExtractor, openapiExtractorPath, pathParameterAsName, plural, projectImports, restControllers, restFolders, rootEndpointFileLookup, rootStaticSegments, scaffoldInMemoryDb, stageModuleMove, toPosix, usesInMemoryDb, walk, wireInMemoryDb, withIdLookup };