@memberjunction/codegen-lib 6.1.0-edge.4 → 6.1.0-edge.6

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 (136) hide show
  1. package/README.md +20 -0
  2. package/dist/Angular/angular-codegen.d.ts +9 -6
  3. package/dist/Angular/angular-codegen.d.ts.map +1 -1
  4. package/dist/Angular/angular-codegen.js +80 -51
  5. package/dist/Angular/angular-codegen.js.map +1 -1
  6. package/dist/Angular/join-grid-related-entity-component.d.ts.map +1 -1
  7. package/dist/Angular/join-grid-related-entity-component.js +5 -2
  8. package/dist/Angular/join-grid-related-entity-component.js.map +1 -1
  9. package/dist/Angular/related-entity-components.d.ts +11 -0
  10. package/dist/Angular/related-entity-components.d.ts.map +1 -1
  11. package/dist/Angular/related-entity-components.js +23 -0
  12. package/dist/Angular/related-entity-components.js.map +1 -1
  13. package/dist/Angular/timeline-related-entity-component.d.ts.map +1 -1
  14. package/dist/Angular/timeline-related-entity-component.js +3 -2
  15. package/dist/Angular/timeline-related-entity-component.js.map +1 -1
  16. package/dist/Config/config.d.ts +216 -12
  17. package/dist/Config/config.d.ts.map +1 -1
  18. package/dist/Config/config.js +88 -6
  19. package/dist/Config/config.js.map +1 -1
  20. package/dist/Config/schema-output.d.ts +33 -0
  21. package/dist/Config/schema-output.d.ts.map +1 -0
  22. package/dist/Config/schema-output.js +52 -0
  23. package/dist/Config/schema-output.js.map +1 -0
  24. package/dist/Database/codeGenDatabaseProvider.d.ts +68 -1
  25. package/dist/Database/codeGenDatabaseProvider.d.ts.map +1 -1
  26. package/dist/Database/codeGenDatabaseProvider.js +142 -3
  27. package/dist/Database/codeGenDatabaseProvider.js.map +1 -1
  28. package/dist/Database/dbSchema.js +2 -1
  29. package/dist/Database/dbSchema.js.map +1 -1
  30. package/dist/Database/decision-metadata-format.d.ts +124 -0
  31. package/dist/Database/decision-metadata-format.d.ts.map +1 -0
  32. package/dist/Database/decision-metadata-format.js +279 -0
  33. package/dist/Database/decision-metadata-format.js.map +1 -0
  34. package/dist/Database/decision-metadata-writer.d.ts +48 -0
  35. package/dist/Database/decision-metadata-writer.d.ts.map +1 -0
  36. package/dist/Database/decision-metadata-writer.js +482 -0
  37. package/dist/Database/decision-metadata-writer.js.map +1 -0
  38. package/dist/Database/entity-field-change-tracking.d.ts +53 -0
  39. package/dist/Database/entity-field-change-tracking.d.ts.map +1 -0
  40. package/dist/Database/entity-field-change-tracking.js +120 -0
  41. package/dist/Database/entity-field-change-tracking.js.map +1 -0
  42. package/dist/Database/entity-level-tree-cycles.d.ts.map +1 -1
  43. package/dist/Database/entity-level-tree-cycles.js +3 -2
  44. package/dist/Database/entity-level-tree-cycles.js.map +1 -1
  45. package/dist/Database/exclude-tables.d.ts +26 -0
  46. package/dist/Database/exclude-tables.d.ts.map +1 -0
  47. package/dist/Database/exclude-tables.js +38 -0
  48. package/dist/Database/exclude-tables.js.map +1 -0
  49. package/dist/Database/field-metadata-lock.d.ts +47 -0
  50. package/dist/Database/field-metadata-lock.d.ts.map +1 -0
  51. package/dist/Database/field-metadata-lock.js +159 -0
  52. package/dist/Database/field-metadata-lock.js.map +1 -0
  53. package/dist/Database/manage-metadata.d.ts +142 -42
  54. package/dist/Database/manage-metadata.d.ts.map +1 -1
  55. package/dist/Database/manage-metadata.js +625 -287
  56. package/dist/Database/manage-metadata.js.map +1 -1
  57. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts +2 -2
  58. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts.map +1 -1
  59. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js +90 -41
  60. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js.map +1 -1
  61. package/dist/Database/providers/postgresql/metadataSupportObjects.js +31 -8
  62. package/dist/Database/providers/postgresql/metadataSupportObjects.js.map +1 -1
  63. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts +3 -1
  64. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts.map +1 -1
  65. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js +58 -23
  66. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js.map +1 -1
  67. package/dist/Database/providers/sqlserver/__tests__/BaseViewEmissionGoldenMaster.test.js +15 -2
  68. package/dist/Database/providers/sqlserver/__tests__/BaseViewEmissionGoldenMaster.test.js.map +1 -1
  69. package/dist/Database/providers/sqlserver/__tests__/SQLServerCodeGenProvider.test.js +17 -0
  70. package/dist/Database/providers/sqlserver/__tests__/SQLServerCodeGenProvider.test.js.map +1 -1
  71. package/dist/Database/sql_codegen.d.ts +24 -0
  72. package/dist/Database/sql_codegen.d.ts.map +1 -1
  73. package/dist/Database/sql_codegen.js +108 -29
  74. package/dist/Database/sql_codegen.js.map +1 -1
  75. package/dist/Manifest/GenerateClassRegistrationsManifest.d.ts +22 -0
  76. package/dist/Manifest/GenerateClassRegistrationsManifest.d.ts.map +1 -1
  77. package/dist/Manifest/GenerateClassRegistrationsManifest.js +115 -7
  78. package/dist/Manifest/GenerateClassRegistrationsManifest.js.map +1 -1
  79. package/dist/Misc/action_subclasses_codegen.js +2 -2
  80. package/dist/Misc/action_subclasses_codegen.js.map +1 -1
  81. package/dist/Misc/advanced_generation.d.ts +7 -5
  82. package/dist/Misc/advanced_generation.d.ts.map +1 -1
  83. package/dist/Misc/advanced_generation.js +34 -23
  84. package/dist/Misc/advanced_generation.js.map +1 -1
  85. package/dist/Misc/codegen-reporter.d.ts +5 -0
  86. package/dist/Misc/codegen-reporter.d.ts.map +1 -1
  87. package/dist/Misc/codegen-reporter.js +9 -2
  88. package/dist/Misc/codegen-reporter.js.map +1 -1
  89. package/dist/Misc/emit-stats.d.ts +28 -0
  90. package/dist/Misc/emit-stats.d.ts.map +1 -0
  91. package/dist/Misc/emit-stats.js +43 -0
  92. package/dist/Misc/emit-stats.js.map +1 -0
  93. package/dist/Misc/entity_subclasses_codegen.d.ts +20 -2
  94. package/dist/Misc/entity_subclasses_codegen.d.ts.map +1 -1
  95. package/dist/Misc/entity_subclasses_codegen.js +120 -51
  96. package/dist/Misc/entity_subclasses_codegen.js.map +1 -1
  97. package/dist/Misc/file-write.d.ts +15 -0
  98. package/dist/Misc/file-write.d.ts.map +1 -0
  99. package/dist/Misc/file-write.js +33 -0
  100. package/dist/Misc/file-write.js.map +1 -0
  101. package/dist/Misc/graphql_server_codegen.d.ts +12 -2
  102. package/dist/Misc/graphql_server_codegen.d.ts.map +1 -1
  103. package/dist/Misc/graphql_server_codegen.js +72 -16
  104. package/dist/Misc/graphql_server_codegen.js.map +1 -1
  105. package/dist/Misc/remote_operations_codegen.d.ts.map +1 -1
  106. package/dist/Misc/remote_operations_codegen.js +4 -3
  107. package/dist/Misc/remote_operations_codegen.js.map +1 -1
  108. package/dist/Misc/runCommand.d.ts +5 -0
  109. package/dist/Misc/runCommand.d.ts.map +1 -1
  110. package/dist/Misc/runCommand.js +43 -17
  111. package/dist/Misc/runCommand.js.map +1 -1
  112. package/dist/Misc/schema-emit.d.ts +123 -0
  113. package/dist/Misc/schema-emit.d.ts.map +1 -0
  114. package/dist/Misc/schema-emit.js +221 -0
  115. package/dist/Misc/schema-emit.js.map +1 -0
  116. package/dist/Misc/sql_logging.d.ts +63 -8
  117. package/dist/Misc/sql_logging.d.ts.map +1 -1
  118. package/dist/Misc/sql_logging.js +169 -42
  119. package/dist/Misc/sql_logging.js.map +1 -1
  120. package/dist/Misc/util.d.ts +12 -0
  121. package/dist/Misc/util.d.ts.map +1 -1
  122. package/dist/Misc/util.js +71 -8
  123. package/dist/Misc/util.js.map +1 -1
  124. package/dist/index.d.ts +8 -0
  125. package/dist/index.d.ts.map +1 -1
  126. package/dist/index.js +8 -0
  127. package/dist/index.js.map +1 -1
  128. package/dist/plugins/index.d.ts +3 -0
  129. package/dist/plugins/index.d.ts.map +1 -1
  130. package/dist/plugins/index.js +28 -1
  131. package/dist/plugins/index.js.map +1 -1
  132. package/dist/runCodeGen.d.ts +20 -2
  133. package/dist/runCodeGen.d.ts.map +1 -1
  134. package/dist/runCodeGen.js +186 -33
  135. package/dist/runCodeGen.js.map +1 -1
  136. package/package.json +29 -29
@@ -3,6 +3,25 @@ import { spawn } from 'child_process';
3
3
  import { logError, logStatus } from './status_logging.js';
4
4
  import path from 'path';
5
5
  import treeKill from 'tree-kill';
6
+ const FAILURE_OUTPUT_TAIL_LINES = 40;
7
+ /**
8
+ * Combine the exit-code message with a tail of captured stdout/stderr so AFTER
9
+ * failures show the actual tsc/pnpm diagnostic instead of just "exited with code N".
10
+ */
11
+ export function formatCommandFailureDetail(result, tailLines = FAILURE_OUTPUT_TAIL_LINES) {
12
+ const parts = [];
13
+ const errorText = (result.error || '').trim();
14
+ if (errorText) {
15
+ parts.push(errorText);
16
+ }
17
+ const output = (result.output || '').trim();
18
+ if (output) {
19
+ const lines = output.split(/\r?\n/);
20
+ const kept = lines.length > tailLines ? ['…', ...lines.slice(-tailLines)] : lines;
21
+ parts.push(kept.join('\n'));
22
+ }
23
+ return parts.join('\n');
24
+ }
6
25
  /**
7
26
  * Base class that handles the process of running commands which can be done executed from any other area of the system, typically done by the main runMemberJunctionCodeGen process
8
27
  */
@@ -37,7 +56,6 @@ export class RunCommandsBase {
37
56
  try {
38
57
  let output = '';
39
58
  let startTime = new Date();
40
- let bErrors = false;
41
59
  const commandName = command.command;
42
60
  const absPath = path.resolve(currentWorkingDirectory, command.workingDirectory);
43
61
  logStatus(`STARTING COMMAND: "${command.command}" in location "${absPath}" with args "${command.args.join(' ')}"`);
@@ -57,13 +75,10 @@ export class RunCommandsBase {
57
75
  output += data.toString();
58
76
  });
59
77
  cp.stderr?.on('data', (data) => {
60
- const elapsedTime = new Date().getTime() - startTime.getTime();
61
- const message = data.toString();
62
- output += message;
63
- if (message.toUpperCase().indexOf('ERROR') >= 0) {
64
- console.error(`COMMAND: "${command.command}" FAILED: ${elapsedTime / 1000} seconds`);
65
- bErrors = true;
66
- }
78
+ // tsc / npm / pnpm write the word "error" to stderr on successful
79
+ // builds (TS diagnostics that were not emitted, deprecation banners,
80
+ // progress). Exit code is the only honest success signal.
81
+ output += data.toString();
67
82
  });
68
83
  cp.on('error', (error) => {
69
84
  const elapsedTime = new Date().getTime() - startTime.getTime();
@@ -73,17 +88,28 @@ export class RunCommandsBase {
73
88
  reject(error);
74
89
  });
75
90
  cp.on('close', (code) => {
91
+ const elapsedTime = new Date().getTime() - startTime.getTime();
76
92
  if (code === 0) {
77
- const elapsedTime = new Date().getTime() - startTime.getTime();
78
93
  logStatus(`COMMAND: "${command.command}" COMPLETED SUCCESSFULLY: ${elapsedTime / 1000} seconds`);
79
- resolve({ output: output,
94
+ resolve({
95
+ output,
80
96
  error: null,
81
- success: !bErrors,
82
- elapsedTime: elapsedTime });
83
- }
84
- else {
85
- reject(new Error(`Process exited with code ${code}`));
97
+ success: true,
98
+ elapsedTime,
99
+ });
100
+ return;
86
101
  }
102
+ // Resolve (do not reject) so callers keep stdout/stderr. The previous
103
+ // reject-on-nonzero path dropped the captured output and left AFTER
104
+ // failures looking like a bare "Process exited with code N".
105
+ const message = `Process exited with code ${code}`;
106
+ console.error(`COMMAND: "${command.command}" FAILED: ${elapsedTime / 1000} seconds (${message})`);
107
+ resolve({
108
+ output,
109
+ error: message,
110
+ success: false,
111
+ elapsedTime,
112
+ });
87
113
  });
88
114
  });
89
115
  if (command.timeout && command.timeout > 0) {
@@ -93,13 +119,13 @@ export class RunCommandsBase {
93
119
  const elapsedTime = new Date().getTime() - startTime.getTime();
94
120
  if (!cp.killed) {
95
121
  treeKill(cp.pid);
96
- console.error(`COMMAND: "${command.command}" COMPLETED ${bErrors ? ' - FAILED' : ' - SUCCESS'} IN ${elapsedTime / 1000} seconds`);
122
+ console.error(`COMMAND: "${command.command}" TIMED OUT after ${elapsedTime / 1000} seconds`);
97
123
  output += `Process killed after ${timeout} ms`;
98
124
  }
99
125
  resolve({
100
126
  output: output,
101
127
  error: null,
102
- success: !bErrors,
128
+ success: false,
103
129
  elapsedTime: elapsedTime,
104
130
  });
105
131
  }, timeout);
@@ -1 +1 @@
1
- {"version":3,"file":"runCommand.js","sourceRoot":"","sources":["../../src/Misc/runCommand.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AACxE,OAAO,EAAE,KAAK,EAAgB,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,QAAQ,MAAM,WAAW,CAAC;AASjC;;GAEG;AACH,MAAM,OAAO,eAAe;IACnB,KAAK,CAAC,WAAW,CAAC,QAAuB;QAC9C,IAAI,CAAC;YACH,MAAM,OAAO,GAA6B,EAAE,CAAC;YAE7C,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;gBAC/B,IAAI,CAAC;oBACH,+EAA+E;oBAC/E,OAAO,CAAC,IAAI,CAAC,MAAM,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC;gBAC/C,CAAC;gBACD,OAAO,CAAC,EAAE,CAAC;oBACT,yEAAyE;oBACzE,0EAA0E;oBAC1E,2EAA2E;oBAC3E,4DAA4D;oBAC5D,MAAM,OAAO,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;oBAC3D,QAAQ,CAAC,OAAO,CAAC,CAAC;oBAClB,OAAO,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,CAAC,EAAE,CAAC,CAAC;gBAC/E,CAAC;YACH,CAAC;YAED,OAAO,OAAO,CAAA;QAChB,CAAC;QACD,OAAO,CAAC,EAAE,CAAC;YACT,QAAQ,CAAC,CAAW,CAAC,CAAA;YACrB,MAAM,CAAC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ema with 2,000 tables. It is
5
+ * two-to-three dozen schemas of 100–150 tables each. Entity identity stays the
6
+ * entity (names, FKs, metadata rows). Everything that can be incremental —
7
+ * emit, dirty regen, parallelism, output-directory routing, agent context —
8
+ * keys off the schema.
9
+ */
10
+ export type DirtySchemaSet = Set<string> | 'all';
11
+ export interface SchemaEmitOptions {
12
+ /**
13
+ * When true (the default), emit one TypeScript file per schema plus a thin
14
+ * barrel. When false, emit the historical single monolith.
15
+ */
16
+ perSchema?: boolean;
17
+ /**
18
+ * Schemas whose files must be rebuilt. `'all'` rebuilds every schema
19
+ * (used by `--skipdb` file-only runs). A Set rebuilds only those schemas
20
+ * plus any schema whose file is missing. An omitted / empty set with
21
+ * existing files is the fast path: skip the string-build entirely.
22
+ */
23
+ dirtySchemas?: DirtySchemaSet;
24
+ /** Assemble independent schema files in parallel. Defaults to true. */
25
+ parallel?: boolean;
26
+ /** Max schemas to assemble in parallel. Defaults to 8. */
27
+ concurrency?: number;
28
+ /** Skip the disk write when bytes are identical. Defaults to true. */
29
+ writeIfChanged?: boolean;
30
+ }
31
+ export interface SchemaNamed {
32
+ Name: string;
33
+ SchemaName: string;
34
+ }
35
+ /**
36
+ * Case-insensitive schema match. `%` is the only wildcard (SQL `_` is a
37
+ * literal — schema names like `bsd_crm` are common and must not glob).
38
+ */
39
+ /** Case-insensitive schema/entity key. Null/undefined become ''. */
40
+ export declare function schemaKey(name: string | null | undefined): string;
41
+ export declare function schemaNameMatches(pattern: string, schemaName: string | null | undefined): boolean;
42
+ /**
43
+ * Turn a SQL schema name into a safe TypeScript file stem.
44
+ * `__mj` stays `__mj`; `bsd_crm` stays `bsd_crm`; `Sales.Analytics` becomes `Sales_Analytics`.
45
+ */
46
+ export declare function sanitizeSchemaFileName(schemaName: string | null | undefined): string;
47
+ /**
48
+ * Group entities by their raw `SchemaName` (trimmed, original casing of the
49
+ * first occurrence). Order inside each group is the input order.
50
+ */
51
+ export declare function groupEntitiesBySchema<T extends {
52
+ SchemaName: string;
53
+ }>(entities: readonly T[]): Map<string, T[]>;
54
+ /**
55
+ * Map dirty entity names (from `newEntityList` ∪ `modifiedEntityList`) back to
56
+ * the schemas those entities live in. Comparison is case-insensitive.
57
+ */
58
+ /**
59
+ * Resolve which schemas a file-emit pass should rebuild.
60
+ * `--skipdb` and `dirtySchemaOnly === false` rebuild every schema (write-if-changed
61
+ * still keeps mtimes stable). Otherwise only schemas that contain a new/modified
62
+ * entity are dirty — missing files are added later by {@link schemasToEmit}.
63
+ */
64
+ export declare function resolveDirtySchemasForEmit(entities: readonly SchemaNamed[], dirtyEntityNames: Iterable<string>, skipDB: boolean, dirtySchemaOnly: boolean, deletedEntitySchemas?: Iterable<string>): DirtySchemaSet;
65
+ export declare function collectDirtySchemas(entities: readonly SchemaNamed[], dirtyEntityNames: Iterable<string>): Set<string>;
66
+ /**
67
+ * Decide which schema files to rebuild. Missing files are always rebuilt so a
68
+ * fresh clone / first run is complete. When `dirty` is `'all'` every schema is
69
+ * rebuilt (callers still use write-if-changed to keep mtimes stable).
70
+ */
71
+ export declare function schemasToEmit(allSchemas: readonly string[], dirty: DirtySchemaSet | undefined, fileExists: (schemaName: string) => boolean): string[];
72
+ /**
73
+ * Bounded parallel map. Order of results matches `items`. A limit of 1 is serial.
74
+ */
75
+ export declare function mapLimit<T, R>(items: readonly T[], limit: number, mapper: (item: T, index: number) => Promise<R>): Promise<R[]>;
76
+ /**
77
+ * Barrel that re-exports every per-schema file. Uses `.js` specifiers so the
78
+ * file is valid in `"type": "module"` packages (MJCoreEntities, MJServer).
79
+ */
80
+ export declare function buildSchemaBarrel(schemas: readonly string[], relativeDir: string, extraHeader: string): string;
81
+ /**
82
+ * Names of files in a per-schema emit directory that no live schema claims.
83
+ *
84
+ * Kept pure and separate from the deletion so the decision is testable without a
85
+ * filesystem. `fileNames` is a plain directory listing; `schemas` is every schema in the
86
+ * run, not just the dirty subset.
87
+ */
88
+ export declare function selectOrphanedSchemaFiles(fileNames: readonly string[], schemas: readonly string[]): string[];
89
+ /**
90
+ * Delete per-schema files that no live schema claims, returning what was removed.
91
+ *
92
+ * A schema that empties out — its last table dropped — leaves its file on disk. The barrel
93
+ * stops exporting it, which is not enough: `tsc` still compiles it through `include`, the
94
+ * class-registration manifest still globs it into the registry, and the CodeGen-tail guard
95
+ * reads every `.ts` in the directory regardless of what the barrel names. So a deleted
96
+ * entity keeps a live `@RegisterClass` registration and inflates the roster the guard
97
+ * compares. The old monolith could not drift this way; it was rewritten in full every run.
98
+ *
99
+ * Safe under dirty-schema regen: `schemas` is the full set for the run, so a schema that
100
+ * simply was not dirty this time is still live and is never pruned.
101
+ */
102
+ export declare function pruneOrphanedSchemaFiles(directory: string, schemas: readonly string[]): string[];
103
+ /**
104
+ * Fill in a partial {@link SchemaEmitOptions} from config defaults.
105
+ *
106
+ * Shared by both generators so the defaults cannot drift between entity subclasses and
107
+ * GraphQL resolvers — they must agree, or one emits per-schema while the other emits a
108
+ * monolith and the two rosters stop lining up.
109
+ *
110
+ * `parallel` / `concurrency` are resolved for every caller even though only the entity
111
+ * generator uses them: its per-schema assembly is async (each file awaits its entities),
112
+ * while GraphQL assembly is synchronous, so there is nothing to overlap there.
113
+ */
114
+ export declare function resolveSchemaEmitOptions(options: SchemaEmitOptions | undefined, defaults: SchemaEmitOptions | undefined): Required<SchemaEmitOptions>;
115
+ /**
116
+ * Write one emitted file, honouring the write-if-changed setting.
117
+ *
118
+ * Shared for the same reason as {@link resolveSchemaEmitOptions}: both generators must treat
119
+ * an unchanged file identically, or one leaves mtimes alone while the other churns them and
120
+ * downstream incremental builds see phantom work.
121
+ */
122
+ export declare function emitSchemaFile(filePath: string, content: string, useWriteIfChanged: boolean): void;
123
+ //# sourceMappingURL=schema-emit.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema-emit.d.ts","sourceRoot":"","sources":["../../src/Misc/schema-emit.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAQH,MAAM,MAAM,cAAc,GAAG,GAAG,CAAC,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+1,221 @@
1
+ /**
2
+ * Schema is the incremental unit for CodeGen file emit.
3
+ *
4
+ * A 2,000-entity database is almost never one schema with 2,000 tables. It is
5
+ * two-to-three dozen schemas of 100–150 tables each. Entity identity stays the
6
+ * entity (names, FKs, metadata rows). Everything that can be incremental —
7
+ * emit, dirty regen, parallelism, output-directory routing, agent context —
8
+ * keys off the schema.
9
+ */
10
+ import fs from 'fs';
11
+ import path from 'path';
12
+ import { ordinalCompare } from '@memberjunction/global';
13
+ import { writeFileIfChanged } from './file-write.js';
14
+ /**
15
+ * Case-insensitive schema match. `%` is the only wildcard (SQL `_` is a
16
+ * literal — schema names like `bsd_crm` are common and must not glob).
17
+ */
18
+ /** Case-insensitive schema/entity key. Null/undefined become ''. */
19
+ export function schemaKey(name) {
20
+ return (name ?? '').trim().toLowerCase();
21
+ }
22
+ export function schemaNameMatches(pattern, schemaName) {
23
+ const p = schemaKey(pattern);
24
+ const s = schemaKey(schemaName);
25
+ if (!p.includes('%')) {
26
+ return p === s;
27
+ }
28
+ const escaped = p.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/%/g, '.*');
29
+ return new RegExp(`^${escaped}$`).test(s);
30
+ }
31
+ /**
32
+ * Turn a SQL schema name into a safe TypeScript file stem.
33
+ * `__mj` stays `__mj`; `bsd_crm` stays `bsd_crm`; `Sales.Analytics` becomes `Sales_Analytics`.
34
+ */
35
+ export function sanitizeSchemaFileName(schemaName) {
36
+ // Keep leading underscores — `__mj` is a real schema name and a valid file stem.
37
+ const cleaned = (schemaName ?? '').trim().replace(/[^A-Za-z0-9_]+/g, '_').replace(/_+$/g, '');
38
+ return cleaned.length > 0 ? cleaned : 'schema';
39
+ }
40
+ /**
41
+ * Group entities by their raw `SchemaName` (trimmed, original casing of the
42
+ * first occurrence). Order inside each group is the input order.
43
+ */
44
+ export function groupEntitiesBySchema(entities) {
45
+ const map = new Map();
46
+ for (const entity of entities) {
47
+ const key = (entity.SchemaName ?? '').trim() || 'unknown';
48
+ const list = map.get(key);
49
+ if (list) {
50
+ list.push(entity);
51
+ }
52
+ else {
53
+ map.set(key, [entity]);
54
+ }
55
+ }
56
+ return map;
57
+ }
58
+ /**
59
+ * Map dirty entity names (from `newEntityList` ∪ `modifiedEntityList`) back to
60
+ * the schemas those entities live in. Comparison is case-insensitive.
61
+ */
62
+ /**
63
+ * Resolve which schemas a file-emit pass should rebuild.
64
+ * `--skipdb` and `dirtySchemaOnly === false` rebuild every schema (write-if-changed
65
+ * still keeps mtimes stable). Otherwise only schemas that contain a new/modified
66
+ * entity are dirty — missing files are added later by {@link schemasToEmit}.
67
+ */
68
+ export function resolveDirtySchemasForEmit(entities, dirtyEntityNames, skipDB, dirtySchemaOnly, deletedEntitySchemas = []) {
69
+ if (skipDB || !dirtySchemaOnly) {
70
+ return 'all';
71
+ }
72
+ const schemas = collectDirtySchemas(entities, dirtyEntityNames);
73
+ // Deletion arrives as a schema, not an entity name: by the time this runs the entity is gone
74
+ // from `entities`, so `collectDirtySchemas` could never resolve it. Union it in directly, or
75
+ // the schema is not rebuilt and the dead class survives on disk.
76
+ for (const schema of deletedEntitySchemas) {
77
+ const trimmed = (schema ?? '').trim();
78
+ if (trimmed.length > 0) {
79
+ schemas.add(trimmed);
80
+ }
81
+ }
82
+ return schemas;
83
+ }
84
+ export function collectDirtySchemas(entities, dirtyEntityNames) {
85
+ const dirty = new Set();
86
+ for (const name of dirtyEntityNames) {
87
+ const key = schemaKey(name);
88
+ if (key.length > 0) {
89
+ dirty.add(key);
90
+ }
91
+ }
92
+ const schemas = new Set();
93
+ if (dirty.size === 0) {
94
+ return schemas;
95
+ }
96
+ for (const entity of entities) {
97
+ if (dirty.has(schemaKey(entity.Name))) {
98
+ const schema = (entity.SchemaName ?? '').trim();
99
+ if (schema.length > 0) {
100
+ schemas.add(schema);
101
+ }
102
+ }
103
+ }
104
+ return schemas;
105
+ }
106
+ /**
107
+ * Decide which schema files to rebuild. Missing files are always rebuilt so a
108
+ * fresh clone / first run is complete. When `dirty` is `'all'` every schema is
109
+ * rebuilt (callers still use write-if-changed to keep mtimes stable).
110
+ */
111
+ export function schemasToEmit(allSchemas, dirty, fileExists) {
112
+ if (dirty === 'all' || dirty == null) {
113
+ return [...allSchemas];
114
+ }
115
+ const dirtyLower = new Set([...dirty].map((s) => s.trim().toLowerCase()));
116
+ return allSchemas.filter((schema) => {
117
+ if (!fileExists(schema)) {
118
+ return true;
119
+ }
120
+ return dirtyLower.has(schema.trim().toLowerCase());
121
+ });
122
+ }
123
+ /**
124
+ * Bounded parallel map. Order of results matches `items`. A limit of 1 is serial.
125
+ */
126
+ export async function mapLimit(items, limit, mapper) {
127
+ const concurrency = Math.max(1, Math.floor(limit));
128
+ const results = new Array(items.length);
129
+ let next = 0;
130
+ const workers = Array.from({ length: Math.min(concurrency, items.length) }, async () => {
131
+ while (next < items.length) {
132
+ const index = next;
133
+ next += 1;
134
+ results[index] = await mapper(items[index], index);
135
+ }
136
+ });
137
+ await Promise.all(workers);
138
+ return results;
139
+ }
140
+ /**
141
+ * Barrel that re-exports every per-schema file. Uses `.js` specifiers so the
142
+ * file is valid in `"type": "module"` packages (MJCoreEntities, MJServer).
143
+ */
144
+ export function buildSchemaBarrel(schemas, relativeDir, extraHeader) {
145
+ const dir = relativeDir.replace(/\\/g, '/').replace(/\/+$/, '');
146
+ const exports = [...schemas]
147
+ .sort((a, b) => ordinalCompare(a, b))
148
+ .map((schema) => `export * from './${dir}/${sanitizeSchemaFileName(schema)}.js';`)
149
+ .join('\n');
150
+ return `${extraHeader}${exports}\n`;
151
+ }
152
+ /**
153
+ * Names of files in a per-schema emit directory that no live schema claims.
154
+ *
155
+ * Kept pure and separate from the deletion so the decision is testable without a
156
+ * filesystem. `fileNames` is a plain directory listing; `schemas` is every schema in the
157
+ * run, not just the dirty subset.
158
+ */
159
+ export function selectOrphanedSchemaFiles(fileNames, schemas) {
160
+ const live = new Set(schemas.map((schema) => `${sanitizeSchemaFileName(schema)}.ts`));
161
+ return fileNames.filter((name) => name.endsWith('.ts') && !live.has(name)).sort();
162
+ }
163
+ /**
164
+ * Delete per-schema files that no live schema claims, returning what was removed.
165
+ *
166
+ * A schema that empties out — its last table dropped — leaves its file on disk. The barrel
167
+ * stops exporting it, which is not enough: `tsc` still compiles it through `include`, the
168
+ * class-registration manifest still globs it into the registry, and the CodeGen-tail guard
169
+ * reads every `.ts` in the directory regardless of what the barrel names. So a deleted
170
+ * entity keeps a live `@RegisterClass` registration and inflates the roster the guard
171
+ * compares. The old monolith could not drift this way; it was rewritten in full every run.
172
+ *
173
+ * Safe under dirty-schema regen: `schemas` is the full set for the run, so a schema that
174
+ * simply was not dirty this time is still live and is never pruned.
175
+ */
176
+ export function pruneOrphanedSchemaFiles(directory, schemas) {
177
+ if (!fs.existsSync(directory)) {
178
+ return [];
179
+ }
180
+ const orphans = selectOrphanedSchemaFiles(fs.readdirSync(directory), schemas);
181
+ for (const name of orphans) {
182
+ fs.unlinkSync(path.join(directory, name));
183
+ }
184
+ return orphans;
185
+ }
186
+ /**
187
+ * Fill in a partial {@link SchemaEmitOptions} from config defaults.
188
+ *
189
+ * Shared by both generators so the defaults cannot drift between entity subclasses and
190
+ * GraphQL resolvers — they must agree, or one emits per-schema while the other emits a
191
+ * monolith and the two rosters stop lining up.
192
+ *
193
+ * `parallel` / `concurrency` are resolved for every caller even though only the entity
194
+ * generator uses them: its per-schema assembly is async (each file awaits its entities),
195
+ * while GraphQL assembly is synchronous, so there is nothing to overlap there.
196
+ */
197
+ export function resolveSchemaEmitOptions(options, defaults) {
198
+ return {
199
+ perSchema: options?.perSchema ?? defaults?.perSchema ?? true,
200
+ dirtySchemas: options?.dirtySchemas ?? 'all',
201
+ parallel: options?.parallel ?? defaults?.parallel ?? true,
202
+ concurrency: options?.concurrency ?? defaults?.concurrency ?? 8,
203
+ writeIfChanged: options?.writeIfChanged ?? defaults?.writeIfChanged ?? true,
204
+ };
205
+ }
206
+ /**
207
+ * Write one emitted file, honouring the write-if-changed setting.
208
+ *
209
+ * Shared for the same reason as {@link resolveSchemaEmitOptions}: both generators must treat
210
+ * an unchanged file identically, or one leaves mtimes alone while the other churns them and
211
+ * downstream incremental builds see phantom work.
212
+ */
213
+ export function emitSchemaFile(filePath, content, useWriteIfChanged) {
214
+ if (useWriteIfChanged) {
215
+ writeFileIfChanged(filePath, content);
216
+ return;
217
+ }
218
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
219
+ fs.writeFileSync(filePath, content);
220
+ }
221
+ //# sourceMappingURL=schema-emit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema-emit.js","sourceRoot":"","sources":["../../src/Misc/schema-emit.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAExD,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AA8BlD;;;GAGG;AACH,oEAAoE;AACpE,MAAM,UAAU,SAAS,CAAC,IAA+B;IACvD,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;AAC3C,CAAC;AAED,MAAM,UAAU,iBAAiB,CAAC,OAAe,EAAE,UAAqC;IACtF,MAAM,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;IAC7B,MAAM,CAAC,GAAG,SAAS,CAAC,UAAU,CAAC,CAAC;IAChC,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QACrB,OAAO,CAAC,KAAK,CAAC,CAAC;IACjB,CAAC;IACD,MAAM,OAAO,GAAG,CAAC,CAAC,OAAO,CAAC,mBAAmB,EAAE,MAAM,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAC3E,OAAO,IAAI,MAAM,CAAC,IAAI,OAAO,GAAG,CAAC,CAAC,IAAI,CAAC,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1,39 @@
1
1
  import { CodeGenConnection } from '../Database/codeGenDatabaseProvider.js';
2
+ /**
3
+ * True when `folderPath` is the CodeGenLib / MJ-host default (`./migrations/v5` etc.),
4
+ * not an Open App `migrations/codegen` tree.
5
+ */
6
+ export declare function isMjDefaultSqlOutputPath(folderPath: string): boolean;
7
+ export type ResolveSQLOutputFolderArgs = {
8
+ cwd: string;
9
+ configuredFolderPath?: string;
10
+ includeSchemas?: string[];
11
+ coreSchema: string;
12
+ /** CLI `--sql-output-dir`. Wins over config when set. */
13
+ sqlOutputDirFlag?: string;
14
+ hasMjAppJson: boolean;
15
+ isMjMonorepo: boolean;
16
+ };
17
+ /**
18
+ * Where CodeGen writes `CodeGen_Run_*.sql` (EntityField INSERTs and other metadata SQL).
19
+ *
20
+ * Open App (`mj-app.json` in cwd): always `{cwd}/migrations/codegen` unless
21
+ * `--sql-output-dir` or an explicit non-MJ `SQLOutput.folderPath` is set.
22
+ * Never fall back to `MJ/migrations/v*` — that silently dropped Open App
23
+ * EntityField SQL into the host tree.
24
+ *
25
+ * MJ monorepo cwd + `includeSchemas` listing a non-core schema: throw. Run
26
+ * CodeGen from the app directory.
27
+ */
28
+ export declare function resolveSQLOutputFolder(args: ResolveSQLOutputFolderArgs): string;
2
29
  /**
3
30
  * Utility class for logging SQL to a run file that can be fresh for each run or appended to depending on the settings in the configuration
4
31
  */
5
32
  export declare class SQLLogging {
6
33
  private static _SQLLoggingFilePath;
7
34
  private static _OmitRecurringScriptsFromLog;
35
+ /** CLI `--sql-output-dir`. Set before {@link initSQLLogging}. */
36
+ static sqlOutputDirFlag: string | undefined;
8
37
  static get SQLLoggingFilePath(): string;
9
38
  static get OmitRecurringScriptsFromLog(): boolean;
10
39
  /**
@@ -33,17 +62,35 @@ export declare class SQLLogging {
33
62
  */
34
63
  static redirectToPGMigrations(folderPath: string): string;
35
64
  static initSQLLogging(): void;
36
- static finishSQLLogging(): void;
37
- protected static createFileName(): string;
38
65
  /**
39
- * Adds the provided SQL to the log file for the run
40
- * @param contents - the executable SQL to log
41
- * @param description - a description of what is being logged that will be emitted and wrapped in comments
42
- * @param isRecurringScript - if set to true tells the logger that the provided SQL represents a recurring script meaning it is something that is executed, generally, for all CodeGen runs. In these cases, the Config settings can result in omitting these recurring scripts from being logged because the configuration environment may have those recurring scripts already set to run after all run-specific migrations get run.
43
- * @returns
66
+ * The batch separator for the active platform: `GO` on SQL Server, none on PostgreSQL. Used as the
67
+ * default for callers that do not pass the provider's separator, so a PostgreSQL capture can never
68
+ * pick up a literal `GO` from a forgotten argument.
69
+ */
70
+ static defaultBatchSeparator(): string;
71
+ /** Test hook — SQLLogging is a process-wide singleton. */
72
+ static resetForTests(): void;
73
+ /** Test hook — sets the active capture file path for testing. */
74
+ static setFilePathForTesting(filePath: string): void;
75
+ /**
76
+ * Test hook — turns SQL capture off for the process: disables `SQLOutput` so
77
+ * {@link LogSQLAndExecute} does not refuse to run against a stub connection with no CodeGen_Run
78
+ * file open, and closes any capture file already open so nothing is written meanwhile. Returns a
79
+ * function that restores both; call it from `afterAll`.
44
80
  */
81
+ static suppressOutputForTests(): () => void;
82
+ static finishSQLLogging(): void;
83
+ protected static createFileName(): string;
45
84
  /**
46
- * Adds the provided SQL to the log file for the run
85
+ * Adds the provided SQL to the log file for the run.
86
+ *
87
+ * Two rules keep the file replayable as a migration. A unit that declares a batch-scoped T-SQL
88
+ * variable always ends its batch: every unit is executed as its own query, so no later unit can
89
+ * depend on the variable, but two such units concatenated into one migration batch fail replay
90
+ * with "The variable name '@x' has already been declared" (see {@link declaresBatchScopedVariable}).
91
+ * And a unit that already ends in `GO` never receives a second separator. An empty
92
+ * `batchSeparator` (PostgreSQL) means none. Callers should still pass `includeBatchSeparator`
93
+ * explicitly: the scan does not see a declaration hidden inside a string or a mid-line statement.
47
94
  * @param contents - the executable SQL to log
48
95
  * @param description - a description of what is being logged that will be emitted and wrapped in comments
49
96
  * @param isRecurringScript - if set to true tells the logger that the provided SQL represents a recurring script meaning it is something that is executed, generally, for all CodeGen runs. In these cases, the Config settings can result in omitting these recurring scripts from being logged because the configuration environment may have those recurring scripts already set to run after all run-specific migrations get run.
@@ -63,6 +110,14 @@ export declare class SQLLogging {
63
110
  * @returns - The result of the query execution.
64
111
  */
65
112
  static LogSQLAndExecute(ds: CodeGenConnection, query: string, description?: string, isRecurringScript?: boolean, includeBatchSeparator?: boolean, batchSeparator?: string): Promise<any>;
113
+ /**
114
+ * True when the SQL text declares a batch-scoped T-SQL local variable: a `DECLARE @name ...` at the
115
+ * start of any line with no routine header (`CREATE|ALTER [OR ALTER] PROCEDURE|FUNCTION|TRIGGER`) before
116
+ * it. T-SQL variables are scoped to the batch wherever they are declared — after `SET NOCOUNT ON`,
117
+ * inside `IF ... BEGIN ... END` — so the match is not limited to the first statement. A declaration
118
+ * inside a routine body is routine-scoped and cannot collide across units, so it does not count.
119
+ */
120
+ static declaresBatchScopedVariable(sql: string): boolean;
66
121
  protected static getFileLength(filePath: string): number;
67
122
  protected static convertSQLLogToFlywaySchema(): void;
68
123
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"sql_logging.d.ts","sourceRoot":"","sources":["../../src/Misc/sql_logging.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AAMxE;;GAEG;AACH,qBAAa,UAAU;IACnB,OAAO,CAAC,MAAM,CAAC,mBAAmB,CAAc;IAChD,OAAO,CAAC,MAAM,CAAC,4BAA4B,CAAkB;IAE7D,WAAkB,kBAAkB,IAAI,MAAM,CAE7C;IACD,WAAkB,2BAA2B,IAAI,OAAO,CAEvD;IAED;;;;;;;;;;;;;;;;;;;;;;;OAuBG;WACW,sBAAsB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM;WAwBlD,cAAc;WA2Cb,gBAAgB;IAa9B,SAAS,CAAC,MAAM,CAAC,cAAc,IAAI,MAAM;IAe1C;;;;;;OAMG;IACH;;;;;;;;OAQG;WACiB,kBAAkB,CAAC,QAAQ,EAAE,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