@memberjunction/installer 5.11.0 → 5.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/InstallerEngine.d.ts +83 -0
  2. package/dist/InstallerEngine.d.ts.map +1 -1
  3. package/dist/InstallerEngine.js +476 -3
  4. package/dist/InstallerEngine.js.map +1 -1
  5. package/dist/adapters/GitHubReleaseProvider.d.ts +66 -9
  6. package/dist/adapters/GitHubReleaseProvider.d.ts.map +1 -1
  7. package/dist/adapters/GitHubReleaseProvider.js +157 -29
  8. package/dist/adapters/GitHubReleaseProvider.js.map +1 -1
  9. package/dist/adapters/ProcessRunner.d.ts +6 -0
  10. package/dist/adapters/ProcessRunner.d.ts.map +1 -1
  11. package/dist/adapters/ProcessRunner.js +3 -0
  12. package/dist/adapters/ProcessRunner.js.map +1 -1
  13. package/dist/index.d.ts +2 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +3 -0
  16. package/dist/index.js.map +1 -1
  17. package/dist/logging/EventLogger.d.ts +105 -0
  18. package/dist/logging/EventLogger.d.ts.map +1 -0
  19. package/dist/logging/EventLogger.js +165 -0
  20. package/dist/logging/EventLogger.js.map +1 -0
  21. package/dist/logging/ReportGenerator.d.ts +175 -0
  22. package/dist/logging/ReportGenerator.d.ts.map +1 -0
  23. package/dist/logging/ReportGenerator.js +526 -0
  24. package/dist/logging/ReportGenerator.js.map +1 -0
  25. package/dist/models/InstallConfig.d.ts +5 -0
  26. package/dist/models/InstallConfig.d.ts.map +1 -1
  27. package/dist/models/InstallConfig.js +2 -1
  28. package/dist/models/InstallConfig.js.map +1 -1
  29. package/dist/models/InstallPlan.d.ts +17 -0
  30. package/dist/models/InstallPlan.d.ts.map +1 -1
  31. package/dist/models/InstallPlan.js.map +1 -1
  32. package/dist/phases/CodeGenPhase.d.ts +35 -2
  33. package/dist/phases/CodeGenPhase.d.ts.map +1 -1
  34. package/dist/phases/CodeGenPhase.js +128 -8
  35. package/dist/phases/CodeGenPhase.js.map +1 -1
  36. package/dist/phases/ConfigurePhase.d.ts +143 -8
  37. package/dist/phases/ConfigurePhase.d.ts.map +1 -1
  38. package/dist/phases/ConfigurePhase.js +378 -31
  39. package/dist/phases/ConfigurePhase.js.map +1 -1
  40. package/dist/phases/DependencyPhase.d.ts +40 -2
  41. package/dist/phases/DependencyPhase.d.ts.map +1 -1
  42. package/dist/phases/DependencyPhase.js +102 -5
  43. package/dist/phases/DependencyPhase.js.map +1 -1
  44. package/dist/phases/MigratePhase.d.ts +34 -6
  45. package/dist/phases/MigratePhase.d.ts.map +1 -1
  46. package/dist/phases/MigratePhase.js +48 -7
  47. package/dist/phases/MigratePhase.js.map +1 -1
  48. package/dist/phases/ScaffoldPhase.d.ts.map +1 -1
  49. package/dist/phases/ScaffoldPhase.js +20 -6
  50. package/dist/phases/ScaffoldPhase.js.map +1 -1
  51. package/package.json +1 -1
@@ -42,6 +42,11 @@ import { SmokeTestPhase } from './phases/SmokeTestPhase.js';
42
42
  import { InstallPlan } from './models/InstallPlan.js';
43
43
  import { InstallState } from './models/InstallState.js';
44
44
  import { InstallConfigDefaults, resolveFromEnvironment, loadConfigFile, mergeConfigs } from './models/InstallConfig.js';
45
+ import { EventLogger } from './logging/EventLogger.js';
46
+ import { ReportGenerator } from './logging/ReportGenerator.js';
47
+ import { FileSystemAdapter } from './adapters/FileSystemAdapter.js';
48
+ import { ProcessRunner } from './adapters/ProcessRunner.js';
49
+ import path from 'node:path';
45
50
  /**
46
51
  * Ordered list of all install phases in execution order.
47
52
  *
@@ -95,6 +100,10 @@ export class InstallerEngine {
95
100
  this.dependency = new DependencyPhase();
96
101
  this.codeGen = new CodeGenPhase();
97
102
  this.smokeTest = new SmokeTestPhase();
103
+ /** Event logger that captures all events for diagnostic reports. */
104
+ this.eventLogger = new EventLogger();
105
+ /** Report generator for producing diagnostic markdown files. */
106
+ this.reportGenerator = new ReportGenerator();
98
107
  /**
99
108
  * Resolved config accumulator — populated incrementally by the configure phase,
100
109
  * then consumed by all subsequent phases (database, migrate, smoke test, etc.).
@@ -193,8 +202,12 @@ export class InstallerEngine {
193
202
  const verbose = options?.Verbose ?? false;
194
203
  const yes = options?.Yes ?? false;
195
204
  const fast = options?.Fast ?? false;
205
+ // Attach event logger for diagnostic capture
206
+ this.eventLogger.Clear();
207
+ this.eventLogger.Attach(this.emitter);
196
208
  // Dry-run: the plan itself is the output, so Run is a no-op
197
209
  if (options?.DryRun) {
210
+ this.eventLogger.Detach();
198
211
  return {
199
212
  Success: true,
200
213
  DurationMs: 0,
@@ -321,23 +334,28 @@ export class InstallerEngine {
321
334
  Phase: phaseInfo.Id,
322
335
  Error: installerError,
323
336
  });
324
- // Stop on failure
325
- return {
337
+ // Stop on failure — auto-generate diagnostic report
338
+ const failResult = {
326
339
  Success: false,
327
340
  DurationMs: Date.now() - startTime,
328
341
  Warnings: warnings,
329
342
  PhasesCompleted: phasesCompleted,
330
343
  PhasesFailed: phasesFailed,
331
344
  };
345
+ await this.generateFailureReport(plan.Dir, state, failResult, config);
346
+ this.eventLogger.Detach();
347
+ return failResult;
332
348
  }
333
349
  }
334
- return {
350
+ const successResult = {
335
351
  Success: true,
336
352
  DurationMs: Date.now() - startTime,
337
353
  Warnings: warnings,
338
354
  PhasesCompleted: phasesCompleted,
339
355
  PhasesFailed: phasesFailed,
340
356
  };
357
+ this.eventLogger.Detach();
358
+ return successResult;
341
359
  }
342
360
  /**
343
361
  * Run diagnostics on an existing or target install directory.
@@ -352,6 +370,13 @@ export class InstallerEngine {
352
370
  */
353
371
  async Doctor(targetDir, options) {
354
372
  const config = { ...InstallConfigDefaults };
373
+ // ReportExtended implies Report
374
+ const extended = options?.ReportExtended ?? false;
375
+ const generateReport = extended || (options?.Report ?? false);
376
+ if (generateReport) {
377
+ this.eventLogger.Clear();
378
+ this.eventLogger.Attach(this.emitter);
379
+ }
355
380
  const diagnostics = await this.preflight.RunDiagnostics(targetDir, config, this.emitter);
356
381
  // Check for install state file
357
382
  const state = await InstallState.Load(targetDir);
@@ -386,6 +411,18 @@ export class InstallerEngine {
386
411
  });
387
412
  }
388
413
  }
414
+ // Run auth configuration validation checks (fast — always runs)
415
+ await this.runAuthValidationChecks(targetDir, diagnostics);
416
+ // Generate diagnostic report if requested
417
+ if (generateReport) {
418
+ const reportPath = await this.generateDoctorReport(targetDir, state, diagnostics, config, extended);
419
+ this.eventLogger.Detach();
420
+ this.emitter.Emit('log', {
421
+ Type: 'log',
422
+ Level: 'info',
423
+ Message: `Diagnostic report saved to: ${reportPath}`,
424
+ });
425
+ }
389
426
  return diagnostics;
390
427
  }
391
428
  /**
@@ -443,6 +480,7 @@ export class InstallerEngine {
443
480
  return this.executeSmokeTest(plan);
444
481
  }
445
482
  }
483
+ /** Run preflight checks (Node version, disk space, ports, SQL connectivity). */
446
484
  async executePreflight(plan, config) {
447
485
  const result = await this.preflight.Run({
448
486
  TargetDir: plan.Dir,
@@ -458,6 +496,7 @@ export class InstallerEngine {
458
496
  const warningMessages = result.Diagnostics.Warnings.map((w) => w.Message);
459
497
  return { Warnings: warningMessages };
460
498
  }
499
+ /** Download and extract the selected MemberJunction release from GitHub. */
461
500
  async executeScaffold(plan, config, yes) {
462
501
  const tag = plan.Tag === 'latest' ? undefined : plan.Tag;
463
502
  const result = await this.scaffold.Run({
@@ -473,6 +512,7 @@ export class InstallerEngine {
473
512
  });
474
513
  return { Warnings: [] };
475
514
  }
515
+ /** Gather config values (prompts or defaults) and generate `.env`, `mj.config.cjs`, and environment files. */
476
516
  async executeConfigure(plan, config, yes) {
477
517
  const result = await this.configure.Run({
478
518
  Dir: plan.Dir,
@@ -484,6 +524,7 @@ export class InstallerEngine {
484
524
  this.resolvedConfig = { ...this.resolvedConfig, ...result.Config };
485
525
  return { Warnings: [] };
486
526
  }
527
+ /** Generate SQL setup/validation scripts and optionally validate database connectivity. */
487
528
  async executeDatabase(plan, yes) {
488
529
  const result = await this.databaseProvision.Run({
489
530
  Dir: plan.Dir,
@@ -497,14 +538,17 @@ export class InstallerEngine {
497
538
  }
498
539
  return { Warnings: warnings };
499
540
  }
541
+ /** Run Flyway database migrations to create/update the `__mj` schema. */
500
542
  async executeMigrate(plan) {
501
543
  await this.migrate.Run({
502
544
  Dir: plan.Dir,
503
545
  Config: this.resolvedConfig,
504
546
  Emitter: this.emitter,
547
+ VersionTag: plan.Tag,
505
548
  });
506
549
  return { Warnings: [] };
507
550
  }
551
+ /** Patch npm scripts for OS compatibility (e.g. `cross-env` on Windows). */
508
552
  async executePlatform(plan) {
509
553
  const result = await this.platformCompat.Run({
510
554
  Dir: plan.Dir,
@@ -517,18 +561,22 @@ export class InstallerEngine {
517
561
  }
518
562
  return { Warnings: warnings };
519
563
  }
564
+ /** Run `npm install` and `npm run build` to install and compile all packages. */
520
565
  async executeDependencies(plan) {
521
566
  const result = await this.dependency.Run({
522
567
  Dir: plan.Dir,
568
+ Tag: plan.Tag,
523
569
  Emitter: this.emitter,
524
570
  });
525
571
  return { Warnings: result.Warnings };
526
572
  }
573
+ /** Run `mj codegen` to generate entities, manifests, and apply known-issue patches. */
527
574
  async executeCodeGen(plan, fast) {
528
575
  const result = await this.codeGen.Run({
529
576
  Dir: plan.Dir,
530
577
  Emitter: this.emitter,
531
578
  Fast: fast,
579
+ VersionTag: plan.Tag,
532
580
  });
533
581
  const warnings = [];
534
582
  if (result.RetryUsed) {
@@ -536,6 +584,7 @@ export class InstallerEngine {
536
584
  }
537
585
  return { Warnings: warnings };
538
586
  }
587
+ /** Start MJAPI and Explorer, verify they launch, then shut them down. */
539
588
  async executeSmokeTest(plan) {
540
589
  const result = await this.smokeTest.Run({
541
590
  Dir: plan.Dir,
@@ -552,6 +601,430 @@ export class InstallerEngine {
552
601
  return { Warnings: warnings };
553
602
  }
554
603
  // -------------------------------------------------------------------------
604
+ // Diagnostic report generation
605
+ // -------------------------------------------------------------------------
606
+ /**
607
+ * Auto-generate a diagnostic report after an install failure.
608
+ *
609
+ * Collects environment info, install state, sanitized config, and the
610
+ * full event log into a markdown file in the install directory.
611
+ *
612
+ * @param targetDir - Install directory where the report is saved.
613
+ * @param state - Current install checkpoint state.
614
+ * @param result - The install result with failure details.
615
+ * @param config - Resolved config (passwords will be redacted).
616
+ */
617
+ async generateFailureReport(targetDir, state, result, config) {
618
+ try {
619
+ const reportData = {
620
+ TargetDir: targetDir,
621
+ Trigger: 'install-failure',
622
+ InstallState: state.ToJSON(),
623
+ InstallResult: result,
624
+ Config: config,
625
+ EventLog: this.eventLogger.Entries,
626
+ };
627
+ // Try to get environment info from a quick preflight diagnostic
628
+ try {
629
+ const diagnostics = await this.preflight.RunDiagnostics(targetDir, config, this.emitter);
630
+ reportData.Environment = diagnostics.Environment;
631
+ reportData.Diagnostics = diagnostics;
632
+ }
633
+ catch {
634
+ // Preflight may fail — that's fine, we generate what we can
635
+ }
636
+ const reportPath = await this.reportGenerator.Generate(reportData);
637
+ this.emitter.Emit('log', {
638
+ Type: 'log',
639
+ Level: 'info',
640
+ Message: `Diagnostic report saved to: ${reportPath}`,
641
+ });
642
+ this.emitter.Emit('log', {
643
+ Type: 'log',
644
+ Level: 'info',
645
+ Message: 'Share this report when requesting installation support.',
646
+ });
647
+ }
648
+ catch {
649
+ // Report generation is best-effort — don't fail the install flow
650
+ }
651
+ }
652
+ /**
653
+ * Generate a diagnostic report for `mj doctor --report`.
654
+ *
655
+ * Collects config file snapshots, service startup logs, key file checks,
656
+ * and all other diagnostic data into a comprehensive markdown report.
657
+ *
658
+ * @param targetDir - Directory being diagnosed.
659
+ * @param state - Install state from checkpoint (if available).
660
+ * @param diagnostics - Completed diagnostic results.
661
+ * @param config - Current config (passwords will be redacted).
662
+ * @returns Absolute path to the generated report file.
663
+ */
664
+ async generateDoctorReport(targetDir, state, diagnostics, config, extended = false) {
665
+ // Check key files (fast — always included)
666
+ const keyFiles = await this.reportGenerator.CheckKeyFiles(targetDir);
667
+ const reportData = {
668
+ TargetDir: targetDir,
669
+ Trigger: 'doctor-report',
670
+ Environment: diagnostics.Environment,
671
+ Diagnostics: diagnostics,
672
+ Config: config,
673
+ EventLog: this.eventLogger.Entries,
674
+ };
675
+ if (state) {
676
+ reportData.InstallState = state.ToJSON();
677
+ }
678
+ // Extended report: add config file snapshots and service startup logs
679
+ if (extended) {
680
+ this.emitter.Emit('step:progress', {
681
+ Type: 'step:progress',
682
+ Phase: 'preflight',
683
+ Message: 'Collecting configuration files...',
684
+ });
685
+ reportData.ConfigFiles = await this.reportGenerator.SnapshotConfigFiles(targetDir);
686
+ this.emitter.Emit('step:progress', {
687
+ Type: 'step:progress',
688
+ Phase: 'preflight',
689
+ Message: 'Capturing service startup logs (this may take up to 3 minutes)...',
690
+ });
691
+ reportData.ServiceLogs = await this.captureServiceLogs(targetDir, config);
692
+ }
693
+ // Generate the base report, then inject key files section
694
+ let markdown = this.reportGenerator.Render(reportData);
695
+ // Replace placeholder key files section with actual results
696
+ const keyFilesSection = this.renderKeyFilesSection(keyFiles);
697
+ markdown = markdown.replace(/## Key Files\n\n_File existence checks will be populated when the report is generated with a target directory._/, keyFilesSection);
698
+ // Write final report
699
+ const fsModule = await import('node:fs/promises');
700
+ const filename = extended ? 'mj-diagnostic-report-extended.md' : 'mj-diagnostic-report.md';
701
+ const finalPath = path.join(targetDir, filename);
702
+ await fsModule.writeFile(finalPath, markdown, 'utf-8');
703
+ return finalPath;
704
+ }
705
+ /**
706
+ * Render the key files section with actual existence check results.
707
+ *
708
+ * @param keyFiles - Results from checking key file existence.
709
+ * @returns Markdown section string.
710
+ */
711
+ renderKeyFilesSection(keyFiles) {
712
+ const lines = [
713
+ '## Key Files',
714
+ '',
715
+ '| File | Description | Status |',
716
+ '|------|-------------|--------|',
717
+ ];
718
+ for (const file of keyFiles) {
719
+ const status = file.Exists ? 'Found' : '**MISSING**';
720
+ lines.push(`| ${file.Path} | ${file.Description} | ${status} |`);
721
+ }
722
+ return lines.join('\n');
723
+ }
724
+ // -------------------------------------------------------------------------
725
+ // Auth validation checks
726
+ // -------------------------------------------------------------------------
727
+ /**
728
+ * Validate authentication configuration across all config files.
729
+ *
730
+ * Checks for common misconfiguration patterns like AUTH_TYPE='msal' with
731
+ * empty CLIENT_ID, or .env and environment.ts having conflicting auth settings.
732
+ *
733
+ * @param targetDir - Install directory to check.
734
+ * @param diagnostics - Diagnostics object to add checks to.
735
+ */
736
+ async runAuthValidationChecks(targetDir, diagnostics) {
737
+ const fs = new FileSystemAdapter();
738
+ // Find and parse Explorer environment.ts
739
+ const envTsCandidates = [
740
+ path.join(targetDir, 'apps', 'MJExplorer', 'src', 'environments', 'environment.ts'),
741
+ path.join(targetDir, 'packages', 'MJExplorer', 'src', 'environments', 'environment.ts'),
742
+ ];
743
+ let authType = '';
744
+ let clientId = '';
745
+ let tenantId = '';
746
+ let auth0Domain = '';
747
+ let auth0ClientId = '';
748
+ let envTsFound = false;
749
+ for (const candidate of envTsCandidates) {
750
+ if (await fs.FileExists(candidate)) {
751
+ envTsFound = true;
752
+ const content = await fs.ReadText(candidate);
753
+ // Extract auth values from TypeScript (keys may be quoted or unquoted)
754
+ const authTypeMatch = content.match(/["']?AUTH_TYPE["']?\s*:\s*['"]([^'"]*)['"]/);
755
+ const clientIdMatch = content.match(/["']?CLIENT_ID["']?\s*:\s*['"]([^'"]*)['"]/);
756
+ const tenantIdMatch = content.match(/["']?TENANT_ID["']?\s*:\s*['"]([^'"]*)['"]/);
757
+ const auth0DomainMatch = content.match(/["']?AUTH0_DOMAIN["']?\s*:\s*['"]([^'"]*)['"]/);
758
+ const auth0ClientIdMatch = content.match(/["']?AUTH0_CLIENTID["']?\s*:\s*['"]([^'"]*)['"]/);
759
+ authType = authTypeMatch?.[1] ?? '';
760
+ clientId = clientIdMatch?.[1] ?? '';
761
+ tenantId = tenantIdMatch?.[1] ?? '';
762
+ auth0Domain = auth0DomainMatch?.[1] ?? '';
763
+ auth0ClientId = auth0ClientIdMatch?.[1] ?? '';
764
+ break;
765
+ }
766
+ }
767
+ if (!envTsFound) {
768
+ diagnostics.AddCheck({
769
+ Name: 'Explorer environment.ts',
770
+ Status: 'warn',
771
+ Message: 'Explorer environment.ts not found. MJExplorer may not be installed.',
772
+ SuggestedFix: 'Run "mj install" to generate environment files.',
773
+ });
774
+ this.emitDiagnostic('Explorer environment.ts', 'warn', 'Explorer environment.ts not found.');
775
+ return;
776
+ }
777
+ // Check AUTH_TYPE is set
778
+ if (!authType) {
779
+ diagnostics.AddCheck({
780
+ Name: 'Auth configuration',
781
+ Status: 'warn',
782
+ Message: 'AUTH_TYPE is not set in environment.ts.',
783
+ SuggestedFix: 'Set AUTH_TYPE to "msal" or "auth0" in environment.ts.',
784
+ });
785
+ this.emitDiagnostic('Auth configuration', 'warn', 'AUTH_TYPE is not set in environment.ts.');
786
+ return;
787
+ }
788
+ // MSAL auth checks
789
+ if (authType === 'msal') {
790
+ if (!clientId) {
791
+ diagnostics.AddCheck({
792
+ Name: 'MSAL CLIENT_ID',
793
+ Status: 'fail',
794
+ Message: 'AUTH_TYPE is "msal" but CLIENT_ID is empty. Browser will show Azure login errors.',
795
+ SuggestedFix: 'Set CLIENT_ID in environment.ts to your Azure AD Application (client) ID.',
796
+ });
797
+ this.emitDiagnostic('MSAL CLIENT_ID', 'fail', 'AUTH_TYPE is "msal" but CLIENT_ID is empty.');
798
+ }
799
+ else {
800
+ diagnostics.AddCheck({ Name: 'MSAL CLIENT_ID', Status: 'pass', Message: `CLIENT_ID is set (${clientId.slice(0, 8)}...)` });
801
+ this.emitDiagnostic('MSAL CLIENT_ID', 'pass', 'CLIENT_ID is configured.');
802
+ }
803
+ if (!tenantId) {
804
+ diagnostics.AddCheck({
805
+ Name: 'MSAL TENANT_ID',
806
+ Status: 'fail',
807
+ Message: 'AUTH_TYPE is "msal" but TENANT_ID is empty. Browser will show Azure login errors.',
808
+ SuggestedFix: 'Set TENANT_ID in environment.ts to your Azure AD Directory (tenant) ID.',
809
+ });
810
+ this.emitDiagnostic('MSAL TENANT_ID', 'fail', 'AUTH_TYPE is "msal" but TENANT_ID is empty.');
811
+ }
812
+ else {
813
+ diagnostics.AddCheck({ Name: 'MSAL TENANT_ID', Status: 'pass', Message: `TENANT_ID is set (${tenantId.slice(0, 8)}...)` });
814
+ this.emitDiagnostic('MSAL TENANT_ID', 'pass', 'TENANT_ID is configured.');
815
+ }
816
+ }
817
+ // Auth0 checks
818
+ if (authType === 'auth0') {
819
+ if (!auth0Domain) {
820
+ diagnostics.AddCheck({
821
+ Name: 'Auth0 Domain',
822
+ Status: 'fail',
823
+ Message: 'AUTH_TYPE is "auth0" but AUTH0_DOMAIN is empty.',
824
+ SuggestedFix: 'Set AUTH0_DOMAIN in environment.ts (e.g., "your-tenant.us.auth0.com").',
825
+ });
826
+ this.emitDiagnostic('Auth0 Domain', 'fail', 'AUTH_TYPE is "auth0" but AUTH0_DOMAIN is empty.');
827
+ }
828
+ else {
829
+ diagnostics.AddCheck({ Name: 'Auth0 Domain', Status: 'pass', Message: `AUTH0_DOMAIN is set (${auth0Domain})` });
830
+ this.emitDiagnostic('Auth0 Domain', 'pass', 'AUTH0_DOMAIN is configured.');
831
+ }
832
+ if (!auth0ClientId) {
833
+ diagnostics.AddCheck({
834
+ Name: 'Auth0 Client ID',
835
+ Status: 'fail',
836
+ Message: 'AUTH_TYPE is "auth0" but AUTH0_CLIENTID is empty.',
837
+ SuggestedFix: 'Set AUTH0_CLIENTID in environment.ts.',
838
+ });
839
+ this.emitDiagnostic('Auth0 Client ID', 'fail', 'AUTH_TYPE is "auth0" but AUTH0_CLIENTID is empty.');
840
+ }
841
+ else {
842
+ diagnostics.AddCheck({ Name: 'Auth0 Client ID', Status: 'pass', Message: 'AUTH0_CLIENTID is set.' });
843
+ this.emitDiagnostic('Auth0 Client ID', 'pass', 'AUTH0_CLIENTID is configured.');
844
+ }
845
+ }
846
+ // Cross-file consistency: check MJAPI .env has matching auth values
847
+ await this.checkApiAuthConsistency(targetDir, authType, fs, diagnostics);
848
+ }
849
+ /**
850
+ * Verify MJAPI .env has auth values consistent with Explorer's environment.ts.
851
+ */
852
+ async checkApiAuthConsistency(targetDir, explorerAuthType, fs, diagnostics) {
853
+ const envCandidates = [
854
+ path.join(targetDir, 'apps', 'MJAPI', '.env'),
855
+ path.join(targetDir, 'packages', 'MJAPI', '.env'),
856
+ path.join(targetDir, '.env'),
857
+ ];
858
+ for (const envPath of envCandidates) {
859
+ if (!(await fs.FileExists(envPath)))
860
+ continue;
861
+ const content = await fs.ReadText(envPath);
862
+ if (explorerAuthType === 'msal') {
863
+ const hasTenantId = /^TENANT_ID\s*=\s*\S+/m.test(content);
864
+ const hasClientId = /^WEB_CLIENT_ID\s*=\s*\S+/m.test(content);
865
+ if (!hasTenantId || !hasClientId) {
866
+ diagnostics.AddCheck({
867
+ Name: 'MJAPI auth consistency',
868
+ Status: 'warn',
869
+ Message: `Explorer uses MSAL but MJAPI .env (${path.basename(path.dirname(envPath))}) is missing TENANT_ID or WEB_CLIENT_ID.`,
870
+ SuggestedFix: 'Add TENANT_ID and WEB_CLIENT_ID to the MJAPI .env file with the same values as environment.ts.',
871
+ });
872
+ this.emitDiagnostic('MJAPI auth consistency', 'warn', 'MJAPI .env missing MSAL credentials.');
873
+ }
874
+ else {
875
+ diagnostics.AddCheck({ Name: 'MJAPI auth consistency', Status: 'pass', Message: 'MJAPI .env has MSAL credentials matching Explorer auth type.' });
876
+ this.emitDiagnostic('MJAPI auth consistency', 'pass', 'MJAPI .env MSAL credentials present.');
877
+ }
878
+ }
879
+ if (explorerAuthType === 'auth0') {
880
+ const hasDomain = /^AUTH0_DOMAIN\s*=\s*\S+/m.test(content);
881
+ const hasClientId = /^AUTH0_CLIENT_ID\s*=\s*\S+/m.test(content);
882
+ if (!hasDomain || !hasClientId) {
883
+ diagnostics.AddCheck({
884
+ Name: 'MJAPI auth consistency',
885
+ Status: 'warn',
886
+ Message: `Explorer uses Auth0 but MJAPI .env is missing AUTH0_DOMAIN or AUTH0_CLIENT_ID.`,
887
+ SuggestedFix: 'Add Auth0 credentials to the MJAPI .env file.',
888
+ });
889
+ this.emitDiagnostic('MJAPI auth consistency', 'warn', 'MJAPI .env missing Auth0 credentials.');
890
+ }
891
+ else {
892
+ diagnostics.AddCheck({ Name: 'MJAPI auth consistency', Status: 'pass', Message: 'MJAPI .env has Auth0 credentials.' });
893
+ this.emitDiagnostic('MJAPI auth consistency', 'pass', 'MJAPI .env Auth0 credentials present.');
894
+ }
895
+ }
896
+ return; // Only check first found .env
897
+ }
898
+ }
899
+ /** Emit a diagnostic event with the given parameters. */
900
+ emitDiagnostic(check, status, message, suggestedFix) {
901
+ this.emitter.Emit('diagnostic', {
902
+ Type: 'diagnostic',
903
+ Check: check,
904
+ Status: status,
905
+ Message: message,
906
+ SuggestedFix: suggestedFix,
907
+ });
908
+ }
909
+ // -------------------------------------------------------------------------
910
+ // Service log capture
911
+ // -------------------------------------------------------------------------
912
+ /** Readiness patterns for MJAPI startup detection. */
913
+ static { this.API_READY_PATTERNS = [/Server ready at/i]; }
914
+ /** Readiness patterns for Explorer startup detection. */
915
+ static { this.EXPLORER_READY_PATTERNS = [
916
+ /Compiled successfully/i,
917
+ /Application bundle generation complete/i,
918
+ /Local:\s+http/i,
919
+ ]; }
920
+ /** Patterns indicating fatal startup errors. */
921
+ static { this.FATAL_PATTERNS = [
922
+ /EADDRINUSE/i,
923
+ /Cannot find module/i,
924
+ /FATAL ERROR/i,
925
+ /Error: listen/i,
926
+ /Missing required environment variable/i,
927
+ ]; }
928
+ /**
929
+ * Briefly start MJAPI and Explorer to capture their startup output.
930
+ *
931
+ * Starts each service for up to 30 seconds, capturing stdout/stderr.
932
+ * Kills processes after capture. Used by `mj doctor --report` to detect
933
+ * runtime errors like missing modules, auth failures, or DB connectivity.
934
+ *
935
+ * @param targetDir - Install directory where `npm run start:api` is valid.
936
+ * @param config - Current config (for port detection).
937
+ * @returns Array of service log captures.
938
+ */
939
+ async captureServiceLogs(targetDir, config) {
940
+ const results = [];
941
+ const runner = new ProcessRunner();
942
+ // Only attempt if package.json exists (indicates a valid install)
943
+ const fsAdapter = new FileSystemAdapter();
944
+ const pkgJsonPath = path.join(targetDir, 'package.json');
945
+ if (!(await fsAdapter.FileExists(pkgJsonPath))) {
946
+ return results;
947
+ }
948
+ // Capture MJAPI startup
949
+ results.push(await this.captureServiceStartup(runner, targetDir, 'MJAPI', ['run', 'start:api'], InstallerEngine.API_READY_PATTERNS, config.APIPort ?? 4000));
950
+ // Capture Explorer startup
951
+ results.push(await this.captureServiceStartup(runner, targetDir, 'Explorer', ['run', 'start:explorer'], InstallerEngine.EXPLORER_READY_PATTERNS, config.ExplorerPort ?? 4200));
952
+ return results;
953
+ }
954
+ /**
955
+ * Start a single service, capture output for up to 30 seconds, then kill it.
956
+ */
957
+ async captureServiceStartup(runner, dir, label, args, readyPatterns, port) {
958
+ const output = [];
959
+ const startTime = Date.now();
960
+ let started = false;
961
+ let failureReason;
962
+ const captureTimeoutMs = 90_000; // 90 seconds max — MJAPI needs time for DB + metadata bootstrap
963
+ this.emitter.Emit('step:progress', {
964
+ Type: 'step:progress',
965
+ Phase: 'preflight',
966
+ Message: `Starting ${label} for log capture...`,
967
+ });
968
+ try {
969
+ // Create a promise that resolves when we detect readiness, fatal error, or timeout
970
+ let resolveCapture;
971
+ const capturePromise = new Promise((resolve) => { resolveCapture = resolve; });
972
+ const timer = setTimeout(() => resolveCapture(), captureTimeoutMs);
973
+ let childPid;
974
+ const processPromise = runner.Run('npm', args, {
975
+ Cwd: dir,
976
+ TimeoutMs: captureTimeoutMs + 10_000, // Process timeout slightly longer than capture
977
+ OnSpawn: (pid) => { childPid = pid; },
978
+ OnStdout: (line) => {
979
+ output.push(line.trimEnd());
980
+ // Check for readiness
981
+ if (readyPatterns.some((p) => p.test(line))) {
982
+ started = true;
983
+ resolveCapture();
984
+ }
985
+ // Check for fatal errors
986
+ if (InstallerEngine.FATAL_PATTERNS.some((p) => p.test(line))) {
987
+ failureReason = line.trim();
988
+ resolveCapture();
989
+ }
990
+ },
991
+ OnStderr: (line) => {
992
+ output.push(`[stderr] ${line.trimEnd()}`);
993
+ if (InstallerEngine.FATAL_PATTERNS.some((p) => p.test(line))) {
994
+ failureReason = line.trim();
995
+ resolveCapture();
996
+ }
997
+ },
998
+ });
999
+ // Wait for capture to complete (readiness, fatal error, or timeout)
1000
+ await capturePromise;
1001
+ clearTimeout(timer);
1002
+ // Kill the server process on the port, then kill the entire spawned
1003
+ // process tree (npm → turbo → node). Both are needed because killByPort
1004
+ // targets the listening server while killTree targets the parent wrapper.
1005
+ runner.killByPort(port);
1006
+ runner.killTree(childPid);
1007
+ // Suppress the expected rejection from killing
1008
+ processPromise.catch(() => { });
1009
+ }
1010
+ catch {
1011
+ // Process failed to start — capture the error
1012
+ failureReason = failureReason ?? 'Process failed to start';
1013
+ }
1014
+ this.emitter.Emit('step:progress', {
1015
+ Type: 'step:progress',
1016
+ Phase: 'preflight',
1017
+ Message: `${label} capture complete (${output.length} lines, ${started ? 'started' : 'did not start'}).`,
1018
+ });
1019
+ return {
1020
+ Service: label,
1021
+ Started: started,
1022
+ Output: output,
1023
+ DurationMs: Date.now() - startTime,
1024
+ FailureReason: failureReason,
1025
+ };
1026
+ }
1027
+ // -------------------------------------------------------------------------
555
1028
  // Helpers
556
1029
  // -------------------------------------------------------------------------
557
1030
  /**