@domain-first/project-structure 2.14.2 → 2.15.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/README.md CHANGED
@@ -46,13 +46,13 @@ npm exec --package=@domain-first/project-structure -- df-ps
46
46
 
47
47
  On the first run, the CLI asks for:
48
48
 
49
- | Setting | What to enter |
50
- | ---------------------------------- | ----------------------------------------------------------------------------------------------------------- |
51
- | Root folder | The source directory, such as `src` or `src/server`. Default: `src`. |
52
- | `@domain-first` packages | The integrations to use in generated templates. |
53
- | Default persistence implementation | A label such as `prisma`, used as the suggested implementation for execution commands and queries. |
54
- | React | Whether to show the React module menu. |
55
- | Unit tests | Whether to generate tests, and which module to import test helpers from. Suggested module: `vitest`. |
49
+ | Setting | What to enter |
50
+ | ---------------------------------- | ---------------------------------------------------------------------------------------------------- |
51
+ | Root folder | The source directory, such as `src` or `src/server`. Default: `src`. |
52
+ | `@domain-first` packages | The integrations to use in generated templates. |
53
+ | Default persistence implementation | A label such as `prisma`, used as the suggested implementation for execution commands and queries. |
54
+ | React | Whether to show the React module menu. |
55
+ | Unit tests | Whether to generate tests, and which module to import test helpers from. Suggested module: `vitest`. |
56
56
 
57
57
  Setup writes `domain-first.project-structure.config.json` beside your `package.json` and creates shared helpers for the selected `wire` and `errors` integrations. That first run then exits.
58
58
 
@@ -128,19 +128,19 @@ This is an example of the accumulated output; creating a context alone creates i
128
128
 
129
129
  Choose a bounded context, then a layer:
130
130
 
131
- | Layer / menu option | Generated output |
132
- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
133
- | Domain → New Aggregate | Aggregate root and barrel export; optional repository contract, primary and test implementations, tests, and repository wiring. |
131
+ | Layer / menu option | Generated output |
132
+ | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
133
+ | Domain → New Aggregate | Aggregate root and barrel export; optional repository contract, primary and test implementations, tests, and repository wiring. |
134
134
  | Domain → New Entity / New Value Object | Entity or value object class with tests, in the `entities/` or `value-objects/` folder of a chosen aggregate (exported from its barrel) or of the context's `domain/`. Also in the Shared Layer, under `shared/domain/`. |
135
- | Domain → Errors | Errors in the context namespace, nested namespaces, and exports. Uses `@domain-first/errors`. |
136
- | Domain → New Service | Domain service class, with optional tests and wiring. |
137
- | Application → New Use Case | Use case class; handler schemas and `handle` when enabled; optional tests and wiring. |
138
- | Application → New Command / New Query | Execution or orchestration templates, with optional tests and wiring. |
139
- | Application → New Port | Abstract port and an adapter implementation, with an optional test adapter, tests, and wiring. |
140
- | Application → New Service | Application service class, with optional tests and wiring. |
141
- | Infrastructure → New Service | Infrastructure service class, with optional tests and wiring. |
142
- | Presentation → New Service | Presentation service class, with optional tests and wiring. |
143
- | Presentation → New Handlers-REST Endpoint | Endpoint class for a controller, method, and relative path; wiring and handler exports when enabled. Requires `@domain-first/handlers-rest` to appear in the menu. |
135
+ | Domain → Errors | Errors in the context namespace, nested namespaces, and exports. Uses `@domain-first/errors`. |
136
+ | Domain → New Service | Domain service class, with optional tests and wiring. |
137
+ | Application → New Use Case | Use case class; handler schemas and `handle` when enabled; optional tests and wiring. |
138
+ | Application → New Command / New Query | Execution or orchestration templates, with optional tests and wiring. |
139
+ | Application → New Port | Abstract port and an adapter implementation, with an optional test adapter, tests, and wiring. |
140
+ | Application → New Service | Application service class, with optional tests and wiring. |
141
+ | Infrastructure → New Service | Infrastructure service class, with optional tests and wiring. |
142
+ | Presentation → New Service | Presentation service class, with optional tests and wiring. |
143
+ | Presentation → New Handlers-REST Endpoint | Endpoint class for a controller, method, and relative path; wiring and handler exports when enabled. Requires `@domain-first/handlers-rest` to appear in the menu. |
144
144
 
145
145
  ### Commands and queries
146
146
 
@@ -165,12 +165,12 @@ Implementation names such as `prisma`, `api`, `in-memory`, and `mock` determine
165
165
 
166
166
  The list depends on the layer of the class being built:
167
167
 
168
- | Layer | Can depend on |
169
- | -------------- | -------------------------------------------- |
170
- | Domain | Domain |
171
- | Application | Domain, application |
172
- | Infrastructure | Domain, infrastructure |
173
- | Presentation | Application, presentation |
168
+ | Layer | Can depend on |
169
+ | -------------- | ------------------------- |
170
+ | Domain | Domain |
171
+ | Application | Domain, application |
172
+ | Infrastructure | Domain, infrastructure |
173
+ | Presentation | Application, presentation |
174
174
 
175
175
  Some kinds of modules have narrower rules. From the application layer, application services can use only ports. Use cases can't use other use cases, and repository implementations can't use other repositories. Execution commands and queries can't use other commands or queries. From the application layer, orchestration commands and queries can use only execution commands and queries. Repository, execution command, execution query, and port implementations belong to infrastructure: they implement application modules but can't take them as dependencies. REST endpoints are not offered as dependencies. Their dependencies are chosen when they are generated (see REST endpoints) and are not available in **Wire dependency**.
176
176
 
@@ -192,14 +192,14 @@ With wiring enabled, the generator also adds endpoint factories and exports coll
192
192
 
193
193
  Enable `useReact` and choose **Scaffold React module** from the main menu. Modules are created under `<rootFolder>/presentation/react`.
194
194
 
195
- | Generator | Output |
196
- | ------------------------------ | ---------------------------------------------------------------------------------------------------------- |
197
- | New page | `pages/<name>-page.tsx` with a typed props object and a component. |
198
- | New widget → monolithic | `widgets/<name>/<name>-widget.tsx` with props and rendering in one file, re-exported from `index.ts`. |
195
+ | Generator | Output |
196
+ | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
197
+ | New page | `pages/<name>-page.tsx` with a typed props object and a component. |
198
+ | New widget → monolithic | `widgets/<name>/<name>-widget.tsx` with props and rendering in one file, re-exported from `index.ts`. |
199
199
  | New widget → with separated ui | `<name>-widget.tsx`, `types.ts`, `ui/<name>-widget-ui.tsx`, `hooks/use-<name>-ui-model.ts`, and `index.ts`; with `storybookFramework`, also `ui/<name>-widget-ui.stories.tsx`. |
200
- | New widget → headless | `<name>-widget.tsx`, types, a UI-model hook, and `index.ts`; the rendering component is supplied through the `UI` prop. |
201
- | New UI-kit component | `ui-kit/<name>/<name>.tsx` with a typed props object and a component, re-exported from `index.ts`; with `storybookFramework`, also `<name>.stories.tsx`. |
202
- | New shared hook | `hooks/use-<name>.ts` with an app-wide hook, such as `use-debounce`; a leading `use-` in the name is not repeated. |
200
+ | New widget → headless | `<name>-widget.tsx`, types, a UI-model hook, and `index.ts`; the rendering component is supplied through the `UI` prop. |
201
+ | New UI-kit component | `ui-kit/<name>/<name>.tsx` with a typed props object and a component, re-exported from `index.ts`; with `storybookFramework`, also `<name>.stories.tsx`. |
202
+ | New shared hook | `hooks/use-<name>.ts` with an app-wide hook, such as `use-debounce`; a leading `use-` in the name is not repeated. |
203
203
 
204
204
  Page and widget names can include folders split by `/`. For example, a page named `admin/panel/users` is created at `pages/admin/panel/admin-panel-users-page.tsx` as `AdminPanelUsersPage`, and a widget with the same name at `widgets/admin/panel/users/admin-panel-users-widget.tsx` as `AdminPanelUsersWidget` with the story title `Widgets/Admin/Panel/Users`. The widget folder uses only the last segment; file names and code names use the whole path.
205
205
 
@@ -218,8 +218,8 @@ It adds these package scripts, with paths adjusted to your `rootFolder`:
218
218
 
219
219
  ```json
220
220
  {
221
- "storybook": "storybook dev -p 6006 -c \"src/presentation/react/.storybook\"",
222
- "build-storybook": "storybook build -c \"src/presentation/react/.storybook\" -o \"src/presentation/react/storybook-static\""
221
+ "storybook": "storybook dev -p 6006 -c \"src/presentation/react/.storybook\"",
222
+ "build-storybook": "storybook build -c \"src/presentation/react/.storybook\" -o \"src/presentation/react/storybook-static\""
223
223
  }
224
224
  ```
225
225
 
@@ -298,8 +298,8 @@ adds `/coverage/` to the project `.gitignore` and these package scripts:
298
298
 
299
299
  ```json
300
300
  {
301
- "test": "vitest run --reporter=dot --silent=passed-only",
302
- "test:coverage": "vitest run --coverage --reporter=dot --silent=passed-only"
301
+ "test": "vitest run --reporter=dot --silent=passed-only",
302
+ "test:coverage": "vitest run --coverage --reporter=dot --silent=passed-only"
303
303
  }
304
304
  ```
305
305
 
@@ -329,6 +329,68 @@ After writing, the CLI prints `npm install --save-dev @playwright/test` if the
329
329
  package is missing and `npx playwright install --with-deps` for the browsers and
330
330
  their system dependencies. Then run `npm run test:e2e`.
331
331
 
332
+ ### OpenAPI
333
+
334
+ Choose **Add integration → OpenAPI**. The item is listed only when
335
+ `domainFirstPackages` includes `@domain-first/handlers-rest`. The integration asks for the route prefix
336
+ your HTTP server serves `restHandlers` under (`/api` by default) and for the
337
+ document path (`public/openapi.json` when `next` is declared, otherwise
338
+ `openapi.json`). It creates `scripts/generate-openapi.ts` in the project root,
339
+ which passes `restHandlers` from `<rootFolder>/presentation/rest` to
340
+ `generateOpenAPI` from `@domain-first/handlers-rest`. The document title comes from the package name. It adds this package script:
341
+
342
+ ```json
343
+ {
344
+ "openapi": "tsx --env-file-if-exists=.env scripts/generate-openapi.ts"
345
+ }
346
+ ```
347
+
348
+ `.env` is loaded because wiring imported through `restHandlers` may read the
349
+ environment. Script conflicts and overwrite confirmation work as in the other
350
+ integrations. After writing, the CLI prints `npm install --save-dev tsx` when
351
+ `tsx` is missing. The script needs `@domain-first/handlers-rest` 7.0.2+, where
352
+ OpenAPI paths start with `/` without a leading empty prefix segment; when the
353
+ package is missing or older (the installed version is checked first, then the
354
+ declared range), the CLI prints `npm install @domain-first/handlers-rest@^7.0.2`. `restHandlers`
355
+ are created with the first REST endpoint generated with `@domain-first/wire`;
356
+ until then, the CLI reminds you about it. Run `npm run openapi` after adding or
357
+ changing endpoints, then regenerate your API client, if you have one.
358
+
359
+ ### Orval (React Query client)
360
+
361
+ Choose **Add integration → Orval (React Query client)**. The item is listed only
362
+ when `domainFirstPackages` includes `@domain-first/handlers-rest` and `useReact`
363
+ is enabled. The integration asks for the OpenAPI document path; the default is
364
+ read from `scripts/generate-openapi.ts` created by the OpenAPI integration. It
365
+ creates:
366
+
367
+ - `<rootFolder>/presentation/react/data-layer/orval.config.ts`: TanStack Query
368
+ v5 hooks on `fetch`, split by tags into `data-layer/orval`, with schemas in
369
+ its `model` folder. Orval resolves paths relative to the config, so they
370
+ point to the OpenAPI document and the data layer from there. When `next` is
371
+ declared, request URLs start with `NEXT_PUBLIC_API_BASE_URL`.
372
+ - `data-layer/api-client/mutator.ts`: `customInstance`, which every generated
373
+ request goes through. It calls `fetch` and throws `ApiError` with the status
374
+ and the parsed body on non-2xx responses; the hooks type that body per
375
+ endpoint. Add auth headers, token refresh and other shared request logic here.
376
+ - `data-layer/query-provider.tsx`: `QueryProvider` with one `QueryClient` per
377
+ browser session. Wrap your app in it.
378
+
379
+ The mutator and the provider are starting points and are never overwritten.
380
+
381
+ The generated `data-layer/orval/` folder is added to `.gitignore`, and this
382
+ package script is added, with the path adjusted to your `rootFolder`:
383
+
384
+ ```json
385
+ {
386
+ "client:orval": "orval --config \"src/presentation/react/data-layer/orval.config.ts\""
387
+ }
388
+ ```
389
+
390
+ After writing, the CLI prints `npm install @tanstack/react-query` and
391
+ `npm install --save-dev orval` for missing packages. Run `npm run openapi`, then
392
+ `npm run client:orval`, and import hooks and types from `data-layer/orval`.
393
+
332
394
  ## Configuration
333
395
 
334
396
  The project configuration is stored in `domain-first.project-structure.config.json`. Commit it to share generation settings with your team. For example:
@@ -350,14 +412,14 @@ The project configuration is stored in `domain-first.project-structure.config.js
350
412
  }
351
413
  ```
352
414
 
353
- | Field | Effect |
354
- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
355
- | `rootFolder` | Base path for generated source, relative to the project root. |
356
- | `domainFirstPackages` | Explicit list of integrations used by templates. An empty array selects basic class templates where supported. |
357
- | `defaultPersistenceLayerImplementation` | Suggested implementation label for execution commands and queries. |
358
- | `useReact` | Shows or hides the React module menu. |
415
+ | Field | Effect |
416
+ | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
417
+ | `rootFolder` | Base path for generated source, relative to the project root. |
418
+ | `domainFirstPackages` | Explicit list of integrations used by templates. An empty array selects basic class templates where supported. |
419
+ | `defaultPersistenceLayerImplementation` | Suggested implementation label for execution commands and queries. |
420
+ | `useReact` | Shows or hides the React module menu. |
359
421
  | `storybookFramework` | Storybook framework package imported by generated stories (`Meta`, `StoryObj`), e.g. `@storybook/react-vite`. Omit this field to skip stories for UI-kit components and widget UI. Asked during setup only when React is enabled. |
360
- | `testingLibrary` | Module imported by generated tests. Omit this field to disable test generation. Templates expect helpers such as `describe`, `test`, `expect`, and `beforeEach`. |
422
+ | `testingLibrary` | Module imported by generated tests. Omit this field to disable test generation. Templates expect helpers such as `describe`, `test`, `expect`, and `beforeEach`. |
361
423
 
362
424
  ### Package integrations
363
425
 
package/dist/index.cjs CHANGED
@@ -258,6 +258,84 @@ const addPackageScripts = async (file, additions)=>{
258
258
  return selected;
259
259
  };
260
260
  const describeScripts = (selected, descriptions)=>Object.entries(descriptions).filter(([name])=>selected[name]).map(([name, description])=>`npm run ${selected[name]} — ${description}`);
261
+ const openapiScriptPath = "scripts/generate-openapi.ts";
262
+ const defaultOpenapiPath = (withNext)=>withNext ? 'public/openapi.json' : 'openapi.json';
263
+ const openapiScripts = {
264
+ openapi: `tsx --env-file-if-exists=.env ${openapiScriptPath}`
265
+ };
266
+ const splitPath = (value)=>value.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
267
+ const apiTitle = (packageName)=>{
268
+ const words = String(packageName ?? '').replace(/^@[^/]*\//, '').split(/[^a-zA-Z0-9]+/).filter((word)=>!!word).map((word)=>word[0].toUpperCase() + word.slice(1));
269
+ return [
270
+ ...words,
271
+ 'API'
272
+ ].join(' ');
273
+ };
274
+ const openapiGenerator = (rootFolder, title, routePrefix, outputPath)=>{
275
+ const restFolder = external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/rest');
276
+ const restImport = external_node_path_default().posix.relative(external_node_path_default().posix.dirname(openapiScriptPath), restFolder);
277
+ const prefixSegments = splitPath(routePrefix);
278
+ const apiRoutePrefix = prefixSegments.length ? `\n apiRoutePrefix: [${prefixSegments.map((segment)=>`'${segment}'`).join(', ')}],` : '';
279
+ return `import { generateOpenAPI } from '@domain-first/handlers-rest';
280
+ import { restHandlers } from '${restImport.startsWith('.') ? restImport : `./${restImport}`}';
281
+
282
+ generateOpenAPI(restHandlers, {
283
+ document: { info: { title: '${title}', version: '1.0.0' } },${apiRoutePrefix}
284
+ outputFile: { path: '${outputPath}' }
285
+ });
286
+ `;
287
+ };
288
+ const minimalHandlersRest = [
289
+ 7,
290
+ 0,
291
+ 2
292
+ ];
293
+ const parseVersion = (value)=>String(value ?? '').match(/(\d+)\.(\d+)\.(\d+)/)?.slice(1).map(Number);
294
+ const handlersRestUpToDate = (root, declared)=>{
295
+ const installed = new File(external_node_path_default().join(root, 'node_modules/@domain-first/handlers-rest/package.json'));
296
+ const version = parseVersion(installed.exists ? JSON.parse(installed.data).version : declared);
297
+ if (!version) return false;
298
+ for (const [index, part] of minimalHandlersRest.entries())if (version[index] !== part) return version[index] > part;
299
+ return true;
300
+ };
301
+ const addOpenapi = async ()=>{
302
+ const { rootFolder } = ConfigFile.Instance.data;
303
+ const root = new ProjectRoot().path;
304
+ const manifestFile = new File(external_node_path_default().join(root, 'package.json'));
305
+ const manifest = JSON.parse(manifestFile.data);
306
+ const dependencies = {
307
+ ...manifest.dependencies,
308
+ ...manifest.devDependencies
309
+ };
310
+ const routePrefix = await (0, prompts_namespaceObject.input)({
311
+ message: 'Route prefix the REST handlers are served under:',
312
+ default: '/api'
313
+ });
314
+ const outputPath = await (0, prompts_namespaceObject.input)({
315
+ message: 'OpenAPI document path:',
316
+ default: defaultOpenapiPath(Boolean(dependencies.next)),
317
+ validate: (value)=>splitPath(value).length ? true : 'Path is required'
318
+ });
319
+ const selected = await addPackageScripts(manifestFile, openapiScripts);
320
+ const generatorFile = new File(external_node_path_default().join(root, openapiScriptPath));
321
+ const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'));
322
+ if (!generatorFile.exists || generatorFile.data !== content) generatorFile.data = content;
323
+ const hasRestHandlers = new File(external_node_path_default().join(root, rootFolder, 'presentation', 'rest', 'index.ts')).exists;
324
+ return [
325
+ ...handlersRestUpToDate(root, dependencies['@domain-first/handlers-rest']) ? [] : [
326
+ `npm install @domain-first/handlers-rest@^${minimalHandlersRest.join('.')}`
327
+ ],
328
+ ...dependencies.tsx ? [] : [
329
+ 'npm install --save-dev tsx'
330
+ ],
331
+ ...describeScripts(selected, {
332
+ openapi: `generate the OpenAPI document from restHandlers in ${splitPath(outputPath).join('/')}`
333
+ }),
334
+ ...hasRestHandlers ? [] : [
335
+ `restHandlers appear in ${external_node_path_default().posix.join(rootFolder, 'presentation/rest/index.ts')} with the first REST endpoint generated with @domain-first/wire`
336
+ ]
337
+ ];
338
+ };
261
339
  const addGitignoreEntry = (root, entry)=>{
262
340
  const gitignore = new File(external_node_path_default().join(root, '.gitignore'));
263
341
  const ignored = gitignore.exists ? gitignore.data : '';
@@ -265,6 +343,154 @@ const addGitignoreEntry = (root, entry)=>{
265
343
  const newline = ignored.includes('\r\n') ? '\r\n' : '\n';
266
344
  gitignore.update(`${ignored}${ignored && !ignored.endsWith('\n') ? newline : ''}${entry}${newline}`);
267
345
  };
346
+ const dataLayerFolder = (rootFolder)=>external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react/data-layer');
347
+ const orvalScripts = (rootFolder)=>({
348
+ 'client:orval': `orval --config ${JSON.stringify(`${dataLayerFolder(rootFolder)}/orval.config.ts`)}`
349
+ });
350
+ const orvalConfig = (rootFolder, openapiPath, withNext)=>{
351
+ const inputPath = external_node_path_default().posix.relative(dataLayerFolder(rootFolder), openapiPath);
352
+ const baseUrl = withNext ? `
353
+ baseUrl: {
354
+ runtime: 'process.env.NEXT_PUBLIC_API_BASE_URL ?? ""'
355
+ },` : '';
356
+ return `import { defineConfig } from 'orval';
357
+
358
+ export default defineConfig({
359
+ api: {
360
+ input: '${inputPath.startsWith('.') ? inputPath : `./${inputPath}`}',
361
+ output: {
362
+ mode: 'tags-split',
363
+ target: './orval',
364
+ schemas: './orval/model',
365
+ client: 'react-query',
366
+ httpClient: 'fetch',${baseUrl}
367
+ clean: true,
368
+ override: {
369
+ mutator: {
370
+ path: './api-client/mutator.ts',
371
+ name: 'customInstance'
372
+ },
373
+ fetch: {
374
+ includeHttpResponseReturnType: false
375
+ },
376
+ query: {
377
+ version: 5
378
+ }
379
+ }
380
+ }
381
+ }
382
+ });
383
+ `;
384
+ };
385
+ const orvalMutator = `/** Error of the generated hooks, with the parsed response body. */
386
+ export class ApiError<Body = unknown> extends Error {
387
+ constructor(
388
+ public readonly status: number,
389
+ public readonly body: Body
390
+ ) {
391
+ super(\`API error \${status}\`);
392
+ this.name = 'ApiError';
393
+ }
394
+ }
395
+
396
+ /** Error type of the generated hooks, typed per endpoint by Orval. */
397
+ export type ErrorType<Body> = ApiError<Body>;
398
+
399
+ /** Every generated request goes through here: add auth headers, token refresh, logging. */
400
+ export const customInstance = async <T>(
401
+ url: string,
402
+ init?: RequestInit
403
+ ): Promise<T> => {
404
+ const response = await fetch(url, init);
405
+ const text = await response.text();
406
+ const body = text ? JSON.parse(text) : undefined;
407
+
408
+ if (!response.ok) {
409
+ throw new ApiError(response.status, body);
410
+ }
411
+
412
+ return body as T;
413
+ };
414
+ `;
415
+ const queryProvider = `'use client';
416
+
417
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
418
+ import { type FC, type ReactNode, useState } from 'react';
419
+
420
+ export const QueryProvider: FC<{ children: ReactNode }> = ({ children }) => {
421
+ // One client per browser session; a module-level client would be shared between requests on the server
422
+ const [queryClient] = useState(() => new QueryClient());
423
+
424
+ return (
425
+ <QueryClientProvider client={queryClient}>
426
+ {children}
427
+ </QueryClientProvider>
428
+ );
429
+ };
430
+ `;
431
+ const openapiOutputPath = (root)=>{
432
+ const generator = new File(external_node_path_default().join(root, openapiScriptPath));
433
+ if (!generator.exists) return;
434
+ return generator.data.match(/outputFile:\s*{\s*path:\s*'([^']+)'/)?.[1];
435
+ };
436
+ const addOrval = async ()=>{
437
+ const { rootFolder } = ConfigFile.Instance.data;
438
+ const root = new ProjectRoot().path;
439
+ const manifestFile = new File(external_node_path_default().join(root, 'package.json'));
440
+ const manifest = JSON.parse(manifestFile.data);
441
+ const dependencies = {
442
+ ...manifest.dependencies,
443
+ ...manifest.devDependencies
444
+ };
445
+ const withNext = Boolean(dependencies.next);
446
+ const generatedOpenapiPath = openapiOutputPath(root);
447
+ const openapiPath = await (0, prompts_namespaceObject.input)({
448
+ message: 'OpenAPI document path:',
449
+ default: generatedOpenapiPath ?? defaultOpenapiPath(withNext),
450
+ validate: (value)=>value.trim() ? true : 'Path is required'
451
+ });
452
+ const selected = await addPackageScripts(manifestFile, orvalScripts(rootFolder));
453
+ const dataLayer = dataLayerFolder(rootFolder);
454
+ const configFile = new File(external_node_path_default().join(root, dataLayer, 'orval.config.ts'));
455
+ const content = orvalConfig(rootFolder, external_node_path_default().posix.normalize(openapiPath.trim().replaceAll('\\', '/')), withNext);
456
+ if (!configFile.exists || configFile.data !== content) configFile.data = content;
457
+ for (const [name, fileContent] of [
458
+ [
459
+ 'api-client/mutator.ts',
460
+ orvalMutator
461
+ ],
462
+ [
463
+ 'query-provider.tsx',
464
+ queryProvider
465
+ ]
466
+ ]){
467
+ const file = new File(external_node_path_default().join(root, dataLayer, name));
468
+ if (!file.exists) file.data = fileContent;
469
+ }
470
+ addGitignoreEntry(root, `/${dataLayer}/orval/`);
471
+ const missing = (names)=>names.filter((name)=>!dependencies[name]);
472
+ const runtime = missing([
473
+ '@tanstack/react-query'
474
+ ]);
475
+ const development = missing([
476
+ 'orval'
477
+ ]);
478
+ return [
479
+ ...runtime.length ? [
480
+ `npm install ${runtime.join(' ')}`
481
+ ] : [],
482
+ ...development.length ? [
483
+ `npm install --save-dev ${development.join(' ')}`
484
+ ] : [],
485
+ ...describeScripts(selected, {
486
+ 'client:orval': `generate React Query hooks from ${openapiPath.trim()} in ${dataLayer}/orval`
487
+ }),
488
+ `Wrap your app in QueryProvider from ${dataLayer}/query-provider.tsx`,
489
+ ...generatedOpenapiPath ? [] : [
490
+ 'Add integration → OpenAPI generates the OpenAPI document the client is built from'
491
+ ]
492
+ ];
493
+ };
268
494
  const playwrightScripts = {
269
495
  'test:e2e': 'playwright test'
270
496
  };
@@ -685,6 +911,7 @@ const addVitest = async ()=>{
685
911
  })
686
912
  ];
687
913
  };
914
+ const withHandlersRest = ()=>ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers-rest');
688
915
  const integrations = [
689
916
  {
690
917
  name: 'Storybook (React + Vite)',
@@ -702,20 +929,30 @@ const integrations = [
702
929
  name: 'Playwright',
703
930
  run: addPlaywright
704
931
  },
932
+ {
933
+ name: 'OpenAPI',
934
+ run: addOpenapi,
935
+ available: ()=>withHandlersRest()
936
+ },
937
+ {
938
+ name: 'Orval (React Query client)',
939
+ run: addOrval,
940
+ available: ()=>withHandlersRest() && ConfigFile.Instance.data.useReact
941
+ },
705
942
  {
706
943
  name: 'Missing domain-first packages',
707
944
  run: missingDomainFirstPackages
708
945
  }
709
946
  ];
710
947
  const addIntegration = async ()=>{
711
- const index = await (0, prompts_namespaceObject.select)({
948
+ const integration = await (0, prompts_namespaceObject.select)({
712
949
  message: 'Integration:',
713
- choices: integrations.map((integration, value)=>({
714
- name: integration.name,
950
+ choices: integrations.filter(({ available })=>available?.() ?? true).map((value)=>({
951
+ name: value.name,
715
952
  value
716
953
  }))
717
954
  });
718
- const nextSteps = await integrations[index].run();
955
+ const nextSteps = await integration.run();
719
956
  if (await savePendingChanges()) {
720
957
  const isCommand = (line)=>/^\s*(?:npm (?:i|install)|npx playwright install)\b/.test(line);
721
958
  const commands = nextSteps.filter(isCommand);
package/dist/index.js CHANGED
@@ -228,6 +228,84 @@ const addPackageScripts = async (file, additions)=>{
228
228
  return selected;
229
229
  };
230
230
  const describeScripts = (selected, descriptions)=>Object.entries(descriptions).filter(([name])=>selected[name]).map(([name, description])=>`npm run ${selected[name]} — ${description}`);
231
+ const openapiScriptPath = "scripts/generate-openapi.ts";
232
+ const defaultOpenapiPath = (withNext)=>withNext ? 'public/openapi.json' : 'openapi.json';
233
+ const openapiScripts = {
234
+ openapi: `tsx --env-file-if-exists=.env ${openapiScriptPath}`
235
+ };
236
+ const splitPath = (value)=>value.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
237
+ const apiTitle = (packageName)=>{
238
+ const words = String(packageName ?? '').replace(/^@[^/]*\//, '').split(/[^a-zA-Z0-9]+/).filter((word)=>!!word).map((word)=>word[0].toUpperCase() + word.slice(1));
239
+ return [
240
+ ...words,
241
+ 'API'
242
+ ].join(' ');
243
+ };
244
+ const openapiGenerator = (rootFolder, title, routePrefix, outputPath)=>{
245
+ const restFolder = node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/rest');
246
+ const restImport = node_path.posix.relative(node_path.posix.dirname(openapiScriptPath), restFolder);
247
+ const prefixSegments = splitPath(routePrefix);
248
+ const apiRoutePrefix = prefixSegments.length ? `\n apiRoutePrefix: [${prefixSegments.map((segment)=>`'${segment}'`).join(', ')}],` : '';
249
+ return `import { generateOpenAPI } from '@domain-first/handlers-rest';
250
+ import { restHandlers } from '${restImport.startsWith('.') ? restImport : `./${restImport}`}';
251
+
252
+ generateOpenAPI(restHandlers, {
253
+ document: { info: { title: '${title}', version: '1.0.0' } },${apiRoutePrefix}
254
+ outputFile: { path: '${outputPath}' }
255
+ });
256
+ `;
257
+ };
258
+ const minimalHandlersRest = [
259
+ 7,
260
+ 0,
261
+ 2
262
+ ];
263
+ const parseVersion = (value)=>String(value ?? '').match(/(\d+)\.(\d+)\.(\d+)/)?.slice(1).map(Number);
264
+ const handlersRestUpToDate = (root, declared)=>{
265
+ const installed = new File(node_path.join(root, 'node_modules/@domain-first/handlers-rest/package.json'));
266
+ const version = parseVersion(installed.exists ? JSON.parse(installed.data).version : declared);
267
+ if (!version) return false;
268
+ for (const [index, part] of minimalHandlersRest.entries())if (version[index] !== part) return version[index] > part;
269
+ return true;
270
+ };
271
+ const addOpenapi = async ()=>{
272
+ const { rootFolder } = ConfigFile.Instance.data;
273
+ const root = new ProjectRoot().path;
274
+ const manifestFile = new File(node_path.join(root, 'package.json'));
275
+ const manifest = JSON.parse(manifestFile.data);
276
+ const dependencies = {
277
+ ...manifest.dependencies,
278
+ ...manifest.devDependencies
279
+ };
280
+ const routePrefix = await input({
281
+ message: 'Route prefix the REST handlers are served under:',
282
+ default: '/api'
283
+ });
284
+ const outputPath = await input({
285
+ message: 'OpenAPI document path:',
286
+ default: defaultOpenapiPath(Boolean(dependencies.next)),
287
+ validate: (value)=>splitPath(value).length ? true : 'Path is required'
288
+ });
289
+ const selected = await addPackageScripts(manifestFile, openapiScripts);
290
+ const generatorFile = new File(node_path.join(root, openapiScriptPath));
291
+ const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'));
292
+ if (!generatorFile.exists || generatorFile.data !== content) generatorFile.data = content;
293
+ const hasRestHandlers = new File(node_path.join(root, rootFolder, 'presentation', 'rest', 'index.ts')).exists;
294
+ return [
295
+ ...handlersRestUpToDate(root, dependencies['@domain-first/handlers-rest']) ? [] : [
296
+ `npm install @domain-first/handlers-rest@^${minimalHandlersRest.join('.')}`
297
+ ],
298
+ ...dependencies.tsx ? [] : [
299
+ 'npm install --save-dev tsx'
300
+ ],
301
+ ...describeScripts(selected, {
302
+ openapi: `generate the OpenAPI document from restHandlers in ${splitPath(outputPath).join('/')}`
303
+ }),
304
+ ...hasRestHandlers ? [] : [
305
+ `restHandlers appear in ${node_path.posix.join(rootFolder, 'presentation/rest/index.ts')} with the first REST endpoint generated with @domain-first/wire`
306
+ ]
307
+ ];
308
+ };
231
309
  const addGitignoreEntry = (root, entry)=>{
232
310
  const gitignore = new File(node_path.join(root, '.gitignore'));
233
311
  const ignored = gitignore.exists ? gitignore.data : '';
@@ -235,6 +313,154 @@ const addGitignoreEntry = (root, entry)=>{
235
313
  const newline = ignored.includes('\r\n') ? '\r\n' : '\n';
236
314
  gitignore.update(`${ignored}${ignored && !ignored.endsWith('\n') ? newline : ''}${entry}${newline}`);
237
315
  };
316
+ const dataLayerFolder = (rootFolder)=>node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react/data-layer');
317
+ const orvalScripts = (rootFolder)=>({
318
+ 'client:orval': `orval --config ${JSON.stringify(`${dataLayerFolder(rootFolder)}/orval.config.ts`)}`
319
+ });
320
+ const orvalConfig = (rootFolder, openapiPath, withNext)=>{
321
+ const inputPath = node_path.posix.relative(dataLayerFolder(rootFolder), openapiPath);
322
+ const baseUrl = withNext ? `
323
+ baseUrl: {
324
+ runtime: 'process.env.NEXT_PUBLIC_API_BASE_URL ?? ""'
325
+ },` : '';
326
+ return `import { defineConfig } from 'orval';
327
+
328
+ export default defineConfig({
329
+ api: {
330
+ input: '${inputPath.startsWith('.') ? inputPath : `./${inputPath}`}',
331
+ output: {
332
+ mode: 'tags-split',
333
+ target: './orval',
334
+ schemas: './orval/model',
335
+ client: 'react-query',
336
+ httpClient: 'fetch',${baseUrl}
337
+ clean: true,
338
+ override: {
339
+ mutator: {
340
+ path: './api-client/mutator.ts',
341
+ name: 'customInstance'
342
+ },
343
+ fetch: {
344
+ includeHttpResponseReturnType: false
345
+ },
346
+ query: {
347
+ version: 5
348
+ }
349
+ }
350
+ }
351
+ }
352
+ });
353
+ `;
354
+ };
355
+ const orvalMutator = `/** Error of the generated hooks, with the parsed response body. */
356
+ export class ApiError<Body = unknown> extends Error {
357
+ constructor(
358
+ public readonly status: number,
359
+ public readonly body: Body
360
+ ) {
361
+ super(\`API error \${status}\`);
362
+ this.name = 'ApiError';
363
+ }
364
+ }
365
+
366
+ /** Error type of the generated hooks, typed per endpoint by Orval. */
367
+ export type ErrorType<Body> = ApiError<Body>;
368
+
369
+ /** Every generated request goes through here: add auth headers, token refresh, logging. */
370
+ export const customInstance = async <T>(
371
+ url: string,
372
+ init?: RequestInit
373
+ ): Promise<T> => {
374
+ const response = await fetch(url, init);
375
+ const text = await response.text();
376
+ const body = text ? JSON.parse(text) : undefined;
377
+
378
+ if (!response.ok) {
379
+ throw new ApiError(response.status, body);
380
+ }
381
+
382
+ return body as T;
383
+ };
384
+ `;
385
+ const queryProvider = `'use client';
386
+
387
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
388
+ import { type FC, type ReactNode, useState } from 'react';
389
+
390
+ export const QueryProvider: FC<{ children: ReactNode }> = ({ children }) => {
391
+ // One client per browser session; a module-level client would be shared between requests on the server
392
+ const [queryClient] = useState(() => new QueryClient());
393
+
394
+ return (
395
+ <QueryClientProvider client={queryClient}>
396
+ {children}
397
+ </QueryClientProvider>
398
+ );
399
+ };
400
+ `;
401
+ const openapiOutputPath = (root)=>{
402
+ const generator = new File(node_path.join(root, openapiScriptPath));
403
+ if (!generator.exists) return;
404
+ return generator.data.match(/outputFile:\s*{\s*path:\s*'([^']+)'/)?.[1];
405
+ };
406
+ const addOrval = async ()=>{
407
+ const { rootFolder } = ConfigFile.Instance.data;
408
+ const root = new ProjectRoot().path;
409
+ const manifestFile = new File(node_path.join(root, 'package.json'));
410
+ const manifest = JSON.parse(manifestFile.data);
411
+ const dependencies = {
412
+ ...manifest.dependencies,
413
+ ...manifest.devDependencies
414
+ };
415
+ const withNext = Boolean(dependencies.next);
416
+ const generatedOpenapiPath = openapiOutputPath(root);
417
+ const openapiPath = await input({
418
+ message: 'OpenAPI document path:',
419
+ default: generatedOpenapiPath ?? defaultOpenapiPath(withNext),
420
+ validate: (value)=>value.trim() ? true : 'Path is required'
421
+ });
422
+ const selected = await addPackageScripts(manifestFile, orvalScripts(rootFolder));
423
+ const dataLayer = dataLayerFolder(rootFolder);
424
+ const configFile = new File(node_path.join(root, dataLayer, 'orval.config.ts'));
425
+ const content = orvalConfig(rootFolder, node_path.posix.normalize(openapiPath.trim().replaceAll('\\', '/')), withNext);
426
+ if (!configFile.exists || configFile.data !== content) configFile.data = content;
427
+ for (const [name, fileContent] of [
428
+ [
429
+ 'api-client/mutator.ts',
430
+ orvalMutator
431
+ ],
432
+ [
433
+ 'query-provider.tsx',
434
+ queryProvider
435
+ ]
436
+ ]){
437
+ const file = new File(node_path.join(root, dataLayer, name));
438
+ if (!file.exists) file.data = fileContent;
439
+ }
440
+ addGitignoreEntry(root, `/${dataLayer}/orval/`);
441
+ const missing = (names)=>names.filter((name)=>!dependencies[name]);
442
+ const runtime = missing([
443
+ '@tanstack/react-query'
444
+ ]);
445
+ const development = missing([
446
+ 'orval'
447
+ ]);
448
+ return [
449
+ ...runtime.length ? [
450
+ `npm install ${runtime.join(' ')}`
451
+ ] : [],
452
+ ...development.length ? [
453
+ `npm install --save-dev ${development.join(' ')}`
454
+ ] : [],
455
+ ...describeScripts(selected, {
456
+ 'client:orval': `generate React Query hooks from ${openapiPath.trim()} in ${dataLayer}/orval`
457
+ }),
458
+ `Wrap your app in QueryProvider from ${dataLayer}/query-provider.tsx`,
459
+ ...generatedOpenapiPath ? [] : [
460
+ 'Add integration → OpenAPI generates the OpenAPI document the client is built from'
461
+ ]
462
+ ];
463
+ };
238
464
  const playwrightScripts = {
239
465
  'test:e2e': 'playwright test'
240
466
  };
@@ -655,6 +881,7 @@ const addVitest = async ()=>{
655
881
  })
656
882
  ];
657
883
  };
884
+ const withHandlersRest = ()=>ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers-rest');
658
885
  const integrations = [
659
886
  {
660
887
  name: 'Storybook (React + Vite)',
@@ -672,20 +899,30 @@ const integrations = [
672
899
  name: 'Playwright',
673
900
  run: addPlaywright
674
901
  },
902
+ {
903
+ name: 'OpenAPI',
904
+ run: addOpenapi,
905
+ available: ()=>withHandlersRest()
906
+ },
907
+ {
908
+ name: 'Orval (React Query client)',
909
+ run: addOrval,
910
+ available: ()=>withHandlersRest() && ConfigFile.Instance.data.useReact
911
+ },
675
912
  {
676
913
  name: 'Missing domain-first packages',
677
914
  run: missingDomainFirstPackages
678
915
  }
679
916
  ];
680
917
  const addIntegration = async ()=>{
681
- const index = await prompts_select({
918
+ const integration = await prompts_select({
682
919
  message: 'Integration:',
683
- choices: integrations.map((integration, value)=>({
684
- name: integration.name,
920
+ choices: integrations.filter(({ available })=>available?.() ?? true).map((value)=>({
921
+ name: value.name,
685
922
  value
686
923
  }))
687
924
  });
688
- const nextSteps = await integrations[index].run();
925
+ const nextSteps = await integration.run();
689
926
  if (await savePendingChanges()) {
690
927
  const isCommand = (line)=>/^\s*(?:npm (?:i|install)|npx playwright install)\b/.test(line);
691
928
  const commands = nextSteps.filter(isCommand);
@@ -1,4 +1,6 @@
1
1
  export * from './missing-domain-first-packages';
2
+ export * from './openapi';
3
+ export * from './orval';
2
4
  export * from './package-scripts';
3
5
  export * from './playwright';
4
6
  export * from './prisma';
@@ -0,0 +1,13 @@
1
+ export declare const openapiScriptPath = "scripts/generate-openapi.ts";
2
+ export declare const defaultOpenapiPath: (withNext: boolean) => "public/openapi.json" | "openapi.json";
3
+ export declare const openapiScripts: {
4
+ openapi: string;
5
+ };
6
+ export declare const apiTitle: (packageName: unknown) => string;
7
+ export declare const openapiGenerator: (rootFolder: string, title: string, routePrefix: string, outputPath: string) => string;
8
+ /**
9
+ * The installed version wins over the declared range, which only gives
10
+ * the lowest version allowed.
11
+ */
12
+ export declare const handlersRestUpToDate: (root: string, declared: unknown) => boolean;
13
+ export declare const addOpenapi: () => Promise<string[]>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,11 @@
1
+ export declare const orvalScripts: (rootFolder: string) => {
2
+ 'client:orval': string;
3
+ };
4
+ /**
5
+ * Orval resolves paths relative to the config, which lives in the data layer
6
+ * folder next to the generated client.
7
+ */
8
+ export declare const orvalConfig: (rootFolder: string, openapiPath: string, withNext: boolean) => string;
9
+ export declare const orvalMutator = "/** Error of the generated hooks, with the parsed response body. */\nexport class ApiError<Body = unknown> extends Error {\n constructor(\n public readonly status: number,\n public readonly body: Body\n ) {\n super(`API error ${status}`);\n this.name = 'ApiError';\n }\n}\n\n/** Error type of the generated hooks, typed per endpoint by Orval. */\nexport type ErrorType<Body> = ApiError<Body>;\n\n/** Every generated request goes through here: add auth headers, token refresh, logging. */\nexport const customInstance = async <T>(\n url: string,\n init?: RequestInit\n): Promise<T> => {\n const response = await fetch(url, init);\n const text = await response.text();\n const body = text ? JSON.parse(text) : undefined;\n\n if (!response.ok) {\n throw new ApiError(response.status, body);\n }\n\n return body as T;\n};\n";
10
+ export declare const queryProvider = "'use client';\n\nimport { QueryClient, QueryClientProvider } from '@tanstack/react-query';\nimport { type FC, type ReactNode, useState } from 'react';\n\nexport const QueryProvider: FC<{ children: ReactNode }> = ({ children }) => {\n // One client per browser session; a module-level client would be shared between requests on the server\n const [queryClient] = useState(() => new QueryClient());\n\n return (\n <QueryClientProvider client={queryClient}>\n {children}\n </QueryClientProvider>\n );\n};\n";
11
+ export declare const addOrval: () => Promise<string[]>;
@@ -0,0 +1 @@
1
+ export {};
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": "2.14.2",
4
+ "version": "2.15.1",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",