@memberjunction/installer 0.0.1 → 5.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/dist/InstallerEngine.d.ts +182 -0
  2. package/dist/InstallerEngine.d.ts.map +1 -0
  3. package/dist/InstallerEngine.js +571 -0
  4. package/dist/InstallerEngine.js.map +1 -0
  5. package/dist/adapters/FileSystemAdapter.d.ts +197 -0
  6. package/dist/adapters/FileSystemAdapter.d.ts.map +1 -0
  7. package/dist/adapters/FileSystemAdapter.js +355 -0
  8. package/dist/adapters/FileSystemAdapter.js.map +1 -0
  9. package/dist/adapters/GitHubReleaseProvider.d.ts +197 -0
  10. package/dist/adapters/GitHubReleaseProvider.d.ts.map +1 -0
  11. package/dist/adapters/GitHubReleaseProvider.js +348 -0
  12. package/dist/adapters/GitHubReleaseProvider.js.map +1 -0
  13. package/dist/adapters/ProcessRunner.d.ts +174 -0
  14. package/dist/adapters/ProcessRunner.d.ts.map +1 -0
  15. package/dist/adapters/ProcessRunner.js +264 -0
  16. package/dist/adapters/ProcessRunner.js.map +1 -0
  17. package/dist/adapters/SqlServerAdapter.d.ts +78 -0
  18. package/dist/adapters/SqlServerAdapter.d.ts.map +1 -0
  19. package/dist/adapters/SqlServerAdapter.js +120 -0
  20. package/dist/adapters/SqlServerAdapter.js.map +1 -0
  21. package/dist/errors/InstallerError.d.ts +92 -0
  22. package/dist/errors/InstallerError.d.ts.map +1 -0
  23. package/dist/errors/InstallerError.js +66 -0
  24. package/dist/errors/InstallerError.js.map +1 -0
  25. package/dist/events/InstallerEvents.d.ts +255 -0
  26. package/dist/events/InstallerEvents.d.ts.map +1 -0
  27. package/dist/events/InstallerEvents.js +96 -0
  28. package/dist/events/InstallerEvents.js.map +1 -0
  29. package/dist/index.d.ts +59 -0
  30. package/dist/index.d.ts.map +1 -0
  31. package/dist/index.js +63 -0
  32. package/dist/index.js.map +1 -0
  33. package/dist/models/Diagnostics.d.ts +121 -0
  34. package/dist/models/Diagnostics.d.ts.map +1 -0
  35. package/dist/models/Diagnostics.js +75 -0
  36. package/dist/models/Diagnostics.js.map +1 -0
  37. package/dist/models/InstallConfig.d.ts +139 -0
  38. package/dist/models/InstallConfig.d.ts.map +1 -0
  39. package/dist/models/InstallConfig.js +207 -0
  40. package/dist/models/InstallConfig.js.map +1 -0
  41. package/dist/models/InstallPlan.d.ts +189 -0
  42. package/dist/models/InstallPlan.d.ts.map +1 -0
  43. package/dist/models/InstallPlan.js +117 -0
  44. package/dist/models/InstallPlan.js.map +1 -0
  45. package/dist/models/InstallState.d.ts +173 -0
  46. package/dist/models/InstallState.d.ts.map +1 -0
  47. package/dist/models/InstallState.js +203 -0
  48. package/dist/models/InstallState.js.map +1 -0
  49. package/dist/models/VersionInfo.d.ts +53 -0
  50. package/dist/models/VersionInfo.d.ts.map +1 -0
  51. package/dist/models/VersionInfo.js +2 -0
  52. package/dist/models/VersionInfo.js.map +1 -0
  53. package/dist/phases/CodeGenPhase.d.ts +364 -0
  54. package/dist/phases/CodeGenPhase.d.ts.map +1 -0
  55. package/dist/phases/CodeGenPhase.js +1086 -0
  56. package/dist/phases/CodeGenPhase.js.map +1 -0
  57. package/dist/phases/ConfigurePhase.d.ts +86 -0
  58. package/dist/phases/ConfigurePhase.d.ts.map +1 -0
  59. package/dist/phases/ConfigurePhase.js +439 -0
  60. package/dist/phases/ConfigurePhase.js.map +1 -0
  61. package/dist/phases/DatabaseProvisionPhase.d.ts +82 -0
  62. package/dist/phases/DatabaseProvisionPhase.d.ts.map +1 -0
  63. package/dist/phases/DatabaseProvisionPhase.js +284 -0
  64. package/dist/phases/DatabaseProvisionPhase.js.map +1 -0
  65. package/dist/phases/DependencyPhase.d.ts +88 -0
  66. package/dist/phases/DependencyPhase.d.ts.map +1 -0
  67. package/dist/phases/DependencyPhase.js +237 -0
  68. package/dist/phases/DependencyPhase.js.map +1 -0
  69. package/dist/phases/MigratePhase.d.ts +70 -0
  70. package/dist/phases/MigratePhase.d.ts.map +1 -0
  71. package/dist/phases/MigratePhase.js +96 -0
  72. package/dist/phases/MigratePhase.js.map +1 -0
  73. package/dist/phases/PlatformCompatPhase.d.ts +193 -0
  74. package/dist/phases/PlatformCompatPhase.d.ts.map +1 -0
  75. package/dist/phases/PlatformCompatPhase.js +587 -0
  76. package/dist/phases/PlatformCompatPhase.js.map +1 -0
  77. package/dist/phases/PreflightPhase.d.ts +119 -0
  78. package/dist/phases/PreflightPhase.d.ts.map +1 -0
  79. package/dist/phases/PreflightPhase.js +394 -0
  80. package/dist/phases/PreflightPhase.js.map +1 -0
  81. package/dist/phases/ScaffoldPhase.d.ts +99 -0
  82. package/dist/phases/ScaffoldPhase.d.ts.map +1 -0
  83. package/dist/phases/ScaffoldPhase.js +235 -0
  84. package/dist/phases/ScaffoldPhase.js.map +1 -0
  85. package/dist/phases/SmokeTestPhase.d.ts +111 -0
  86. package/dist/phases/SmokeTestPhase.d.ts.map +1 -0
  87. package/dist/phases/SmokeTestPhase.js +426 -0
  88. package/dist/phases/SmokeTestPhase.js.map +1 -0
  89. package/package.json +26 -7
  90. package/README.md +0 -45
@@ -0,0 +1,1086 @@
1
+ /**
2
+ * Phase H — CodeGen + Validation
3
+ *
4
+ * Runs `mj codegen` to generate TypeScript entity classes, action classes,
5
+ * SQL objects, and Angular form components from database schema and metadata.
6
+ * Validates that required artifacts are produced and applies post-codegen
7
+ * fixups to ensure class registration manifests and known-issue patches
8
+ * are current.
9
+ *
10
+ * **Artifact verification** is two-tier:
11
+ * - `mj_generatedentities` in `node_modules/` — **critical** (blocks install if missing).
12
+ * - `packages/GeneratedEntities` — **secondary** (warns if missing, does not block).
13
+ *
14
+ * **Retry strategy**: If codegen fails on the first attempt (common when AFTER
15
+ * commands leave stale `dist/` from a partial build), the phase runs a full
16
+ * `npm run build` to restore consistency, then retries codegen once. Timeouts
17
+ * are not retried (they indicate deeper connectivity or performance issues).
18
+ *
19
+ * **Post-codegen pipeline** (4 steps after successful codegen):
20
+ * 1. Force-rebuild codegen output packages (`.d.ts` exports must reflect new classes).
21
+ * 2. Regenerate class registration manifest `.ts` files via `npm run mj:manifest`.
22
+ * 3. Force-rebuild manifest packages (compile freshly generated `.ts` to `.js`).
23
+ * 4. Apply known-issue source patches and rebuild affected packages.
24
+ *
25
+ * **Fast mode** (`--fast`): Quick-checks manifest files for stale entity names
26
+ * and compares source/dist timestamps. If everything looks current, Steps 1-3
27
+ * are skipped entirely (saving ~2-3 minutes). Step 4 always runs.
28
+ *
29
+ * @module phases/CodeGenPhase
30
+ * @see DependencyPhase — must complete before codegen (packages must be built).
31
+ * @see MigratePhase — must complete before codegen (schema must be current).
32
+ * @see SmokeTestPhase — runs after codegen to verify the generated code works.
33
+ */
34
+ import path from 'node:path';
35
+ import { InstallerError } from '../errors/InstallerError.js';
36
+ import { ProcessRunner } from '../adapters/ProcessRunner.js';
37
+ import { FileSystemAdapter } from '../adapters/FileSystemAdapter.js';
38
+ /**
39
+ * Phase H — Runs MJ CodeGen, verifies artifacts, and applies post-codegen fixups.
40
+ *
41
+ * This is the most complex phase in the install pipeline. After code generation
42
+ * succeeds, it runs a 4-step post-codegen pipeline to ensure class registration
43
+ * manifests are current and known source-level issues are patched.
44
+ *
45
+ * @example
46
+ * ```typescript
47
+ * const codeGen = new CodeGenPhase();
48
+ * const result = await codeGen.Run({
49
+ * Dir: '/path/to/install',
50
+ * Emitter: emitter,
51
+ * Fast: false,
52
+ * });
53
+ * if (result.RetryUsed) {
54
+ * console.log('CodeGen needed a rebuild + retry');
55
+ * }
56
+ * ```
57
+ */
58
+ export class CodeGenPhase {
59
+ constructor() {
60
+ this.processRunner = new ProcessRunner();
61
+ this.fileSystem = new FileSystemAdapter();
62
+ }
63
+ /**
64
+ * Execute the codegen phase: run `mj codegen`, verify artifacts, retry if needed,
65
+ * then run the post-codegen pipeline (manifest regen + known-issue patches).
66
+ *
67
+ * @param context - Codegen input with directory, emitter, and fast-mode flag.
68
+ * @returns Codegen result with success status, artifact verification, and retry flag.
69
+ * @throws {InstallerError} With code `CODEGEN_TIMEOUT` if codegen exceeds 10 minutes.
70
+ * @throws {InstallerError} With code `CODEGEN_FAILED` if codegen fails after rebuild + retry.
71
+ */
72
+ async Run(context) {
73
+ const { Emitter: emitter } = context;
74
+ // --- First attempt ---
75
+ const firstResult = await this.attemptCodeGen(context.Dir, emitter);
76
+ if (firstResult.Success) {
77
+ // Codegen succeeded — regenerate class registration manifests and rebuild.
78
+ // The manifests (mj-class-registrations.ts in ServerBootstrap, etc.) are
79
+ // generated by `mj codegen manifest`, not by `mj codegen`. The initial
80
+ // build's `postbuild` may not have run if it was a partial build, so the
81
+ // pre-built manifests from the release could reference stale entity names.
82
+ await this.regenerateManifestsAndRebuild(context.Dir, emitter, context.Fast ?? false);
83
+ return { Success: true, ArtifactsVerified: firstResult.AllArtifactsVerified, RetryUsed: false };
84
+ }
85
+ // --- First attempt failed (codegen crash OR missing critical artifacts) ---
86
+ // Common cause: a previous codegen run's AFTER commands failed, leaving
87
+ // dist/ directories with stale compiled .js that reference generated .ts
88
+ // files which were never compiled. A full rebuild restores consistency.
89
+ emitter.Emit('warn', {
90
+ Type: 'warn',
91
+ Phase: 'codegen',
92
+ Message: `First codegen attempt failed: ${firstResult.FailureReason}. Rebuilding packages before retry...`,
93
+ });
94
+ await this.rebuildPackages(context.Dir, emitter);
95
+ // --- Second attempt (throws on failure — no more retries) ---
96
+ const secondResult = await this.attemptCodeGen(context.Dir, emitter);
97
+ if (secondResult.Success) {
98
+ emitter.Emit('log', {
99
+ Type: 'log',
100
+ Level: 'info',
101
+ Message: 'Code generation completed after rebuild + retry.',
102
+ });
103
+ await this.regenerateManifestsAndRebuild(context.Dir, emitter, context.Fast ?? false);
104
+ return { Success: true, ArtifactsVerified: secondResult.AllArtifactsVerified, RetryUsed: true };
105
+ }
106
+ // Still failing after rebuild + retry
107
+ throw new InstallerError('codegen', 'CODEGEN_FAILED', `Code generation failed after rebuild and retry: ${secondResult.FailureReason}`, 'Run "npm run build" then "mj codegen" manually to see full error output. Verify database connectivity and that migrations have been applied.');
108
+ }
109
+ /**
110
+ * Runs codegen and verifies artifacts. Returns a result object instead of
111
+ * throwing, so the caller can decide whether to retry.
112
+ * Only timeouts throw immediately (not recoverable by rebuild).
113
+ */
114
+ async attemptCodeGen(dir, emitter) {
115
+ emitter.Emit('step:progress', {
116
+ Type: 'step:progress',
117
+ Phase: 'codegen',
118
+ Message: 'Running code generation...',
119
+ });
120
+ const codegenResult = await this.runCodeGen(dir, emitter);
121
+ if (!codegenResult.Success) {
122
+ return { Success: false, AllArtifactsVerified: false, AfterCommandsFailed: false, FailureReason: codegenResult.ErrorSummary };
123
+ }
124
+ // Codegen exited 0 — verify artifacts
125
+ emitter.Emit('step:progress', {
126
+ Type: 'step:progress',
127
+ Phase: 'codegen',
128
+ Message: 'Verifying generated artifacts...',
129
+ });
130
+ const artifacts = await this.verifyArtifacts(dir, emitter);
131
+ if (artifacts.CriticalPassed) {
132
+ emitter.Emit('log', {
133
+ Type: 'log',
134
+ Level: 'info',
135
+ Message: 'Code generation completed and artifacts verified.',
136
+ });
137
+ return {
138
+ Success: true,
139
+ AllArtifactsVerified: artifacts.AllPassed,
140
+ AfterCommandsFailed: codegenResult.AfterCommandsFailed,
141
+ FailureReason: '',
142
+ };
143
+ }
144
+ return { Success: false, AllArtifactsVerified: false, AfterCommandsFailed: codegenResult.AfterCommandsFailed, FailureReason: 'critical artifact mj_generatedentities not found' };
145
+ }
146
+ // ---------------------------------------------------------------------------
147
+ // CodeGen execution
148
+ // ---------------------------------------------------------------------------
149
+ /**
150
+ * Execute `npx mj codegen` and return structured results.
151
+ *
152
+ * Detects AFTER command failures in the codegen output — these indicate that
153
+ * post-generation build steps failed, leaving `dist/` directories with stale
154
+ * compiled `.js` that references generated `.ts` files which were never compiled.
155
+ *
156
+ * @param dir - Repo root directory.
157
+ * @param emitter - Event emitter for progress reporting.
158
+ * @returns Structured result with success flag, AFTER-command failure detection, and error summary.
159
+ * @throws {InstallerError} With code `CODEGEN_TIMEOUT` if the process exceeds 10 minutes.
160
+ */
161
+ async runCodeGen(dir, emitter) {
162
+ const result = await this.processRunner.Run('npx', ['mj', 'codegen'], {
163
+ Cwd: dir,
164
+ TimeoutMs: 600_000, // 10 minutes
165
+ OnStdout: (line) => {
166
+ emitter.Emit('step:progress', {
167
+ Type: 'step:progress',
168
+ Phase: 'codegen',
169
+ Message: line.trim(),
170
+ });
171
+ },
172
+ OnStderr: (line) => {
173
+ emitter.Emit('log', {
174
+ Type: 'log',
175
+ Level: 'verbose',
176
+ Message: `[codegen:stderr] ${line.trim()}`,
177
+ });
178
+ },
179
+ });
180
+ // Timeouts are not recoverable by rebuild — throw immediately
181
+ if (result.TimedOut) {
182
+ throw new InstallerError('codegen', 'CODEGEN_TIMEOUT', 'Code generation timed out after 10 minutes.', 'Run "mj codegen" manually. Check that the database is accessible and migrations are applied.');
183
+ }
184
+ if (result.ExitCode !== 0) {
185
+ const lastLines = this.lastNLines(result.Stderr || result.Stdout, 50);
186
+ return { Success: false, AfterCommandsFailed: false, ErrorSummary: `exit code ${result.ExitCode}: ${lastLines}` };
187
+ }
188
+ // Log AFTER command output if present
189
+ this.saveAfterLog(dir, result.Stdout, result.Stderr, emitter);
190
+ // Detect AFTER command failures: codegen exited 0 but post-generation
191
+ // build steps failed, leaving dist/ directories with stale .js that
192
+ // reference generated .ts files which were never compiled.
193
+ const afterFailed = /COMMAND:.*FAILED/i.test(result.Stderr);
194
+ return { Success: true, AfterCommandsFailed: afterFailed, ErrorSummary: '' };
195
+ }
196
+ /**
197
+ * Save CodeGen AFTER command output to a log file for diagnostics.
198
+ *
199
+ * Non-critical — failures to write the log are silently ignored.
200
+ *
201
+ * @param dir - Repo root directory.
202
+ * @param stdout - Full stdout from the codegen process.
203
+ * @param stderr - Full stderr from the codegen process.
204
+ * @param emitter - Event emitter for verbose logging.
205
+ */
206
+ saveAfterLog(dir, stdout, stderr, emitter) {
207
+ if (!stdout.includes('AFTER') && !stderr.includes('AFTER'))
208
+ return;
209
+ const logDir = path.join(dir, 'logs');
210
+ const logPath = path.join(logDir, 'mj-codegen-after.log');
211
+ this.fileSystem.WriteText(logPath, stdout + '\n' + stderr)
212
+ .then(() => {
213
+ emitter.Emit('log', {
214
+ Type: 'log',
215
+ Level: 'verbose',
216
+ Message: `CodeGen AFTER output saved to ${logPath}`,
217
+ });
218
+ })
219
+ .catch(() => {
220
+ // non-critical
221
+ });
222
+ }
223
+ // ---------------------------------------------------------------------------
224
+ // Artifact verification
225
+ // ---------------------------------------------------------------------------
226
+ /**
227
+ * Verify that codegen produced the expected artifacts.
228
+ *
229
+ * Two-tier check:
230
+ * - **Critical**: `node_modules/mj_generatedentities` must exist (MJAPI can't start without it).
231
+ * - **Secondary**: `packages/GeneratedEntities` is expected but absence is only a warning.
232
+ *
233
+ * @param dir - Repo root directory.
234
+ * @param emitter - Event emitter for diagnostic logging.
235
+ * @returns Object indicating whether critical and all artifacts passed verification.
236
+ */
237
+ async verifyArtifacts(dir, emitter) {
238
+ // Critical: mj_generatedentities must exist in node_modules for the app to run.
239
+ // Secondary: packages/GeneratedEntities is expected but its absence is a warning, not a blocker.
240
+ const criticalPath = path.join(dir, 'node_modules', 'mj_generatedentities');
241
+ const secondaryPath = path.join(dir, 'packages', 'GeneratedEntities');
242
+ const criticalExists = await this.fileSystem.DirectoryExists(criticalPath);
243
+ const secondaryExists = await this.fileSystem.DirectoryExists(secondaryPath);
244
+ emitter.Emit('log', {
245
+ Type: 'log',
246
+ Level: 'verbose',
247
+ Message: `[codegen] mj_generatedentities package: ${criticalExists ? 'found' : 'NOT found'}`,
248
+ });
249
+ emitter.Emit('log', {
250
+ Type: 'log',
251
+ Level: 'verbose',
252
+ Message: `[codegen] packages/GeneratedEntities directory: ${secondaryExists ? 'found' : 'NOT found'}`,
253
+ });
254
+ if (!secondaryExists && criticalExists) {
255
+ emitter.Emit('warn', {
256
+ Type: 'warn',
257
+ Phase: 'codegen',
258
+ Message: 'packages/GeneratedEntities not found. This is non-critical but may indicate an incomplete codegen run.',
259
+ });
260
+ }
261
+ return {
262
+ CriticalPassed: criticalExists,
263
+ AllPassed: criticalExists && secondaryExists,
264
+ };
265
+ }
266
+ // ---------------------------------------------------------------------------
267
+ // Rebuild packages (recovery before retry)
268
+ // ---------------------------------------------------------------------------
269
+ /**
270
+ * Packages that contain generated code managed by CodeGen. Build failures in
271
+ * only these packages are tolerated — codegen will regenerate the stale code.
272
+ */
273
+ static { this.CODEGEN_MANAGED_PACKAGES = [
274
+ 'ng-core-entity-forms',
275
+ 'server-bootstrap-lite',
276
+ 'server-bootstrap',
277
+ 'ng-bootstrap',
278
+ ]; }
279
+ /**
280
+ * Full workspace rebuild to restore consistency before retrying codegen.
281
+ *
282
+ * Runs `npm run build` at the repo root. Tolerates build failures in
283
+ * codegen-managed packages (they contain stale generated code that the
284
+ * retry will regenerate). Non-codegen build failures are hard errors.
285
+ *
286
+ * @param dir - Repo root directory.
287
+ * @param emitter - Event emitter for progress and warning reporting.
288
+ * @throws {InstallerError} With code `CODEGEN_FAILED` on timeout or non-codegen build failures.
289
+ */
290
+ async rebuildPackages(dir, emitter) {
291
+ emitter.Emit('step:progress', {
292
+ Type: 'step:progress',
293
+ Phase: 'codegen',
294
+ Message: 'Rebuilding packages to restore consistent state...',
295
+ });
296
+ const result = await this.processRunner.Run('npm', ['run', 'build'], {
297
+ Cwd: dir,
298
+ TimeoutMs: 1_800_000, // 30 minutes — same as DependencyPhase
299
+ OnStdout: (line) => {
300
+ emitter.Emit('step:progress', {
301
+ Type: 'step:progress',
302
+ Phase: 'codegen',
303
+ Message: line.trim(),
304
+ });
305
+ },
306
+ OnStderr: (line) => {
307
+ emitter.Emit('log', {
308
+ Type: 'log',
309
+ Level: 'verbose',
310
+ Message: `[codegen:rebuild:stderr] ${line.trim()}`,
311
+ });
312
+ },
313
+ });
314
+ if (result.TimedOut) {
315
+ throw new InstallerError('codegen', 'CODEGEN_FAILED', 'Package rebuild timed out after 30 minutes during codegen retry preparation.', 'Run "npm run build" manually at the repo root, then re-run "mj codegen".');
316
+ }
317
+ if (result.ExitCode === 0) {
318
+ emitter.Emit('log', {
319
+ Type: 'log',
320
+ Level: 'info',
321
+ Message: 'Package rebuild completed successfully.',
322
+ });
323
+ return;
324
+ }
325
+ // Build failed — tolerate failures in codegen-managed packages only.
326
+ // These contain stale generated code that codegen will regenerate.
327
+ // Codegen itself only needs server-side packages (not Angular forms).
328
+ const combinedOutput = result.Stdout + '\n' + result.Stderr;
329
+ const failedPackages = this.extractFailedTurboPackages(combinedOutput);
330
+ const onlyCodegenFailures = failedPackages.length > 0
331
+ && failedPackages.every(pkg => CodeGenPhase.CODEGEN_MANAGED_PACKAGES.some(pattern => pkg.includes(pattern)));
332
+ if (onlyCodegenFailures) {
333
+ const failList = failedPackages.join(', ');
334
+ emitter.Emit('warn', {
335
+ Type: 'warn',
336
+ Phase: 'codegen',
337
+ Message: `Rebuild partially succeeded. Failed packages (${failList}) contain stale generated code — codegen will fix them.`,
338
+ });
339
+ return;
340
+ }
341
+ const lastLines = this.lastNLines(result.Stderr || result.Stdout, 50);
342
+ throw new InstallerError('codegen', 'CODEGEN_FAILED', `Package rebuild failed (exit code ${result.ExitCode}):\n${lastLines}`, 'Run "npm run build" manually at the repo root to see full error output, then re-run "mj codegen".');
343
+ }
344
+ // ---------------------------------------------------------------------------
345
+ // Post-codegen manifest regeneration + rebuild
346
+ // ---------------------------------------------------------------------------
347
+ /**
348
+ * Known stale entity import patterns to check for in manifest files.
349
+ * These are entity class names that were renamed with the "MJ" prefix
350
+ * in 5.0.0+ but may still appear in stale pre-built manifests from
351
+ * release zips that were not fully compiled after renaming.
352
+ */
353
+ static { this.STALE_ENTITY_PATTERNS = [
354
+ 'AIActionEntity', // renamed to MJAIActionEntity
355
+ 'AIAgentActionEntity', // renamed to MJAIAgentActionEntity
356
+ 'EntityAIActionEntity', // renamed to MJEntityAIActionEntity
357
+ ]; }
358
+ /**
359
+ * Manifest source files that should be regenerated after codegen.
360
+ * Paths are relative to the repo root.
361
+ */
362
+ static { this.MANIFEST_SOURCE_PATHS = [
363
+ 'packages/ServerBootstrap/src/generated/mj-class-registrations.ts',
364
+ 'packages/ServerBootstrapLite/src/generated/mj-class-registrations.ts',
365
+ 'packages/Angular/Bootstrap/src/generated/mj-class-registrations.ts',
366
+ ]; }
367
+ /**
368
+ * After codegen succeeds, ensure class registration manifests and their
369
+ * compiled output are up-to-date, and apply known source-level fixes.
370
+ *
371
+ * The flow:
372
+ * 1. Force-rebuild codegen output packages so their .d.ts exports reflect
373
+ * the latest generated entity class names.
374
+ * 2. Regenerate manifest .ts files using `npm run mj:manifest` (which reads
375
+ * .d.ts to verify exported classes).
376
+ * 3. Force-rebuild the manifest packages so the compiled .js matches
377
+ * the freshly generated .ts source.
378
+ * 4. Apply known-issue source patches (e.g. null-safety fixes for fresh
379
+ * installs) and rebuild affected packages.
380
+ */
381
+ async regenerateManifestsAndRebuild(dir, emitter, fast) {
382
+ // In fast mode, quick-check manifests first. If they already look correct
383
+ // (no stale entity names), skip the expensive Steps 1-3 entirely.
384
+ if (fast) {
385
+ const manifestsClean = await this.quickCheckManifests(dir, emitter);
386
+ if (manifestsClean) {
387
+ emitter.Emit('log', {
388
+ Type: 'log',
389
+ Level: 'info',
390
+ Message: 'Fast mode: manifests look correct — skipping post-codegen rebuild steps 1-3.',
391
+ });
392
+ // Still apply known-issue patches (Step 4) — fast and essential.
393
+ await this.applyKnownIssuePatches(dir, emitter);
394
+ return;
395
+ }
396
+ emitter.Emit('log', {
397
+ Type: 'log',
398
+ Level: 'info',
399
+ Message: 'Fast mode: stale manifest content detected — falling back to full rebuild.',
400
+ });
401
+ }
402
+ // Step 1: Force-rebuild codegen output packages.
403
+ // After `mj codegen`, packages like MJCoreEntities have regenerated
404
+ // .ts source, but turbo may serve stale cached .d.ts if the hash is
405
+ // unchanged. Force-rebuilding ensures .d.ts exports are current.
406
+ emitter.Emit('step:progress', {
407
+ Type: 'step:progress',
408
+ Phase: 'codegen',
409
+ Message: 'Post-codegen step 1/4: force-rebuilding codegen output packages...',
410
+ });
411
+ await this.forceRebuildCodegenOutputPackages(dir, emitter);
412
+ // Step 2: Regenerate manifest .ts files.
413
+ // The manifest generator scans source for @RegisterClass decorators and
414
+ // verifies them against .d.ts exports. Step 1 ensures .d.ts is current.
415
+ emitter.Emit('step:progress', {
416
+ Type: 'step:progress',
417
+ Phase: 'codegen',
418
+ Message: 'Post-codegen step 2/4: regenerating class registration manifests...',
419
+ });
420
+ const manifestRegenOk = await this.regenerateManifests(dir, emitter);
421
+ // If manifest regeneration failed (e.g. mj CLI can't load the codegen
422
+ // command), fall back to directly patching the stale entity names in the
423
+ // manifest .ts files. This handles the common case where the only issue
424
+ // is the entity class rename (FooEntity → MJFooEntity).
425
+ if (!manifestRegenOk) {
426
+ await this.patchStaleManifestImports(dir, emitter);
427
+ }
428
+ // Diagnostic: verify manifest content isn't stale
429
+ await this.verifyManifestContent(dir, emitter);
430
+ // Step 3: Force-rebuild manifest packages.
431
+ // Manifest .ts files were just updated — must force-compile to .js.
432
+ emitter.Emit('step:progress', {
433
+ Type: 'step:progress',
434
+ Phase: 'codegen',
435
+ Message: 'Post-codegen step 3/4: force-rebuilding manifest packages...',
436
+ });
437
+ await this.forceRebuildManifestPackages(dir, emitter);
438
+ // Step 4: Apply known-issue patches.
439
+ // Proactively fix source-level issues (e.g. null-safety bugs) that only
440
+ // manifest on fresh installs with empty datasets/metadata.
441
+ emitter.Emit('step:progress', {
442
+ Type: 'step:progress',
443
+ Phase: 'codegen',
444
+ Message: 'Post-codegen step 4/4: applying known-issue patches...',
445
+ });
446
+ await this.applyKnownIssuePatches(dir, emitter);
447
+ }
448
+ /**
449
+ * Codegen output packages whose source vs dist timestamps must match
450
+ * for fast mode to skip the rebuild. If codegen regenerated the source
451
+ * (entity_subclasses.ts) but the compiled output (entity_subclasses.d.ts)
452
+ * is older, Steps 1-3 are needed.
453
+ */
454
+ static { this.CODEGEN_TIMESTAMP_CHECKS = [
455
+ {
456
+ SourceRelPath: 'packages/MJCoreEntities/src/generated/entity_subclasses.ts',
457
+ DistRelPath: 'packages/MJCoreEntities/dist/generated/entity_subclasses.d.ts',
458
+ },
459
+ {
460
+ SourceRelPath: 'packages/Actions/CoreActions/src/generated/action_subclasses.ts',
461
+ DistRelPath: 'packages/Actions/CoreActions/dist/generated/action_subclasses.d.ts',
462
+ },
463
+ ]; }
464
+ /**
465
+ * Quick-check whether the full post-codegen rebuild cycle (Steps 1-3)
466
+ * can be safely skipped.
467
+ *
468
+ * Returns true only if:
469
+ * 1. No codegen output source files are newer than their compiled dist
470
+ * (meaning codegen didn't regenerate them, or they've already been rebuilt).
471
+ * 2. No manifest files contain known stale entity names.
472
+ *
473
+ * If either condition fails, the full rebuild cycle is required.
474
+ */
475
+ async quickCheckManifests(dir, emitter) {
476
+ // Check 1: Are codegen output packages already compiled and up-to-date?
477
+ for (const check of CodeGenPhase.CODEGEN_TIMESTAMP_CHECKS) {
478
+ const srcTime = await this.fileSystem.GetModifiedTime(path.join(dir, check.SourceRelPath));
479
+ const distTime = await this.fileSystem.GetModifiedTime(path.join(dir, check.DistRelPath));
480
+ if (srcTime == null || distTime == null) {
481
+ emitter.Emit('step:progress', {
482
+ Type: 'step:progress',
483
+ Phase: 'codegen',
484
+ Message: `Fast mode check: missing file — ${srcTime == null ? check.SourceRelPath : check.DistRelPath}`,
485
+ });
486
+ return false;
487
+ }
488
+ if (srcTime > distTime) {
489
+ emitter.Emit('step:progress', {
490
+ Type: 'step:progress',
491
+ Phase: 'codegen',
492
+ Message: `Fast mode check: ${check.SourceRelPath} is newer than compiled output — rebuild needed.`,
493
+ });
494
+ return false;
495
+ }
496
+ }
497
+ // Check 2: Do manifest files contain known stale entity names?
498
+ for (const relPath of CodeGenPhase.MANIFEST_SOURCE_PATHS) {
499
+ const fullPath = path.join(dir, relPath);
500
+ try {
501
+ const content = await this.fileSystem.ReadText(fullPath);
502
+ const staleFound = CodeGenPhase.STALE_ENTITY_PATTERNS.filter(name => new RegExp(`\\b${name}\\b`).test(content));
503
+ if (staleFound.length > 0) {
504
+ emitter.Emit('step:progress', {
505
+ Type: 'step:progress',
506
+ Phase: 'codegen',
507
+ Message: `Fast mode check: ${relPath} contains stale names: ${staleFound.join(', ')}`,
508
+ });
509
+ return false;
510
+ }
511
+ }
512
+ catch {
513
+ return false;
514
+ }
515
+ }
516
+ return true;
517
+ }
518
+ /**
519
+ * Force-rebuild ALL packages whose source is generated by codegen.
520
+ * This ensures their compiled .d.ts exports and .js modules are current.
521
+ *
522
+ * Four packages have codegen-generated source in src/generated/:
523
+ * - @memberjunction/core-entities (entity_subclasses.ts)
524
+ * - mj_generatedentities (entity_subclasses.ts)
525
+ * - @memberjunction/core-actions (action_subclasses.ts)
526
+ * - mj_generatedactions (action_subclasses.ts)
527
+ *
528
+ * The manifest generator walks the dependency tree and imports from these
529
+ * packages. If their dist/ is stale (e.g. index.js imports a generated
530
+ * module that was regenerated but never compiled), manifest generation
531
+ * fails with ERR_MODULE_NOT_FOUND.
532
+ */
533
+ async forceRebuildCodegenOutputPackages(dir, emitter) {
534
+ const filters = [
535
+ '--filter=@memberjunction/core-entities',
536
+ '--filter=mj_generatedentities',
537
+ '--filter=@memberjunction/core-actions',
538
+ '--filter=mj_generatedactions',
539
+ ];
540
+ const result = await this.processRunner.Run('npx', ['turbo', 'build', '--force', '--log-order=stream', ...filters], {
541
+ Cwd: dir,
542
+ TimeoutMs: 600_000, // 10 minutes
543
+ OnStdout: (line) => {
544
+ emitter.Emit('step:progress', {
545
+ Type: 'step:progress',
546
+ Phase: 'codegen',
547
+ Message: line.trim(),
548
+ });
549
+ },
550
+ OnStderr: (line) => {
551
+ emitter.Emit('log', {
552
+ Type: 'log',
553
+ Level: 'verbose',
554
+ Message: `[codegen:force-rebuild-entities:stderr] ${line.trim()}`,
555
+ });
556
+ },
557
+ });
558
+ if (result.ExitCode !== 0 || result.TimedOut) {
559
+ emitter.Emit('warn', {
560
+ Type: 'warn',
561
+ Phase: 'codegen',
562
+ Message: `Force-rebuild of codegen output packages ${result.TimedOut ? 'timed out' : `failed (exit ${result.ExitCode})`}. Manifest generation may produce stale results.`,
563
+ });
564
+ return;
565
+ }
566
+ emitter.Emit('step:progress', {
567
+ Type: 'step:progress',
568
+ Phase: 'codegen',
569
+ Message: 'Codegen output packages force-rebuilt — .d.ts exports are current.',
570
+ });
571
+ }
572
+ /**
573
+ * Manifest packages and their build commands/directories.
574
+ * We build each package individually (bypassing turbo) because turbo's
575
+ * `--filter` resolves the full transitive dependency graph, which includes
576
+ * ng-core-entity-forms. That package contains stale generated entity forms
577
+ * (codegen just regenerated its source but hasn't compiled it yet), so it
578
+ * fails to build and turbo skips all packages that depend on it — including
579
+ * the very bootstrap packages we need to rebuild.
580
+ *
581
+ * Building directly with each package's own build command (tsc, ng-packagr)
582
+ * only requires the .d.ts files from direct TypeScript imports, which
583
+ * already exist from prior builds. This cleanly sidesteps the turbo issue.
584
+ */
585
+ static { this.MANIFEST_PACKAGE_BUILDS = [
586
+ {
587
+ Name: '@memberjunction/server-bootstrap',
588
+ RelativeDir: 'packages/ServerBootstrap',
589
+ },
590
+ {
591
+ Name: '@memberjunction/server-bootstrap-lite',
592
+ RelativeDir: 'packages/ServerBootstrapLite',
593
+ },
594
+ {
595
+ Name: '@memberjunction/ng-bootstrap',
596
+ RelativeDir: 'packages/Angular/Bootstrap',
597
+ },
598
+ ]; }
599
+ /**
600
+ * Force-rebuild ONLY the packages that contain class registration manifests.
601
+ * Builds each package individually using its own build command, bypassing
602
+ * turbo to avoid the ng-core-entity-forms transitive dependency failure.
603
+ */
604
+ async forceRebuildManifestPackages(dir, emitter) {
605
+ const failures = [];
606
+ for (const pkg of CodeGenPhase.MANIFEST_PACKAGE_BUILDS) {
607
+ const pkgDir = path.join(dir, pkg.RelativeDir);
608
+ emitter.Emit('step:progress', {
609
+ Type: 'step:progress',
610
+ Phase: 'codegen',
611
+ Message: `Building ${pkg.Name}...`,
612
+ });
613
+ // Run `npm run build` in the package directory. This invokes the
614
+ // package's own build script (tsc, ng-packagr, etc.) without turbo,
615
+ // so it won't pull in transitive dependencies that fail to build.
616
+ const result = await this.processRunner.Run('npm', ['run', 'build'], {
617
+ Cwd: pkgDir,
618
+ TimeoutMs: 300_000, // 5 minutes per package
619
+ OnStdout: (line) => {
620
+ emitter.Emit('step:progress', {
621
+ Type: 'step:progress',
622
+ Phase: 'codegen',
623
+ Message: `[${pkg.Name}] ${line.trim()}`,
624
+ });
625
+ },
626
+ OnStderr: (line) => {
627
+ emitter.Emit('log', {
628
+ Type: 'log',
629
+ Level: 'verbose',
630
+ Message: `[codegen:force-rebuild-manifests:stderr] [${pkg.Name}] ${line.trim()}`,
631
+ });
632
+ },
633
+ });
634
+ if (result.TimedOut || result.ExitCode !== 0) {
635
+ const reason = result.TimedOut ? 'timed out' : `exit ${result.ExitCode}`;
636
+ failures.push(`${pkg.Name} (${reason})`);
637
+ emitter.Emit('warn', {
638
+ Type: 'warn',
639
+ Phase: 'codegen',
640
+ Message: `Build of ${pkg.Name} ${reason}. Attempting remaining packages...`,
641
+ });
642
+ }
643
+ }
644
+ if (failures.length > 0) {
645
+ emitter.Emit('warn', {
646
+ Type: 'warn',
647
+ Phase: 'codegen',
648
+ Message: `Force-rebuild of manifest packages partially failed: ${failures.join('; ')}. MJAPI/Explorer may fail to start.`,
649
+ });
650
+ return;
651
+ }
652
+ emitter.Emit('step:progress', {
653
+ Type: 'step:progress',
654
+ Phase: 'codegen',
655
+ Message: 'Manifest packages force-rebuilt successfully.',
656
+ });
657
+ }
658
+ /**
659
+ * Regenerate class registration manifest `.ts` files by running `npm run mj:manifest`.
660
+ *
661
+ * The manifest generator scans source for `@RegisterClass` decorators, verifies
662
+ * them against `.d.ts` exports (from Step 1), and emits updated manifest files
663
+ * with static import paths that prevent tree-shaking.
664
+ *
665
+ * @param dir - Repo root directory.
666
+ * @param emitter - Event emitter for progress and warning reporting.
667
+ * @returns `true` if manifest regeneration succeeded, `false` if it failed or timed out.
668
+ */
669
+ async regenerateManifests(dir, emitter) {
670
+ const result = await this.processRunner.Run('npm', ['run', 'mj:manifest'], {
671
+ Cwd: dir,
672
+ TimeoutMs: 300_000, // 5 minutes
673
+ OnStdout: (line) => {
674
+ emitter.Emit('step:progress', {
675
+ Type: 'step:progress',
676
+ Phase: 'codegen',
677
+ Message: line.trim(),
678
+ });
679
+ },
680
+ OnStderr: (line) => {
681
+ emitter.Emit('log', {
682
+ Type: 'log',
683
+ Level: 'verbose',
684
+ Message: `[codegen:manifest:stderr] ${line.trim()}`,
685
+ });
686
+ },
687
+ });
688
+ if (result.TimedOut) {
689
+ emitter.Emit('warn', {
690
+ Type: 'warn',
691
+ Phase: 'codegen',
692
+ Message: 'Manifest regeneration timed out. Will attempt to patch stale imports directly.',
693
+ });
694
+ return false;
695
+ }
696
+ if (result.ExitCode !== 0) {
697
+ // Include last few lines of stderr to help diagnose the failure
698
+ const stderrTail = this.lastNLines(result.Stderr, 5).trim();
699
+ const detail = stderrTail ? ` (${stderrTail})` : '';
700
+ emitter.Emit('warn', {
701
+ Type: 'warn',
702
+ Phase: 'codegen',
703
+ Message: `Manifest regeneration failed (exit ${result.ExitCode})${detail}. Will attempt to patch stale imports directly.`,
704
+ });
705
+ return false;
706
+ }
707
+ emitter.Emit('step:progress', {
708
+ Type: 'step:progress',
709
+ Phase: 'codegen',
710
+ Message: 'Manifest regeneration completed (exit 0).',
711
+ });
712
+ return true;
713
+ }
714
+ /**
715
+ * Diagnostic: read each manifest .ts file and check for known stale entity
716
+ * import names. Emits warnings with detailed info to help troubleshoot
717
+ * persistent stale-manifest issues.
718
+ */
719
+ async verifyManifestContent(dir, emitter) {
720
+ for (const relPath of CodeGenPhase.MANIFEST_SOURCE_PATHS) {
721
+ const fullPath = path.join(dir, relPath);
722
+ try {
723
+ const content = await this.fileSystem.ReadText(fullPath);
724
+ // Use word-boundary regex to avoid false positives from substring
725
+ // matches (e.g. "AIActionEntity" inside "MJAIActionEntity" — no
726
+ // \b between J and A since both are word characters).
727
+ const staleFound = CodeGenPhase.STALE_ENTITY_PATTERNS.filter(name => new RegExp(`\\b${name}\\b`).test(content));
728
+ const lineCount = content.split('\n').length;
729
+ const importCount = (content.match(/^import /gm) || []).length;
730
+ if (staleFound.length > 0) {
731
+ emitter.Emit('warn', {
732
+ Type: 'warn',
733
+ Phase: 'codegen',
734
+ Message: `Manifest diagnostic: ${relPath} (${lineCount} lines, ${importCount} imports) contains stale entity names: ${staleFound.join(', ')}`,
735
+ });
736
+ }
737
+ else {
738
+ emitter.Emit('log', {
739
+ Type: 'log',
740
+ Level: 'verbose',
741
+ Message: `Manifest diagnostic: ${relPath} — OK (${lineCount} lines, ${importCount} imports, no stale names detected)`,
742
+ });
743
+ }
744
+ }
745
+ catch {
746
+ emitter.Emit('log', {
747
+ Type: 'log',
748
+ Level: 'verbose',
749
+ Message: `Manifest diagnostic: ${relPath} — could not read file`,
750
+ });
751
+ }
752
+ }
753
+ }
754
+ // ---------------------------------------------------------------------------
755
+ // Fallback: directly patch stale entity names in manifest .ts files
756
+ // ---------------------------------------------------------------------------
757
+ /**
758
+ * When `mj codegen manifest` fails, this method directly patches the
759
+ * manifest .ts files by adding the "MJ" prefix to entity class names
760
+ * that are missing it.
761
+ *
762
+ * The 5.0/5.1 entity rename added an "MJ" prefix to all core entity classes
763
+ * (e.g. AIActionEntity → MJAIActionEntity). The pre-built manifest .ts files
764
+ * from the release zip may still reference the old names.
765
+ *
766
+ * Strategy: read entity_subclasses.ts (regenerated by codegen) to build an
767
+ * exact old→new rename map. Only names that have a corresponding MJ-prefixed
768
+ * class in entity_subclasses.ts are renamed. This avoids touching server
769
+ * entity classes (e.g. ApplicationEntityServerEntity) or extended classes
770
+ * (e.g. EntityEntityExtended) that legitimately don't have the MJ prefix.
771
+ */
772
+ async patchStaleManifestImports(dir, emitter) {
773
+ // Build rename map from entity_subclasses.ts source. After codegen + Step 1,
774
+ // this file contains all MJ-prefixed entity class definitions.
775
+ const renameMap = await this.buildEntityRenameMap(dir, emitter);
776
+ if (renameMap.size === 0) {
777
+ emitter.Emit('warn', {
778
+ Type: 'warn',
779
+ Phase: 'codegen',
780
+ Message: 'Could not build entity rename map from entity_subclasses.ts. Skipping manifest patching.',
781
+ });
782
+ return;
783
+ }
784
+ emitter.Emit('step:progress', {
785
+ Type: 'step:progress',
786
+ Phase: 'codegen',
787
+ Message: `Built rename map with ${renameMap.size} entity class mappings from entity_subclasses.ts.`,
788
+ });
789
+ for (const relPath of CodeGenPhase.MANIFEST_SOURCE_PATHS) {
790
+ const fullPath = path.join(dir, relPath);
791
+ try {
792
+ await this.patchSingleManifest(fullPath, renameMap, relPath, emitter);
793
+ }
794
+ catch {
795
+ emitter.Emit('warn', {
796
+ Type: 'warn',
797
+ Phase: 'codegen',
798
+ Message: `Failed to patch manifest: ${relPath}`,
799
+ });
800
+ }
801
+ }
802
+ }
803
+ /**
804
+ * Read entity_subclasses.ts source and build a map of old→new entity class
805
+ * names. For each `export class MJFooEntity`, we add FooEntity → MJFooEntity.
806
+ *
807
+ * Tries the source .ts first (most up-to-date after codegen), then falls
808
+ * back to the compiled .d.ts.
809
+ */
810
+ async buildEntityRenameMap(dir, emitter) {
811
+ const renameMap = new Map();
812
+ // Try source first, then compiled .d.ts as fallback
813
+ const candidates = [
814
+ path.join(dir, 'packages', 'MJCoreEntities', 'src', 'generated', 'entity_subclasses.ts'),
815
+ path.join(dir, 'packages', 'MJCoreEntities', 'dist', 'generated', 'entity_subclasses.d.ts'),
816
+ ];
817
+ let content = '';
818
+ for (const filePath of candidates) {
819
+ try {
820
+ content = await this.fileSystem.ReadText(filePath);
821
+ if (content.length > 0)
822
+ break;
823
+ }
824
+ catch {
825
+ // try next candidate
826
+ }
827
+ }
828
+ if (!content)
829
+ return renameMap;
830
+ // Match class definitions: "export class MJFooEntity" or "export declare class MJFooEntity"
831
+ const classPattern = /export\s+(?:declare\s+)?class\s+(MJ\w+Entity)\b/g;
832
+ let match;
833
+ while ((match = classPattern.exec(content)) !== null) {
834
+ const newName = match[1]; // e.g. MJAIActionEntity
835
+ const oldName = newName.slice(2); // e.g. AIActionEntity (strip "MJ" prefix)
836
+ renameMap.set(oldName, newName);
837
+ }
838
+ return renameMap;
839
+ }
840
+ /**
841
+ * Patch a single manifest .ts file using the entity rename map.
842
+ * Only renames class names that have a known MJ-prefixed counterpart
843
+ * in entity_subclasses.ts.
844
+ */
845
+ async patchSingleManifest(fullPath, renameMap, relPath, emitter) {
846
+ let content = await this.fileSystem.ReadText(fullPath);
847
+ const replacements = [];
848
+ // Check which old names from the rename map appear in the manifest.
849
+ // Use word boundaries so \bAIActionEntity\b won't match inside
850
+ // MJAIActionEntity (no word boundary between J and A).
851
+ for (const [oldName, newName] of renameMap) {
852
+ const wordPattern = new RegExp(`\\b${oldName}\\b`, 'g');
853
+ if (wordPattern.test(content)) {
854
+ replacements.push({ OldName: oldName, NewName: newName });
855
+ }
856
+ }
857
+ if (replacements.length === 0) {
858
+ emitter.Emit('step:progress', {
859
+ Type: 'step:progress',
860
+ Phase: 'codegen',
861
+ Message: `Manifest patch: ${relPath} — no stale entity names found to patch.`,
862
+ });
863
+ return;
864
+ }
865
+ // Apply replacements, longest first to avoid partial matches.
866
+ replacements.sort((a, b) => b.OldName.length - a.OldName.length);
867
+ for (const { OldName, NewName } of replacements) {
868
+ const wordPattern = new RegExp(`\\b${OldName}\\b`, 'g');
869
+ content = content.replace(wordPattern, NewName);
870
+ }
871
+ await this.fileSystem.WriteText(fullPath, content);
872
+ const preview = replacements.slice(0, 3).map(r => `${r.OldName}→${r.NewName}`).join(', ');
873
+ const extra = replacements.length > 3 ? `, +${replacements.length - 3} more` : '';
874
+ emitter.Emit('warn', {
875
+ Type: 'warn',
876
+ Phase: 'codegen',
877
+ Message: `Manifest patch: ${relPath} — replaced ${replacements.length} stale entity names (${preview}${extra})`,
878
+ });
879
+ }
880
+ // ---------------------------------------------------------------------------
881
+ // Known-issue patching — proactive source-level fixes for fresh installs
882
+ // ---------------------------------------------------------------------------
883
+ /**
884
+ * Registry of known issues that affect fresh installs. Each entry describes
885
+ * a source-level bug (typically null-safety issues in code that assumes
886
+ * non-empty datasets) and how to patch it.
887
+ *
888
+ * When a new issue is discovered during fresh-install testing, add an entry
889
+ * here rather than modifying the source package — this keeps the fix
890
+ * localized to the installer and avoids touching upstream code.
891
+ */
892
+ static { this.KNOWN_ISSUE_PATCHES = [
893
+ {
894
+ Id: 'resource-permission-engine-null-safety',
895
+ Description: 'ResourcePermissionEngine._ResourceTypes and _Permissions may be undefined on fresh installs ' +
896
+ 'with empty datasets. Add null-safe access to prevent "can\'t access property ResourceTypes" errors.',
897
+ RelativePath: 'packages/MJCoreEntities/src/custom/ResourcePermissions/ResourcePermissionEngine.ts',
898
+ PackageRelativeDir: 'packages/MJCoreEntities',
899
+ NeedsPatch: (content) => content.includes('this._ResourceTypes.ResourceTypes') &&
900
+ !content.includes('this._ResourceTypes?.ResourceTypes'),
901
+ Apply: (content) => content
902
+ .replace('return this._ResourceTypes.ResourceTypes;', 'return this._ResourceTypes?.ResourceTypes ?? [];')
903
+ .replace(/return this\._Permissions;/, 'return this._Permissions ?? [];'),
904
+ },
905
+ ]; }
906
+ /**
907
+ * Step 4 of post-codegen fixup: apply known source-level patches to the
908
+ * fresh install's files and rebuild any affected packages.
909
+ *
910
+ * This handles issues like null-safety bugs that only manifest on fresh
911
+ * installs (empty datasets, missing metadata, etc.) without requiring
912
+ * changes to the upstream source packages.
913
+ */
914
+ async applyKnownIssuePatches(dir, emitter) {
915
+ const packagesToRebuild = new Set();
916
+ let appliedCount = 0;
917
+ for (const patch of CodeGenPhase.KNOWN_ISSUE_PATCHES) {
918
+ const fullPath = path.join(dir, patch.RelativePath);
919
+ try {
920
+ const content = await this.fileSystem.ReadText(fullPath);
921
+ if (patch.NeedsPatch(content)) {
922
+ const patched = patch.Apply(content);
923
+ await this.fileSystem.WriteText(fullPath, patched);
924
+ packagesToRebuild.add(patch.PackageRelativeDir);
925
+ appliedCount++;
926
+ emitter.Emit('warn', {
927
+ Type: 'warn',
928
+ Phase: 'codegen',
929
+ Message: `Known-issue patch applied: ${patch.Id} (${patch.RelativePath})`,
930
+ });
931
+ }
932
+ }
933
+ catch {
934
+ emitter.Emit('log', {
935
+ Type: 'log',
936
+ Level: 'verbose',
937
+ Message: `Known-issue patch ${patch.Id}: could not read ${patch.RelativePath}, skipping.`,
938
+ });
939
+ }
940
+ }
941
+ if (appliedCount === 0) {
942
+ emitter.Emit('step:progress', {
943
+ Type: 'step:progress',
944
+ Phase: 'codegen',
945
+ Message: 'Known-issue patches: no patches needed (all files already up-to-date).',
946
+ });
947
+ return;
948
+ }
949
+ emitter.Emit('step:progress', {
950
+ Type: 'step:progress',
951
+ Phase: 'codegen',
952
+ Message: `Applied ${appliedCount} known-issue patch(es). Rebuilding ${packagesToRebuild.size} affected package(s)...`,
953
+ });
954
+ // Rebuild each affected package
955
+ for (const pkgRelDir of packagesToRebuild) {
956
+ await this.rebuildSinglePackage(dir, pkgRelDir, emitter);
957
+ }
958
+ }
959
+ /**
960
+ * Rebuild a single package by running `npm run build` in its directory.
961
+ */
962
+ async rebuildSinglePackage(dir, pkgRelDir, emitter) {
963
+ const pkgDir = path.join(dir, pkgRelDir);
964
+ emitter.Emit('step:progress', {
965
+ Type: 'step:progress',
966
+ Phase: 'codegen',
967
+ Message: `Rebuilding ${pkgRelDir}...`,
968
+ });
969
+ const result = await this.processRunner.Run('npm', ['run', 'build'], {
970
+ Cwd: pkgDir,
971
+ TimeoutMs: 300_000, // 5 minutes
972
+ OnStdout: (line) => {
973
+ emitter.Emit('step:progress', {
974
+ Type: 'step:progress',
975
+ Phase: 'codegen',
976
+ Message: `[${pkgRelDir}] ${line.trim()}`,
977
+ });
978
+ },
979
+ OnStderr: (line) => {
980
+ emitter.Emit('log', {
981
+ Type: 'log',
982
+ Level: 'verbose',
983
+ Message: `[codegen:known-issue-rebuild:stderr] [${pkgRelDir}] ${line.trim()}`,
984
+ });
985
+ },
986
+ });
987
+ if (result.TimedOut || result.ExitCode !== 0) {
988
+ const reason = result.TimedOut ? 'timed out' : `exit ${result.ExitCode}`;
989
+ emitter.Emit('warn', {
990
+ Type: 'warn',
991
+ Phase: 'codegen',
992
+ Message: `Rebuild of ${pkgRelDir} ${reason} after known-issue patching.`,
993
+ });
994
+ }
995
+ }
996
+ /**
997
+ * Run known-issue diagnostic checks against the target directory.
998
+ * Used by `mj doctor` to detect issues that the installer would
999
+ * automatically patch during a fresh install.
1000
+ *
1001
+ * Returns an array of diagnostic results — one per known issue that
1002
+ * was detected (or confirmed absent) in the target directory.
1003
+ */
1004
+ async RunKnownIssueChecks(dir, emitter) {
1005
+ const results = [];
1006
+ for (const patch of CodeGenPhase.KNOWN_ISSUE_PATCHES) {
1007
+ const fullPath = path.join(dir, patch.RelativePath);
1008
+ try {
1009
+ const content = await this.fileSystem.ReadText(fullPath);
1010
+ if (patch.NeedsPatch(content)) {
1011
+ results.push({
1012
+ Id: patch.Id,
1013
+ Status: 'needs_patch',
1014
+ Description: patch.Description,
1015
+ RelativePath: patch.RelativePath,
1016
+ });
1017
+ emitter.Emit('diagnostic', {
1018
+ Type: 'diagnostic',
1019
+ Check: `Known issue: ${patch.Id}`,
1020
+ Status: 'warn',
1021
+ Message: patch.Description,
1022
+ SuggestedFix: `Run "mj install" to auto-patch, or manually edit ${patch.RelativePath}`,
1023
+ });
1024
+ }
1025
+ else {
1026
+ results.push({
1027
+ Id: patch.Id,
1028
+ Status: 'ok',
1029
+ Description: patch.Description,
1030
+ RelativePath: patch.RelativePath,
1031
+ });
1032
+ emitter.Emit('diagnostic', {
1033
+ Type: 'diagnostic',
1034
+ Check: `Known issue: ${patch.Id}`,
1035
+ Status: 'pass',
1036
+ Message: `${patch.Id}: not present or already patched`,
1037
+ });
1038
+ }
1039
+ }
1040
+ catch {
1041
+ results.push({
1042
+ Id: patch.Id,
1043
+ Status: 'skipped',
1044
+ Description: patch.Description,
1045
+ RelativePath: patch.RelativePath,
1046
+ });
1047
+ emitter.Emit('diagnostic', {
1048
+ Type: 'diagnostic',
1049
+ Check: `Known issue: ${patch.Id}`,
1050
+ Status: 'info',
1051
+ Message: `${patch.Id}: file not found (${patch.RelativePath}), skipping`,
1052
+ });
1053
+ }
1054
+ }
1055
+ return results;
1056
+ }
1057
+ // ---------------------------------------------------------------------------
1058
+ // Utilities
1059
+ // ---------------------------------------------------------------------------
1060
+ /**
1061
+ * Extract failed package names from turbo's output.
1062
+ * Turbo outputs lines like: "Failed: @memberjunction/ng-core-entity-forms#build"
1063
+ * Note: the "Failed:" summary goes to stdout, not stderr.
1064
+ */
1065
+ extractFailedTurboPackages(output) {
1066
+ const packages = [];
1067
+ const failedPattern = /Failed:\s+(@[^#\s]+)#build/g;
1068
+ let match;
1069
+ while ((match = failedPattern.exec(output)) !== null) {
1070
+ packages.push(match[1]);
1071
+ }
1072
+ return [...new Set(packages)];
1073
+ }
1074
+ /**
1075
+ * Extract the last N lines from a string (for truncated error output).
1076
+ *
1077
+ * @param text - The full text to extract from.
1078
+ * @param n - Number of trailing lines to keep.
1079
+ * @returns The last `n` lines joined with newlines.
1080
+ */
1081
+ lastNLines(text, n) {
1082
+ const lines = text.split('\n');
1083
+ return lines.slice(-n).join('\n');
1084
+ }
1085
+ }
1086
+ //# sourceMappingURL=CodeGenPhase.js.map