@domain-first/project-structure 8.8.0 → 8.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -479,6 +479,371 @@ class config_file_ConfigFile {
479
479
  }
480
480
  }
481
481
  const configuredDependencyRules = ()=>resolveDependencyRules(config_file_ConfigFile.exists ? config_file_ConfigFile.Instance.data.backend?.rules?.dependencies : void 0);
482
+ const savedImplementations = (kind, purpose)=>[
483
+ ...new Set(config_file_ConfigFile.Instance.data.backend?.implementations?.[kind]?.[purpose] ?? [])
484
+ ];
485
+ const rememberImplementation = (kind, purpose, label)=>{
486
+ implementationLabelSchema.parse(label);
487
+ const backend = config_file_ConfigFile.backend;
488
+ const choices = {
489
+ ...backend.implementations
490
+ };
491
+ const group = choices[kind] ?? {
492
+ primary: [],
493
+ test: []
494
+ };
495
+ if (group[purpose].includes(label)) return;
496
+ choices[kind] = {
497
+ ...group,
498
+ [purpose]: [
499
+ ...group[purpose],
500
+ label
501
+ ]
502
+ };
503
+ config_file_ConfigFile.update({
504
+ backend: {
505
+ ...backend,
506
+ implementations: choices
507
+ }
508
+ });
509
+ };
510
+ const external_node_async_hooks_namespaceObject = require("node:async_hooks");
511
+ const prompts_namespaceObject = require("@inquirer/prompts");
512
+ const isSeparator = (choice)=>'function' == typeof prompts_namespaceObject.Separator && choice instanceof prompts_namespaceObject.Separator || 'object' == typeof choice && null !== choice && 'separator' === choice.type;
513
+ class RequestError extends Error {
514
+ code;
515
+ details;
516
+ constructor(code, message, details){
517
+ super(message), this.code = code, this.details = details;
518
+ }
519
+ }
520
+ const storage = new external_node_async_hooks_namespaceObject.AsyncLocalStorage();
521
+ const isNonInteractive = ()=>Boolean(storage.getStore());
522
+ const runWithAnswers = async (answers, defaults, run)=>storage.run({
523
+ answers,
524
+ defaults,
525
+ used: new Set(),
526
+ messages: []
527
+ }, async ()=>{
528
+ const result = await run();
529
+ const state = storage.getStore();
530
+ assertAnswersConsumed();
531
+ return {
532
+ result,
533
+ messages: state.messages
534
+ };
535
+ });
536
+ const assertAnswersConsumed = ()=>{
537
+ const state = storage.getStore();
538
+ if (!state) return;
539
+ const unused = Object.keys(state.answers).filter((key)=>!state.used.has(key));
540
+ if (unused.length) throw new RequestError('UNUSED_PARAMETERS', 'Some parameters do not apply to this operation.', {
541
+ fields: unused
542
+ });
543
+ };
544
+ const answerFor = (key, fallback)=>{
545
+ const state = storage.getStore();
546
+ if (!state) return;
547
+ if (Object.hasOwn(state.answers, key)) {
548
+ state.used.add(key);
549
+ return state.answers[key];
550
+ }
551
+ return Object.hasOwn(state.defaults, key) ? state.defaults[key] : fallback;
552
+ };
553
+ const report = (...values)=>{
554
+ const state = storage.getStore();
555
+ if (state) state.messages.push(values.map(String).join(' '));
556
+ else console.log(...values);
557
+ };
558
+ const requireKey = (key)=>{
559
+ if (!key) throw new RequestError('UNSUPPORTED_PROMPT', 'This operation needs an answer that is not supported in non-interactive mode.');
560
+ return key;
561
+ };
562
+ const interaction_missing = (key)=>new RequestError('MISSING_PARAMETER', `Provide ${key}.`, {
563
+ field: key
564
+ });
565
+ const interaction_input = async (config)=>{
566
+ const { key, ...interactive } = config;
567
+ if (!isNonInteractive()) return (0, prompts_namespaceObject.input)(interactive);
568
+ const field = requireKey(key);
569
+ const value = answerFor(field, config.default);
570
+ if ('string' != typeof value) throw interaction_missing(field);
571
+ const valid = await config.validate?.(value);
572
+ if (void 0 !== valid && true !== valid) throw new RequestError('INVALID_PARAMETER', 'string' == typeof valid ? valid : `Invalid ${field}.`, {
573
+ field
574
+ });
575
+ return value;
576
+ };
577
+ const interaction_confirm = async (config)=>{
578
+ const { key, requestRequired, ...interactive } = config;
579
+ if (!isNonInteractive()) return (0, prompts_namespaceObject.confirm)(interactive);
580
+ const field = requireKey(key);
581
+ const value = answerFor(field, requestRequired ? void 0 : config.default ?? false);
582
+ if (void 0 === value) throw interaction_missing(field);
583
+ if ('boolean' != typeof value) throw new RequestError('INVALID_PARAMETER', `${field} must be a boolean.`, {
584
+ field
585
+ });
586
+ return value;
587
+ };
588
+ const choicesOf = (config)=>config.choices.filter((choice)=>!isSeparator(choice)).map((choice)=>'object' == typeof choice && null !== choice && 'value' in choice ? choice : {
589
+ value: choice
590
+ });
591
+ const choiceId = (choice, id)=>id?.(choice.value) ?? choice.value;
592
+ const resolveChoice = (value, choices, key, id)=>{
593
+ const matches = choices.filter((choice)=>Object.is(choice.value, value) || choiceId(choice, id) === value);
594
+ if (1 !== matches.length || matches[0].disabled) throw new RequestError('INVALID_CHOICE', `Invalid or unavailable choice for ${key}.`, {
595
+ field: key,
596
+ value,
597
+ choices: choices.filter((choice)=>!choice.disabled).map((choice)=>choiceId(choice, id))
598
+ });
599
+ return matches[0].value;
600
+ };
601
+ const searchThreshold = 10;
602
+ const choiceLabel = (choice)=>choice.name ?? String(choice.value);
603
+ const filterChoices = (choices, term)=>{
604
+ const text = (term ?? '').trim().toLowerCase();
605
+ const words = text.split(/\s+/).filter(Boolean);
606
+ if (!words.length) return [
607
+ ...choices
608
+ ];
609
+ const groups = [
610
+ {
611
+ matches: []
612
+ }
613
+ ];
614
+ for (const choice of choices){
615
+ if (isSeparator(choice)) {
616
+ groups.push({
617
+ separator: choice,
618
+ matches: []
619
+ });
620
+ continue;
621
+ }
622
+ const normalized = 'object' == typeof choice && null !== choice && 'value' in choice ? choice : {
623
+ value: choice
624
+ };
625
+ const label = choiceLabel(normalized).toLowerCase();
626
+ if (words.every((word)=>label.includes(word))) groups.at(-1)?.matches.push({
627
+ choice: normalized,
628
+ prefix: label.startsWith(text)
629
+ });
630
+ }
631
+ const byPrefix = (items, prefix)=>[
632
+ ...items.filter(prefix),
633
+ ...items.filter((item)=>!prefix(item))
634
+ ];
635
+ const [ungrouped, ...grouped] = groups;
636
+ return [
637
+ ungrouped,
638
+ ...byPrefix(grouped.filter(({ matches })=>matches.length), ({ matches })=>matches.some(({ prefix })=>prefix))
639
+ ].flatMap(({ separator, matches })=>[
640
+ ...separator ? [
641
+ separator
642
+ ] : [],
643
+ ...byPrefix(matches, ({ prefix })=>prefix).map(({ choice })=>choice)
644
+ ]);
645
+ };
646
+ const interaction_select = async (config)=>{
647
+ const { key, id, ...interactive } = config;
648
+ if (!isNonInteractive()) {
649
+ if (choicesOf(config).length <= searchThreshold) return (0, prompts_namespaceObject.select)(interactive);
650
+ return (0, prompts_namespaceObject.search)({
651
+ message: `${config.message.trimEnd()} (type to filter)`,
652
+ source: (term)=>filterChoices(config.choices, term),
653
+ pageSize: config.pageSize,
654
+ default: config.default
655
+ });
656
+ }
657
+ const field = requireKey(key);
658
+ const value = answerFor(field, config.default);
659
+ if (void 0 === value) throw interaction_missing(field);
660
+ return resolveChoice(value, choicesOf(config), field, id);
661
+ };
662
+ const interaction_checkbox = async (config)=>{
663
+ const { key, id, ...interactive } = config;
664
+ if (!isNonInteractive()) return (0, prompts_namespaceObject.checkbox)(interactive);
665
+ const field = requireKey(key);
666
+ const choices = choicesOf(config);
667
+ const values = answerFor(field, choices.filter((choice)=>choice.checked && !choice.disabled).map((choice)=>choice.value));
668
+ if (!Array.isArray(values)) throw new RequestError('INVALID_PARAMETER', `${field} must be an array.`, {
669
+ field
670
+ });
671
+ const selected = values.map((value)=>resolveChoice(value, choices, field, id));
672
+ if (new Set(selected).size !== selected.length) throw new RequestError('INVALID_PARAMETER', `Duplicate choices for ${field}.`, {
673
+ field
674
+ });
675
+ if (config.required && !selected.length) throw interaction_missing(field);
676
+ return selected;
677
+ };
678
+ const addPackageScripts = async (file, additions)=>{
679
+ const original = file.data;
680
+ const manifest = JSON.parse(original);
681
+ const scripts = {
682
+ ...manifest.scripts
683
+ };
684
+ const selected = {};
685
+ for (const [name, command] of Object.entries(additions)){
686
+ let target = name;
687
+ if (Object.hasOwn(scripts, name) && scripts[name] !== command) {
688
+ const action = await interaction_select({
689
+ key: `scriptConflicts.${name}`,
690
+ message: `Script "${name}" already exists: ${scripts[name]}`,
691
+ choices: [
692
+ 'Keep existing',
693
+ 'Replace',
694
+ 'Use another name'
695
+ ]
696
+ });
697
+ if ('Keep existing' === action) continue;
698
+ if ('Use another name' === action) target = await interaction_input({
699
+ key: `scriptNames.${name}`,
700
+ message: "New script name:",
701
+ validate: (value)=>!/^[a-zA-Z0-9:_-]+$/.test(value) || Object.hasOwn(scripts, value) || Object.hasOwn(additions, value) ? "Enter an unused script name (letters, numbers, :, _, -)." : true
702
+ });
703
+ }
704
+ scripts[target] = command;
705
+ selected[name] = target;
706
+ }
707
+ if (JSON.stringify(manifest.scripts) !== JSON.stringify(scripts)) {
708
+ manifest.scripts = scripts;
709
+ const indent = original.match(/\n([\t ]+)"/)?.[1] ?? ' ';
710
+ file.update(`${JSON.stringify(manifest, null, indent)}\n`);
711
+ }
712
+ return selected;
713
+ };
714
+ const describeScripts = (selected, descriptions)=>Object.entries(descriptions).filter(([name])=>selected[name]).map(([name, description])=>`npm run ${selected[name]} — ${description}`);
715
+ const runtimePackages = [
716
+ 'drizzle-orm',
717
+ 'pg',
718
+ 'dotenv'
719
+ ];
720
+ const developmentPackages = [
721
+ 'drizzle-kit',
722
+ '@types/pg'
723
+ ];
724
+ const drizzleFolder = (rootFolder)=>external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), 'shared-kernel/infrastructure/drizzle');
725
+ const drizzleConfigPath = (rootFolder)=>external_node_path_default().posix.join(drizzleFolder(rootFolder), 'drizzle.config.ts');
726
+ const drizzleScripts = (rootFolder)=>{
727
+ const config = JSON.stringify(drizzleConfigPath(rootFolder));
728
+ return {
729
+ 'drizzle:generate': `drizzle-kit generate --config ${config}`,
730
+ 'drizzle:migrate': `drizzle-kit migrate --config ${config}`
731
+ };
732
+ };
733
+ const drizzleConfig = (rootFolder)=>{
734
+ const folder = drizzleFolder(rootFolder);
735
+ return `import 'dotenv/config';
736
+ import { defineConfig } from 'drizzle-kit';
737
+
738
+ // Paths are relative to the project root, where package scripts run.
739
+ export default defineConfig({
740
+ dialect: 'postgresql',
741
+ schema: ${JSON.stringify(external_node_path_default().posix.join(folder, 'schema.ts'))},
742
+ out: ${JSON.stringify(external_node_path_default().posix.join(folder, 'migrations'))},
743
+ dbCredentials: {
744
+ url: process.env.DATABASE_URL as string
745
+ }
746
+ });
747
+ `;
748
+ };
749
+ const drizzleSchema = `// Add your application tables here before running drizzle:generate, e.g.
750
+ //
751
+ // import { pgTable, text } from 'drizzle-orm/pg-core';
752
+ //
753
+ // export const orders = pgTable('orders', {
754
+ // id: text('id').primaryKey()
755
+ // });
756
+
757
+ export {};
758
+ `;
759
+ const drizzleService = `import { drizzle } from 'drizzle-orm/node-postgres';
760
+ import { Pool } from 'pg';
761
+
762
+ const createDatabase = () =>
763
+ drizzle({
764
+ client: new Pool({ connectionString: process.env.DATABASE_URL })
765
+ });
766
+
767
+ type DrizzleDatabase = ReturnType<typeof createDatabase>;
768
+
769
+ const globalForDrizzle = globalThis as typeof globalThis & {
770
+ drizzleDatabase?: DrizzleDatabase;
771
+ };
772
+
773
+ // Reuse the connection pool across development hot reloads.
774
+ const drizzleDatabase = globalForDrizzle.drizzleDatabase ?? createDatabase();
775
+
776
+ if (process.env.NODE_ENV !== 'production') {
777
+ globalForDrizzle.drizzleDatabase = drizzleDatabase;
778
+ }
779
+
780
+ export class DrizzleInfrastructureService {
781
+ readonly db = drizzleDatabase;
782
+ }
783
+ `;
784
+ const drizzleWiring = `import { wireClass } from '@domain-first/wire';
785
+ import { DrizzleInfrastructureService } from '../../infrastructure/services/drizzle-infrastructure-service';
786
+
787
+ export const wireDrizzleInfrastructureService = wireClass(
788
+ DrizzleInfrastructureService,
789
+ []
790
+ );
791
+ `;
792
+ const stageFile = (filePath, content)=>{
793
+ const file = new file_system_File(filePath);
794
+ if (!file.exists || file.data !== content) file.data = content;
795
+ };
796
+ const addDrizzle = async ()=>{
797
+ const config = config_file_ConfigFile.Instance.data;
798
+ const root = new project_root_ProjectRoot().path;
799
+ const manifestFile = new file_system_File(external_node_path_default().join(root, 'package.json'));
800
+ const manifest = JSON.parse(manifestFile.data);
801
+ const dependencies = {
802
+ ...manifest.dependencies,
803
+ ...manifest.devDependencies
804
+ };
805
+ const shared = external_node_path_default().resolve(root, config.project.rootFolder, 'shared-kernel');
806
+ const folder = external_node_path_default().join(shared, 'infrastructure/drizzle');
807
+ if ([
808
+ 'drizzle.config.ts',
809
+ 'drizzle.config.js',
810
+ 'drizzle.config.json'
811
+ ].some((name)=>new file_system_File(external_node_path_default().join(root, name)).exists)) throw new Error('This preset adds Drizzle for PostgreSQL in the Shared Kernel. Move the existing Drizzle setup separately before using it.');
812
+ const withService = await interaction_confirm({
813
+ key: 'withService',
814
+ message: 'Create the Drizzle infrastructure service in the Shared Kernel?',
815
+ default: true
816
+ });
817
+ const selected = await addPackageScripts(manifestFile, drizzleScripts(config.project.rootFolder));
818
+ stageFile(external_node_path_default().join(folder, 'drizzle.config.ts'), drizzleConfig(config.project.rootFolder));
819
+ const schema = new file_system_File(external_node_path_default().join(folder, 'schema.ts'));
820
+ if (!schema.exists) schema.data = drizzleSchema;
821
+ if (withService) {
822
+ stageFile(external_node_path_default().join(shared, 'infrastructure/services/drizzle-infrastructure-service.ts'), drizzleService);
823
+ if (config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) stageFile(external_node_path_default().join(shared, 'wiring/infrastructure-services/wire-drizzle-infrastructure-service.ts'), drizzleWiring);
824
+ }
825
+ for (const kind of [
826
+ 'repositories',
827
+ 'commands',
828
+ 'queries'
829
+ ])rememberImplementation(kind, 'primary', 'drizzle');
830
+ const install = (packages, dev)=>{
831
+ const missing = packages.filter((name)=>!dependencies[name]);
832
+ return missing.length ? [
833
+ `npm install${dev ? ' --save-dev' : ''} ${missing.join(' ')}`
834
+ ] : [];
835
+ };
836
+ const relativeFolder = external_node_path_default().relative(root, folder).split(external_node_path_default().sep).join('/');
837
+ return [
838
+ ...install(runtimePackages, false),
839
+ ...install(developmentPackages, true),
840
+ `Add !${relativeFolder}/migrations in your linter, to ignore generated migrations.`,
841
+ ...describeScripts(selected, {
842
+ 'drizzle:generate': 'generate a SQL migration from changes in schema.ts',
843
+ 'drizzle:migrate': 'apply generated migrations to the database in DATABASE_URL'
844
+ })
845
+ ];
846
+ };
482
847
  class UnknownFormatNaming {
483
848
  rawSource;
484
849
  camelCase;
@@ -652,6 +1017,10 @@ const systemInfrastructureServices = new Map([
652
1017
  'prisma',
653
1018
  'prisma-infrastructure-service'
654
1019
  ],
1020
+ [
1021
+ 'drizzle',
1022
+ 'drizzle-infrastructure-service'
1023
+ ],
655
1024
  [
656
1025
  'in-memory',
657
1026
  'in-memory-db-infrastructure-service'
@@ -914,6 +1283,11 @@ const inMemoryImplementationType = 'in-memory';
914
1283
  const in_memory_db_className = 'InMemoryDbInfrastructureService';
915
1284
  const in_memory_db_wireName = 'wireInMemoryDbInfrastructureService';
916
1285
  const in_memory_db_parameterName = 'inMemoryDbInfrastructureService';
1286
+ const withIdLookup = ` withId: (id: TId): T | null =>
1287
+ globalThis.___SHARED_IN_MEMORY_DB___![key].find((entry) =>
1288
+ idsAreEqual(entry.id as TId, id)
1289
+ )?.item ?? null,
1290
+ `;
917
1291
  const inMemoryDbService = `type Entry = {
918
1292
  id: unknown;
919
1293
  item: any;
@@ -952,9 +1326,6 @@ const defaultIdsAreEqual = (a: unknown, b: unknown): boolean => {
952
1326
  return Object.is(a, b);
953
1327
  };
954
1328
 
955
- const hasId = (x: unknown): x is { id: unknown } =>
956
- typeof x === 'object' && x !== null && 'id' in x;
957
-
958
1329
  export class InMemoryDbInfrastructureService {
959
1330
  protected section<T extends { id: unknown }>(
960
1331
  key: string,
@@ -986,11 +1357,7 @@ export class InMemoryDbInfrastructureService {
986
1357
  items().filter(predicate),
987
1358
  first: (predicate: (x: T) => boolean): T | null =>
988
1359
  items().find(predicate) ?? null,
989
- withId: (id: TId): T | null =>
990
- items().find(
991
- (x: T) => hasId(x) && idsAreEqual(x.id as TId, id)
992
- ) ?? null,
993
- lastAddedItem: (): T | null =>
1360
+ ${withIdLookup} lastAddedItem: (): T | null =>
994
1361
  globalThis.___SHARED_IN_MEMORY_DB___![key].at(-1)?.item ?? null,
995
1362
  save: (payload: T extends { id: TId } ? T : [TId, T]) => {
996
1363
  const id = Array.isArray(payload) ? payload[0] : payload.id;
@@ -1144,174 +1511,6 @@ const missing_domain_first_packages_missingPackages = (packages)=>{
1144
1511
  `npm i ${missing.join(' ')}`
1145
1512
  ] : [];
1146
1513
  };
1147
- const external_node_async_hooks_namespaceObject = require("node:async_hooks");
1148
- const prompts_namespaceObject = require("@inquirer/prompts");
1149
- const isSeparator = (choice)=>'function' == typeof prompts_namespaceObject.Separator && choice instanceof prompts_namespaceObject.Separator || 'object' == typeof choice && null !== choice && 'separator' === choice.type;
1150
- class RequestError extends Error {
1151
- code;
1152
- details;
1153
- constructor(code, message, details){
1154
- super(message), this.code = code, this.details = details;
1155
- }
1156
- }
1157
- const storage = new external_node_async_hooks_namespaceObject.AsyncLocalStorage();
1158
- const isNonInteractive = ()=>Boolean(storage.getStore());
1159
- const runWithAnswers = async (answers, defaults, run)=>storage.run({
1160
- answers,
1161
- defaults,
1162
- used: new Set(),
1163
- messages: []
1164
- }, async ()=>{
1165
- const result = await run();
1166
- const state = storage.getStore();
1167
- assertAnswersConsumed();
1168
- return {
1169
- result,
1170
- messages: state.messages
1171
- };
1172
- });
1173
- const assertAnswersConsumed = ()=>{
1174
- const state = storage.getStore();
1175
- if (!state) return;
1176
- const unused = Object.keys(state.answers).filter((key)=>!state.used.has(key));
1177
- if (unused.length) throw new RequestError('UNUSED_PARAMETERS', 'Some parameters do not apply to this operation.', {
1178
- fields: unused
1179
- });
1180
- };
1181
- const answerFor = (key, fallback)=>{
1182
- const state = storage.getStore();
1183
- if (!state) return;
1184
- if (Object.hasOwn(state.answers, key)) {
1185
- state.used.add(key);
1186
- return state.answers[key];
1187
- }
1188
- return Object.hasOwn(state.defaults, key) ? state.defaults[key] : fallback;
1189
- };
1190
- const report = (...values)=>{
1191
- const state = storage.getStore();
1192
- if (state) state.messages.push(values.map(String).join(' '));
1193
- else console.log(...values);
1194
- };
1195
- const requireKey = (key)=>{
1196
- if (!key) throw new RequestError('UNSUPPORTED_PROMPT', 'This operation needs an answer that is not supported in non-interactive mode.');
1197
- return key;
1198
- };
1199
- const interaction_missing = (key)=>new RequestError('MISSING_PARAMETER', `Provide ${key}.`, {
1200
- field: key
1201
- });
1202
- const interaction_input = async (config)=>{
1203
- const { key, ...interactive } = config;
1204
- if (!isNonInteractive()) return (0, prompts_namespaceObject.input)(interactive);
1205
- const field = requireKey(key);
1206
- const value = answerFor(field, config.default);
1207
- if ('string' != typeof value) throw interaction_missing(field);
1208
- const valid = await config.validate?.(value);
1209
- if (void 0 !== valid && true !== valid) throw new RequestError('INVALID_PARAMETER', 'string' == typeof valid ? valid : `Invalid ${field}.`, {
1210
- field
1211
- });
1212
- return value;
1213
- };
1214
- const interaction_confirm = async (config)=>{
1215
- const { key, requestRequired, ...interactive } = config;
1216
- if (!isNonInteractive()) return (0, prompts_namespaceObject.confirm)(interactive);
1217
- const field = requireKey(key);
1218
- const value = answerFor(field, requestRequired ? void 0 : config.default ?? false);
1219
- if (void 0 === value) throw interaction_missing(field);
1220
- if ('boolean' != typeof value) throw new RequestError('INVALID_PARAMETER', `${field} must be a boolean.`, {
1221
- field
1222
- });
1223
- return value;
1224
- };
1225
- const choicesOf = (config)=>config.choices.filter((choice)=>!isSeparator(choice)).map((choice)=>'object' == typeof choice && null !== choice && 'value' in choice ? choice : {
1226
- value: choice
1227
- });
1228
- const choiceId = (choice, id)=>id?.(choice.value) ?? choice.value;
1229
- const resolveChoice = (value, choices, key, id)=>{
1230
- const matches = choices.filter((choice)=>Object.is(choice.value, value) || choiceId(choice, id) === value);
1231
- if (1 !== matches.length || matches[0].disabled) throw new RequestError('INVALID_CHOICE', `Invalid or unavailable choice for ${key}.`, {
1232
- field: key,
1233
- value,
1234
- choices: choices.filter((choice)=>!choice.disabled).map((choice)=>choiceId(choice, id))
1235
- });
1236
- return matches[0].value;
1237
- };
1238
- const searchThreshold = 10;
1239
- const choiceLabel = (choice)=>choice.name ?? String(choice.value);
1240
- const filterChoices = (choices, term)=>{
1241
- const text = (term ?? '').trim().toLowerCase();
1242
- const words = text.split(/\s+/).filter(Boolean);
1243
- if (!words.length) return [
1244
- ...choices
1245
- ];
1246
- const groups = [
1247
- {
1248
- matches: []
1249
- }
1250
- ];
1251
- for (const choice of choices){
1252
- if (isSeparator(choice)) {
1253
- groups.push({
1254
- separator: choice,
1255
- matches: []
1256
- });
1257
- continue;
1258
- }
1259
- const normalized = 'object' == typeof choice && null !== choice && 'value' in choice ? choice : {
1260
- value: choice
1261
- };
1262
- const label = choiceLabel(normalized).toLowerCase();
1263
- if (words.every((word)=>label.includes(word))) groups.at(-1)?.matches.push({
1264
- choice: normalized,
1265
- prefix: label.startsWith(text)
1266
- });
1267
- }
1268
- const byPrefix = (items, prefix)=>[
1269
- ...items.filter(prefix),
1270
- ...items.filter((item)=>!prefix(item))
1271
- ];
1272
- const [ungrouped, ...grouped] = groups;
1273
- return [
1274
- ungrouped,
1275
- ...byPrefix(grouped.filter(({ matches })=>matches.length), ({ matches })=>matches.some(({ prefix })=>prefix))
1276
- ].flatMap(({ separator, matches })=>[
1277
- ...separator ? [
1278
- separator
1279
- ] : [],
1280
- ...byPrefix(matches, ({ prefix })=>prefix).map(({ choice })=>choice)
1281
- ]);
1282
- };
1283
- const interaction_select = async (config)=>{
1284
- const { key, id, ...interactive } = config;
1285
- if (!isNonInteractive()) {
1286
- if (choicesOf(config).length <= searchThreshold) return (0, prompts_namespaceObject.select)(interactive);
1287
- return (0, prompts_namespaceObject.search)({
1288
- message: `${config.message.trimEnd()} (type to filter)`,
1289
- source: (term)=>filterChoices(config.choices, term),
1290
- pageSize: config.pageSize,
1291
- default: config.default
1292
- });
1293
- }
1294
- const field = requireKey(key);
1295
- const value = answerFor(field, config.default);
1296
- if (void 0 === value) throw interaction_missing(field);
1297
- return resolveChoice(value, choicesOf(config), field, id);
1298
- };
1299
- const interaction_checkbox = async (config)=>{
1300
- const { key, id, ...interactive } = config;
1301
- if (!isNonInteractive()) return (0, prompts_namespaceObject.checkbox)(interactive);
1302
- const field = requireKey(key);
1303
- const choices = choicesOf(config);
1304
- const values = answerFor(field, choices.filter((choice)=>choice.checked && !choice.disabled).map((choice)=>choice.value));
1305
- if (!Array.isArray(values)) throw new RequestError('INVALID_PARAMETER', `${field} must be an array.`, {
1306
- field
1307
- });
1308
- const selected = values.map((value)=>resolveChoice(value, choices, field, id));
1309
- if (new Set(selected).size !== selected.length) throw new RequestError('INVALID_PARAMETER', `Duplicate choices for ${field}.`, {
1310
- field
1311
- });
1312
- if (config.required && !selected.length) throw interaction_missing(field);
1313
- return selected;
1314
- };
1315
1514
  const usesNext = ()=>config_file_ConfigFile.exists && config_file_ConfigFile.Instance.data.frontend?.react?.framework === 'next';
1316
1515
  const nextAppFolder = (root)=>[
1317
1516
  'app',
@@ -1578,43 +1777,6 @@ ${endpointFileLookup(rootFolder)}
1578
1777
  };
1579
1778
  };
1580
1779
  `;
1581
- const addPackageScripts = async (file, additions)=>{
1582
- const original = file.data;
1583
- const manifest = JSON.parse(original);
1584
- const scripts = {
1585
- ...manifest.scripts
1586
- };
1587
- const selected = {};
1588
- for (const [name, command] of Object.entries(additions)){
1589
- let target = name;
1590
- if (Object.hasOwn(scripts, name) && scripts[name] !== command) {
1591
- const action = await interaction_select({
1592
- key: `scriptConflicts.${name}`,
1593
- message: `Script "${name}" already exists: ${scripts[name]}`,
1594
- choices: [
1595
- 'Keep existing',
1596
- 'Replace',
1597
- 'Use another name'
1598
- ]
1599
- });
1600
- if ('Keep existing' === action) continue;
1601
- if ('Use another name' === action) target = await interaction_input({
1602
- key: `scriptNames.${name}`,
1603
- message: "New script name:",
1604
- validate: (value)=>!/^[a-zA-Z0-9:_-]+$/.test(value) || Object.hasOwn(scripts, value) || Object.hasOwn(additions, value) ? "Enter an unused script name (letters, numbers, :, _, -)." : true
1605
- });
1606
- }
1607
- scripts[target] = command;
1608
- selected[name] = target;
1609
- }
1610
- if (JSON.stringify(manifest.scripts) !== JSON.stringify(scripts)) {
1611
- manifest.scripts = scripts;
1612
- const indent = original.match(/\n([\t ]+)"/)?.[1] ?? ' ';
1613
- file.update(`${JSON.stringify(manifest, null, indent)}\n`);
1614
- }
1615
- return selected;
1616
- };
1617
- const describeScripts = (selected, descriptions)=>Object.entries(descriptions).filter(([name])=>selected[name]).map(([name, description])=>`npm run ${selected[name]} — ${description}`);
1618
1780
  const openapiScriptPath = "scripts/generate-openapi.ts";
1619
1781
  const defaultOpenapiPath = (withNext)=>withNext ? 'public/openapi.json' : 'openapi.json';
1620
1782
  const extractorPackages = [
@@ -2056,40 +2218,12 @@ const addPlaywright = async ()=>{
2056
2218
  })
2057
2219
  ];
2058
2220
  };
2059
- const savedImplementations = (kind, purpose)=>[
2060
- ...new Set(config_file_ConfigFile.Instance.data.backend?.implementations?.[kind]?.[purpose] ?? [])
2061
- ];
2062
- const rememberImplementation = (kind, purpose, label)=>{
2063
- implementationLabelSchema.parse(label);
2064
- const backend = config_file_ConfigFile.backend;
2065
- const choices = {
2066
- ...backend.implementations
2067
- };
2068
- const group = choices[kind] ?? {
2069
- primary: [],
2070
- test: []
2071
- };
2072
- if (group[purpose].includes(label)) return;
2073
- choices[kind] = {
2074
- ...group,
2075
- [purpose]: [
2076
- ...group[purpose],
2077
- label
2078
- ]
2079
- };
2080
- config_file_ConfigFile.update({
2081
- backend: {
2082
- ...backend,
2083
- implementations: choices
2084
- }
2085
- });
2086
- };
2087
- const runtimePackages = [
2221
+ const prisma_runtimePackages = [
2088
2222
  '@prisma/orm-postgres',
2089
2223
  'temporal-polyfill',
2090
2224
  'dotenv'
2091
2225
  ];
2092
- const developmentPackages = [
2226
+ const prisma_developmentPackages = [
2093
2227
  'prisma',
2094
2228
  '@prisma/cli-engine'
2095
2229
  ];
@@ -2148,7 +2282,7 @@ export const wirePrismaInfrastructureService = wireClass(
2148
2282
  []
2149
2283
  );
2150
2284
  `;
2151
- const stageFile = (filePath, content)=>{
2285
+ const prisma_stageFile = (filePath, content)=>{
2152
2286
  const file = new file_system_File(filePath);
2153
2287
  if (!file.exists || file.data !== content) file.data = content;
2154
2288
  };
@@ -2173,12 +2307,12 @@ const addPrisma = async ()=>{
2173
2307
  default: true
2174
2308
  });
2175
2309
  const selected = await addPackageScripts(manifestFile, prismaScripts(config.project.rootFolder));
2176
- stageFile(external_node_path_default().join(prismaFolder, 'prisma.config.ts'), prismaConfig);
2310
+ prisma_stageFile(external_node_path_default().join(prismaFolder, 'prisma.config.ts'), prismaConfig);
2177
2311
  const contract = new file_system_File(external_node_path_default().join(prismaFolder, 'contract.prisma'));
2178
2312
  if (!contract.exists) contract.data = '// use prisma-8\n\n// Add your application models here before running prisma:emit.\n';
2179
2313
  if (withService) {
2180
- stageFile(external_node_path_default().join(shared, 'infrastructure/services/prisma-infrastructure-service.ts'), prismaService);
2181
- if (config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) stageFile(external_node_path_default().join(shared, 'wiring/infrastructure-services/wire-prisma-infrastructure-service.ts'), prismaWiring);
2314
+ prisma_stageFile(external_node_path_default().join(shared, 'infrastructure/services/prisma-infrastructure-service.ts'), prismaService);
2315
+ if (config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) prisma_stageFile(external_node_path_default().join(shared, 'wiring/infrastructure-services/wire-prisma-infrastructure-service.ts'), prismaWiring);
2182
2316
  }
2183
2317
  for (const kind of [
2184
2318
  'repositories',
@@ -2193,8 +2327,8 @@ const addPrisma = async ()=>{
2193
2327
  };
2194
2328
  const relativeFolder = external_node_path_default().relative(root, prismaFolder).split(external_node_path_default().sep).join('/');
2195
2329
  return [
2196
- ...install(runtimePackages, false),
2197
- ...install(developmentPackages, true),
2330
+ ...install(prisma_runtimePackages, false),
2331
+ ...install(prisma_developmentPackages, true),
2198
2332
  `Add !${relativeFolder} in your linter, to ignore prisma files.`,
2199
2333
  ...describeScripts(selected, {
2200
2334
  'prisma:emit': 'emit contract.json and contract.d.ts from contract.prisma',
@@ -3518,19 +3652,19 @@ export default defineConfig({
3518
3652
  });
3519
3653
  `;
3520
3654
  };
3521
- const testcontainersGlobalSetup = (migrationCommand)=>{
3522
- const migrations = migrationCommand ? `
3523
- // dotenv in the Prisma config does not override an already set variable
3524
- execSync(${JSON.stringify(migrationCommand)}, {
3655
+ const testcontainersGlobalSetup = (migrationCommands = [])=>{
3656
+ const migrations = migrationCommands.length ? `
3657
+ // dotenv in the ORM config does not override an already set variable
3658
+ ${migrationCommands.map((command)=>` execSync(${JSON.stringify(command)}, {
3525
3659
  cwd: project.config.root,
3526
3660
  env: { ...process.env, DATABASE_URL: databaseUrl },
3527
3661
  // On failure the error carries the command's output
3528
3662
  stdio: 'pipe'
3529
3663
  });
3530
- ` : `
3664
+ `).join('')}` : `
3531
3665
  // Apply your migrations to databaseUrl here.
3532
3666
  `;
3533
- return `${migrationCommand ? "import { execSync } from 'node:child_process';\n" : ''}import { GenericContainer, Wait } from 'testcontainers';
3667
+ return `${migrationCommands.length ? "import { execSync } from 'node:child_process';\n" : ''}import { GenericContainer, Wait } from 'testcontainers';
3534
3668
  import type { TestProject } from 'vitest/node';
3535
3669
 
3536
3670
  declare module 'vitest' {
@@ -3676,11 +3810,18 @@ const addTestcontainers = async ()=>{
3676
3810
  ...manifest.devDependencies
3677
3811
  };
3678
3812
  const selected = await addPackageScripts(manifestFile, testcontainersScripts);
3679
- const withPrisma = new file_system_File(external_node_path_default().resolve(root, config.project.rootFolder, 'shared-kernel/infrastructure/prisma/prisma.config.ts')).exists;
3680
- const migrationCommand = withPrisma ? `npx ${prismaScripts(config.project.rootFolder)['prisma:migration:apply'].replace(' --advance-ref db', '')}` : void 0;
3813
+ const presetExists = (relativePath)=>new file_system_File(external_node_path_default().resolve(root, relativePath)).exists;
3814
+ const migrationCommands = [
3815
+ ...presetExists(external_node_path_default().join(config.project.rootFolder, 'shared-kernel/infrastructure/prisma/prisma.config.ts')) ? [
3816
+ `npx ${prismaScripts(config.project.rootFolder)['prisma:migration:apply'].replace(' --advance-ref db', '')}`
3817
+ ] : [],
3818
+ ...presetExists(drizzleConfigPath(config.project.rootFolder)) ? [
3819
+ `npx ${drizzleScripts(config.project.rootFolder)['drizzle:migrate']}`
3820
+ ] : []
3821
+ ];
3681
3822
  const folder = external_node_path_default().join(root, integrationFolder);
3682
3823
  testcontainers_stageFile(external_node_path_default().join(folder, 'vitest.config.ts'), testcontainersVitestConfig(Boolean(dependencies['@domain-first/handlers-next'])));
3683
- testcontainers_stageFile(external_node_path_default().join(folder, 'global-setup.ts'), testcontainersGlobalSetup(migrationCommand));
3824
+ testcontainers_stageFile(external_node_path_default().join(folder, 'global-setup.ts'), testcontainersGlobalSetup(migrationCommands));
3684
3825
  testcontainers_stageFile(external_node_path_default().join(folder, 'setup-env.ts'), testcontainersSetupEnv);
3685
3826
  const example = new file_system_File(external_node_path_default().join(folder, 'database/database.spec.ts'));
3686
3827
  if (!example.exists) example.data = testcontainers_exampleSpec;
@@ -3704,7 +3845,7 @@ const addTestcontainers = async ()=>{
3704
3845
  `npm install --save-dev ${missing.join(' ')}`
3705
3846
  ] : [],
3706
3847
  `Integration specs run against postgres:15 and get its address in DATABASE_URL. Change the image, credentials and connection string in ${integrationFolder}/global-setup.ts, and the variable name in ${integrationFolder}/setup-env.ts.`,
3707
- ...migrationCommand ? [] : [
3848
+ ...migrationCommands.length ? [] : [
3708
3849
  `Apply your migrations in ${integrationFolder}/global-setup.ts.`
3709
3850
  ],
3710
3851
  ...excludedFromUnitTests ? [] : [
@@ -3881,6 +4022,7 @@ const integrationIds = [
3881
4022
  'rest-endpoint-generator',
3882
4023
  'in-memory-db',
3883
4024
  'prisma',
4025
+ 'drizzle',
3884
4026
  'vitest',
3885
4027
  'playwright',
3886
4028
  'testcontainers',
@@ -3917,6 +4059,13 @@ const integrations = [
3917
4059
  run: addPrisma,
3918
4060
  applied: ()=>createdInRoot('shared-kernel/infrastructure/prisma/prisma.config.ts')
3919
4061
  },
4062
+ {
4063
+ id: 'drizzle',
4064
+ name: 'Drizzle (PostgreSQL)',
4065
+ group: 'backend',
4066
+ run: addDrizzle,
4067
+ applied: ()=>created(drizzleConfigPath(config_file_ConfigFile.Instance.data.project.rootFolder))
4068
+ },
3920
4069
  {
3921
4070
  id: 'vitest',
3922
4071
  name: 'Vitest',